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(soup): email filters (#354)

Sean Aye922e6a1ee5ad
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index aace85f8ca..910270c395 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -2835,13 +2835,17 @@ dependencies = [
"axum-extra",
"chrono",
"doppleganger",
+ "either",
+ "filter_ast",
"frecency",
+ "item_filters",
"macro_db_migrator",
"macro_user_id",
"model-entity",
"model-error-response",
"model_user",
"models_pagination",
+ "recursion",
"schemars",
"serde",
"serde_json",
diff --git a/rust/cloud-storage/email/Cargo.toml b/rust/cloud-storage/email/Cargo.toml
index 7f2c51c742..f9aa46b5dc 100644
--- a/rust/cloud-storage/email/Cargo.toml
+++ b/rust/cloud-storage/email/Cargo.toml
@@ -25,12 +25,16 @@ axum = { workspace = true, optional = true }
axum-extra = { workspace = true, optional = true }
chrono = { workspace = true, features = ["serde"] }
doppleganger = { workspace = true, features = ["chrono", "uuid"] }
+either = { workspace = true }
+filter_ast = { path = "../filter_ast" }
frecency = { path = "../frecency" }
+item_filters = { path = "../item_filters" }
macro_user_id = { path = "../macro_user_id" }
model-entity = { path = "../model-entity" }
model-error-response = { path = "../model-error-response", optional = true }
model_user = { path = "../model_user", optional = true }
models_pagination = { path = "../models_pagination" }
+recursion = { workspace = true }
schemars = { workspace = true, optional = true, features = ["uuid1"] }
serde = { workspace = true }
serde_with = { workspace = true }
@@ -43,5 +47,5 @@ utoipa = { workspace = true, optional = true }
uuid = { workspace = true }
[dev-dependencies]
-macro_db_migrator = { path = "../macro_db_migrator"}
+macro_db_migrator = { path = "../macro_db_migrator" }
serde_json = { workspace = true }
diff --git a/rust/cloud-storage/email/fixtures/email_dynamic_query.sql b/rust/cloud-storage/email/fixtures/email_dynamic_query.sql
new file mode 100644
index 0000000000..302edb0dc3
--- /dev/null
+++ b/rust/cloud-storage/email/fixtures/email_dynamic_query.sql
@@ -0,0 +1,162 @@
+-- Fixture for testing dynamic email query builder
+-- Sets up threads, messages, contacts, recipients, labels for comprehensive testing
+
+-- Insert test link
+INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)
+VALUES
+ ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'macro1', 'user1', '[email protected]', 'GMAIL', true, NOW(), NOW());
+
+-- Insert test contacts
+INSERT INTO email_contacts (id, link_id, email_address, name, created_at, updated_at)
+VALUES
+ ('40000001-0000-0000-0000-000000000001', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', 'John Doe', NOW(), NOW()),
+ ('40000002-0000-0000-0000-000000000002', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', 'Jane Smith', NOW(), NOW()),
+ ('40000003-0000-0000-0000-000000000003', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', 'Bob Johnson', NOW(), NOW()),
+ ('40000004-0000-0000-0000-000000000004', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '[email protected]', 'Alice Williams', NOW(), NOW());
+
+-- Insert test labels
+INSERT INTO email_labels (id, link_id, provider_label_id, name, message_list_visibility, label_list_visibility, type, created_at)
+VALUES
+ ('10000001-0000-0000-0000-000000000001', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'INBOX', 'INBOX', 'Show', 'LabelShow', 'System', NOW()),
+ ('10000002-0000-0000-0000-000000000002', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'IMPORTANT', 'IMPORTANT', 'Show', 'LabelShow', 'System', NOW()),
+ ('10000003-0000-0000-0000-000000000003', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'SENT', 'SENT', 'Show', 'LabelShow', 'System', NOW()),
+ ('10000004-0000-0000-0000-000000000004', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'STARRED', 'STARRED', 'Show', 'LabelShow', 'System', NOW()),
+ ('10000005-0000-0000-0000-000000000005', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'DRAFT', 'DRAFT', 'Show', 'LabelShow', 'System', NOW()),
+ ('10000006-0000-0000-0000-000000000006', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'TRASH', 'TRASH', 'Hide', 'LabelHide', 'System', NOW()),
+ ('10000007-0000-0000-0000-000000000007', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'Label_Work', 'Work', 'Show', 'LabelShow', 'User', NOW());
+
+-- Insert test threads
+INSERT INTO email_threads (
+ id, provider_id, link_id, inbox_visible, is_read,
+ latest_inbound_message_ts, latest_outbound_message_ts, latest_non_spam_message_ts,
+ created_at, updated_at
+)
+VALUES
+ -- Thread 1: Inbox, from [email protected]
+ ('20000001-0000-0000-0000-000000000001', 'thread1', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
+ true, false, '2024-01-15 10:00:00+00', NULL, '2024-01-15 10:00:00+00', NOW(), NOW()),
+
+ -- Thread 2: Sent, to [email protected]
+ ('20000002-0000-0000-0000-000000000002', 'thread2', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
+ false, true, NULL, '2024-01-14 09:00:00+00', '2024-01-14 09:00:00+00', NOW(), NOW()),
+
+ -- Thread 3: Draft from [email protected]
+ ('20000003-0000-0000-0000-000000000003', 'thread3', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
+ false, false, NULL, NULL, '2024-01-13 08:00:00+00', NOW(), NOW()),
+
+ -- Thread 4: Starred, from [email protected]
+ ('20000004-0000-0000-0000-000000000004', 'thread4', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
+ true, false, '2024-01-12 07:00:00+00', NULL, '2024-01-12 07:00:00+00', NOW(), NOW()),
+
+ -- Thread 5: Important inbox from [email protected]
+ ('20000005-0000-0000-0000-000000000005', 'thread5', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
+ true, false, '2024-01-11 06:00:00+00', NULL, '2024-01-11 06:00:00+00', NOW(), NOW()),
+
+ -- Thread 6: User label "Work", from [email protected]
+ ('20000006-0000-0000-0000-000000000006', 'thread6', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
+ false, false, NULL, NULL, '2024-01-10 05:00:00+00', NOW(), NOW()),
+
+ -- Thread 7: Inbox with CC to [email protected]
+ ('20000007-0000-0000-0000-000000000007', 'thread7', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
+ true, false, '2024-01-09 04:00:00+00', NULL, '2024-01-09 04:00:00+00', NOW(), NOW());
+
+-- Insert test messages
+INSERT INTO email_messages (
+ id, thread_id, link_id, provider_id, from_contact_id,
+ subject, snippet, internal_date_ts,
+ is_draft, is_sent, is_starred, is_read,
+ created_at, updated_at
+)
+VALUES
+ -- Message 1: Inbox from [email protected]
+ ('30000001-0000-0000-0000-000000000001', '20000001-0000-0000-0000-000000000001',
+ 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'msg1', '40000001-0000-0000-0000-000000000001',
+ 'Meeting Tomorrow', 'Lets meet tomorrow at 10am', '2024-01-15 10:00:00+00',
+ false, false, false, false, NOW(), NOW()),
+
+ -- Message 2: Sent to [email protected]
+ ('30000002-0000-0000-0000-000000000002', '20000002-0000-0000-0000-000000000002',
+ 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'msg2', '40000001-0000-0000-0000-000000000001',
+ 'Project Update', 'Here is the update', '2024-01-14 09:00:00+00',
+ false, true, false, true, NOW(), NOW()),
+
+ -- Message 3: Draft from [email protected]
+ ('30000003-0000-0000-0000-000000000003', '20000003-0000-0000-0000-000000000003',
+ 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'msg3', '40000003-0000-0000-0000-000000000003',
+ 'Draft Email', 'This is a draft', '2024-01-13 08:00:00+00',
+ true, false, false, false, NOW(), NOW()),
+
+ -- Message 4: Starred from [email protected]
+ ('30000004-0000-0000-0000-000000000004', '20000004-0000-0000-0000-000000000004',
+ 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'msg4', '40000004-0000-0000-0000-000000000004',
+ 'Important Info', 'Please review', '2024-01-12 07:00:00+00',
+ false, false, true, false, NOW(), NOW()),
+
+ -- Message 5: Important inbox from [email protected]
+ ('30000005-0000-0000-0000-000000000005', '20000005-0000-0000-0000-000000000005',
+ 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'msg5', '40000001-0000-0000-0000-000000000001',
+ 'Urgent: Action Required', 'Please respond ASAP', '2024-01-11 06:00:00+00',
+ false, false, false, false, NOW(), NOW()),
+
+ -- Message 6: User label "Work" from [email protected]
+ ('30000006-0000-0000-0000-000000000006', '20000006-0000-0000-0000-000000000006',
+ 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'msg6', '40000002-0000-0000-0000-000000000002',
+ 'Work Project', 'Quarterly review', '2024-01-10 05:00:00+00',
+ false, false, false, false, NOW(), NOW()),
+
+ -- Message 7: Inbox with CC to [email protected]
+ ('30000007-0000-0000-0000-000000000007', '20000007-0000-0000-0000-000000000007',
+ 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'msg7', '40000002-0000-0000-0000-000000000002',
+ 'Team Update', 'FYI for everyone', '2024-01-09 04:00:00+00',
+ false, false, false, false, NOW(), NOW());
+
+-- Insert message recipients
+INSERT INTO email_message_recipients (message_id, contact_id, recipient_type)
+VALUES
+ -- Message 1: To [email protected]
+ ('30000001-0000-0000-0000-000000000001', '40000004-0000-0000-0000-000000000004', 'TO'),
+
+ -- Message 2: To [email protected]
+ ('30000002-0000-0000-0000-000000000002', '40000002-0000-0000-0000-000000000002', 'TO'),
+
+ -- Message 3: To [email protected]
+ ('30000003-0000-0000-0000-000000000003', '40000004-0000-0000-0000-000000000004', 'TO'),
+
+ -- Message 4: To [email protected]
+ ('30000004-0000-0000-0000-000000000004', '40000001-0000-0000-0000-000000000001', 'TO'),
+
+ -- Message 5: To [email protected]
+ ('30000005-0000-0000-0000-000000000005', '40000004-0000-0000-0000-000000000004', 'TO'),
+
+ -- Message 6: To [email protected]
+ ('30000006-0000-0000-0000-000000000006', '40000001-0000-0000-0000-000000000001', 'TO'),
+
+ -- Message 7: To [email protected], CC [email protected]
+ ('30000007-0000-0000-0000-000000000007', '40000004-0000-0000-0000-000000000004', 'TO'),
+ ('30000007-0000-0000-0000-000000000007', '40000003-0000-0000-0000-000000000003', 'CC');
+
+-- Insert message-label relationships
+INSERT INTO email_message_labels (message_id, label_id)
+VALUES
+ -- Message 1: INBOX
+ ('30000001-0000-0000-0000-000000000001', '10000001-0000-0000-0000-000000000001'),
+
+ -- Message 2: SENT
+ ('30000002-0000-0000-0000-000000000002', '10000003-0000-0000-0000-000000000003'),
+
+ -- Message 3: DRAFT
+ ('30000003-0000-0000-0000-000000000003', '10000005-0000-0000-0000-000000000005'),
+
+ -- Message 4: STARRED, INBOX
+ ('30000004-0000-0000-0000-000000000004', '10000004-0000-0000-0000-000000000004'),
+ ('30000004-0000-0000-0000-000000000004', '10000001-0000-0000-0000-000000000001'),
+
+ -- Message 5: IMPORTANT, INBOX
+ ('30000005-0000-0000-0000-000000000005', '10000002-0000-0000-0000-000000000002'),
+ ('30000005-0000-0000-0000-000000000005', '10000001-0000-0000-0000-000000000001'),
+
+ -- Message 6: Work (user label)
+ ('30000006-0000-0000-0000-000000000006', '10000007-0000-0000-0000-000000000007'),
+
+ -- Message 7: INBOX
+ ('30000007-0000-0000-0000-000000000007', '10000001-0000-0000-0000-000000000001');
diff --git a/rust/cloud-storage/email/src/domain/models.rs b/rust/cloud-storage/email/src/domain/models.rs
index 689f153e89..54ab03e46e 100644
--- a/rust/cloud-storage/email/src/domain/models.rs
+++ b/rust/cloud-storage/email/src/domain/models.rs
@@ -1,5 +1,6 @@
use chrono::{DateTime, Utc};
use frecency::domain::models::{AggregateFrecency, FrecencyQueryErr};
+use item_filters::ast::{LiteralTree, email::EmailLiteral};
use macro_user_id::{email::EmailStr, user_id::MacroUserIdStr};
use models_pagination::{Identify, Query, SimpleSortMethod, SortOn};
use serde_with::{DeserializeFromStr, SerializeDisplay};
@@ -16,7 +17,7 @@ pub struct PreviewCursorQuery {
pub view: PreviewView,
pub link_id: Uuid,
pub limit: u32,
- pub query: Query<Uuid, SimpleSortMethod, ()>,
+ pub query: Query<Uuid, SimpleSortMethod, LiteralTree<EmailLiteral>>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, EnumString, Display)]
@@ -192,7 +193,7 @@ pub struct GetEmailsRequest {
pub link_id: Uuid,
pub macro_id: MacroUserIdStr<'static>,
pub limit: Option<u32>,
- pub query: Query<Uuid, SimpleSortMethod, ()>,
+ pub query: Query<Uuid, SimpleSortMethod, LiteralTree<EmailLiteral>>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
diff --git a/rust/cloud-storage/email/src/inbound/axum/router.rs b/rust/cloud-storage/email/src/inbound/axum/router.rs
index 79abdbb4eb..7ed2c89e04 100644
--- a/rust/cloud-storage/email/src/inbound/axum/router.rs
+++ b/rust/cloud-storage/email/src/inbound/axum/router.rs
@@ -86,13 +86,15 @@ async fn cursor_handler<T: EmailService>(
link_id: link.id,
macro_id: macro_user.macro_user_id,
limit: params.limit,
- query: cursor.into_query(
- params
- .sort_method
- .map(|v| v.into_simple_sort())
- .unwrap_or(SimpleSortMethod::ViewedUpdated),
- (),
- ),
+ query: cursor
+ .into_query(
+ params
+ .sort_method
+ .map(|v| v.into_simple_sort())
+ .unwrap_or(SimpleSortMethod::ViewedUpdated),
+ (),
+ )
+ .map_filter(|_| None),
})
.await?
.type_erase(),
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo.rs
index 73c0dacfb5..e93773e9fd 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo.rs
@@ -8,12 +8,15 @@ use crate::domain::{
};
use db_types::*;
use doppleganger::{Doppleganger, Mirror};
-use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
+use either::Either;
+use macro_user_id::user_id::MacroUserIdStr;
use sqlx::PgPool;
use uuid::Uuid;
mod db_types;
+mod dynamic;
mod queries;
+
#[cfg(test)]
mod test;
@@ -36,54 +39,67 @@ impl EmailRepo for EmailPgRepo {
query: PreviewCursorQuery,
user_id: MacroUserIdStr<'static>,
) -> Result<Vec<EmailThreadPreview>, Self::Err> {
- Ok(match query.view {
- PreviewView::StandardLabel(ref label) => match label {
- PreviewViewStandardLabel::Inbox => {
- queries::new_inbox::new_inbox_preview_cursor(
- &self.pool,
- &query,
- user_id.copied(),
- )
+ let PreviewCursorQuery {
+ view,
+ link_id,
+ limit,
+ query,
+ } = query;
+
+ let query = query.split_option();
+
+ Ok(match (view, query) {
+ (view, Either::Right(dynamic_query)) => {
+ dynamic::dynamic_email_thread_cursor(
+ &self.pool,
+ &link_id,
+ limit,
+ &view,
+ dynamic_query,
+ )
+ .await?
+ }
+ (PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox), Either::Left(query)) => {
+ queries::new_inbox::new_inbox_preview_cursor(&self.pool, &link_id, limit, &query)
.await?
- }
- PreviewViewStandardLabel::Sent => {
- queries::sent::sent_preview_cursor(&self.pool, &query, user_id.copied()).await?
- }
- PreviewViewStandardLabel::Drafts => {
- queries::draft::drafts_preview_cursor(&self.pool, &query, user_id.copied())
- .await?
- }
- PreviewViewStandardLabel::Starred => {
- queries::starred::starred_preview_cursor(&self.pool, &query, user_id.copied())
- .await?
- }
- PreviewViewStandardLabel::All => {
- queries::all_mail::all_mail_preview_cursor(&self.pool, &query, user_id.copied())
- .await?
- }
- PreviewViewStandardLabel::Important => {
- queries::important::important_preview_cursor(
- &self.pool,
- &query,
- user_id.copied(),
- )
+ }
+ (PreviewView::StandardLabel(PreviewViewStandardLabel::Sent), Either::Left(query)) => {
+ queries::sent::sent_preview_cursor(&self.pool, &link_id, limit, &query).await?
+ }
+ (PreviewView::StandardLabel(PreviewViewStandardLabel::Drafts), Either::Left(query)) => {
+ queries::draft::drafts_preview_cursor(&self.pool, &link_id, limit, &query).await?
+ }
+ (
+ PreviewView::StandardLabel(PreviewViewStandardLabel::Starred),
+ Either::Left(query),
+ ) => {
+ queries::starred::starred_preview_cursor(&self.pool, &link_id, limit, &query)
+ .await?
+ }
+ (PreviewView::StandardLabel(PreviewViewStandardLabel::All), Either::Left(query)) => {
+ queries::all_mail::all_mail_preview_cursor(&self.pool, &link_id, limit, &query)
.await?
- }
- PreviewViewStandardLabel::Other => {
- queries::other_inbox::other_inbox_preview_cursor(
- &self.pool,
- &query,
- user_id.copied(),
- )
+ }
+ (
+ PreviewView::StandardLabel(PreviewViewStandardLabel::Important),
+ Either::Left(query),
+ ) => {
+ queries::important::important_preview_cursor(&self.pool, &link_id, limit, &query)
.await?
- }
- },
- PreviewView::UserLabel(ref label_name) => {
+ }
+ (PreviewView::StandardLabel(PreviewViewStandardLabel::Other), Either::Left(query)) => {
+ queries::other_inbox::other_inbox_preview_cursor(
+ &self.pool, &link_id, limit, &query,
+ )
+ .await?
+ }
+ (PreviewView::UserLabel(label_name), Either::Left(query)) => {
queries::user_label::user_label_preview_cursor(
&self.pool,
+ &link_id,
+ limit,
&query,
- label_name,
- user_id.copied(),
+ &label_name,
)
.await?
}
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic.rs
new file mode 100644
index 0000000000..b663332f15
--- /dev/null
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic.rs
@@ -0,0 +1,437 @@
+//! This module exposes a dynamic query builder for email threads which can build specific
+//! email queries that filter content based on input AST (EmailLiteral).
+
+use super::db_types::*;
+use crate::domain::models::{PreviewView, PreviewViewStandardLabel};
+use filter_ast::Expr;
+use item_filters::ast::email::{Email, EmailLiteral};
+use models_pagination::{Query, SimpleSortMethod};
+use recursion::CollapsibleExt;
+use sqlx::{PgPool, Postgres, QueryBuilder, Row};
+use std::sync::Arc;
+use uuid::Uuid;
+
+#[cfg(test)]
+mod tests;
+
+/// Builds SQL WHERE conditions for email filters based on the AST.
+/// Returns a string to be appended to the WHERE clause.
+fn build_email_filter(ast: &Expr<EmailLiteral>) -> String {
+ let formatting = ast.collapse_frames(|frame| match frame {
+ filter_ast::ExprFrame::And(a, b) => format!("({a} AND {b})"),
+ filter_ast::ExprFrame::Or(a, b) => format!("({a} OR {b})"),
+ filter_ast::ExprFrame::Not(a) => format!("(NOT {a})"),
+
+ filter_ast::ExprFrame::Literal(EmailLiteral::Sender(email)) => match email {
+ Email::Complete(e) => format!(
+ r#"EXISTS (
+ SELECT 1 FROM email_contacts c
+ WHERE c.id = m.from_contact_id
+ AND LOWER(c.email_address) = LOWER('{}')
+ )"#,
+ e.0.as_ref()
+ ),
+ Email::Partial(s) => format!(
+ r#"EXISTS (
+ SELECT 1 FROM email_contacts c
+ WHERE c.id = m.from_contact_id
+ AND c.email_address ILIKE '%{}%'
+ )"#,
+ escape_like_pattern(&s)
+ ),
+ },
+
+ filter_ast::ExprFrame::Literal(EmailLiteral::Recipient(email)) => match email {
+ Email::Complete(e) => format!(
+ r#"EXISTS (
+ SELECT 1 FROM email_message_recipients mr
+ JOIN email_contacts c ON mr.contact_id = c.id
+ WHERE mr.message_id = m.id
+ AND mr.recipient_type = 'TO'
+ AND LOWER(c.email_address) = LOWER('{}')
+ )"#,
+ e.0.as_ref()
+ ),
+ Email::Partial(s) => format!(
+ r#"EXISTS (
+ SELECT 1 FROM email_message_recipients mr
+ JOIN email_contacts c ON mr.contact_id = c.id
+ WHERE mr.message_id = m.id
+ AND mr.recipient_type = 'TO'
+ AND c.email_address ILIKE '%{}%'
+ )"#,
+ escape_like_pattern(&s)
+ ),
+ },
+
+ filter_ast::ExprFrame::Literal(EmailLiteral::Cc(email)) => match email {
+ Email::Complete(e) => format!(
+ r#"EXISTS (
+ SELECT 1 FROM email_message_recipients mr
+ JOIN email_contacts c ON mr.contact_id = c.id
+ WHERE mr.message_id = m.id
+ AND mr.recipient_type = 'CC'
+ AND LOWER(c.email_address) = LOWER('{}')
+ )"#,
+ e.0.as_ref()
+ ),
+ Email::Partial(s) => format!(
+ r#"EXISTS (
+ SELECT 1 FROM email_message_recipients mr
+ JOIN email_contacts c ON mr.contact_id = c.id
+ WHERE mr.message_id = m.id
+ AND mr.recipient_type = 'CC'
+ AND c.email_address ILIKE '%{}%'
+ )"#,
+ escape_like_pattern(&s)
+ ),
+ },
+
+ filter_ast::ExprFrame::Literal(EmailLiteral::Bcc(email)) => match email {
+ Email::Complete(e) => format!(
+ r#"EXISTS (
+ SELECT 1 FROM email_message_recipients mr
+ JOIN email_contacts c ON mr.contact_id = c.id
+ WHERE mr.message_id = m.id
+ AND mr.recipient_type = 'BCC'
+ AND LOWER(c.email_address) = LOWER('{}')
+ )"#,
+ e.0.as_ref()
+ ),
+ Email::Partial(s) => format!(
+ r#"EXISTS (
+ SELECT 1 FROM email_message_recipients mr
+ JOIN email_contacts c ON mr.contact_id = c.id
+ WHERE mr.message_id = m.id
+ AND mr.recipient_type = 'BCC'
+ AND c.email_address ILIKE '%{}%'
+ )"#,
+ escape_like_pattern(&s)
+ ),
+ },
+ });
+
+ if formatting.is_empty() {
+ String::new()
+ } else {
+ format!(" AND {}", formatting)
+ }
+}
+
+/// Escapes special characters in LIKE patterns to prevent SQL injection
+fn escape_like_pattern(s: &str) -> String {
+ s.replace('\\', r"\\")
+ .replace('%', r"\%")
+ .replace('_', r"\_")
+}
+
+/// Builds thread-level WHERE conditions based on the view type
+fn build_view_thread_filter(view: &PreviewView) -> String {
+ match view {
+ PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox) => {
+ " AND t.inbox_visible = TRUE AND t.latest_inbound_message_ts IS NOT NULL".to_string()
+ }
+ PreviewView::StandardLabel(PreviewViewStandardLabel::Sent) => {
+ " AND t.latest_outbound_message_ts IS NOT NULL".to_string()
+ }
+ PreviewView::StandardLabel(PreviewViewStandardLabel::Drafts) => {
+ // Drafts are filtered at message level, no thread filter needed
+ String::new()
+ }
+ PreviewView::StandardLabel(PreviewViewStandardLabel::Starred) => {
+ // Starred threads are those with at least one starred message
+ // This is handled in a different way in the original query
+ String::new()
+ }
+ PreviewView::StandardLabel(PreviewViewStandardLabel::All) => {
+ // All mail, no additional filter
+ String::new()
+ }
+ PreviewView::StandardLabel(PreviewViewStandardLabel::Important) => {
+ // Important threads have at least one message with IMPORTANT label
+ String::new()
+ }
+ PreviewView::StandardLabel(PreviewViewStandardLabel::Other) => {
+ // Other inbox: inbox_visible but not in primary (no IMPORTANT or CATEGORY_PERSONAL)
+ " AND t.inbox_visible = TRUE".to_string()
+ }
+ PreviewView::UserLabel(_label_name) => {
+ // User labels are filtered at message level
+ String::new()
+ }
+ }
+}
+
+/// Builds message-level WHERE conditions based on the view type
+fn build_view_message_filter(view: &PreviewView, link_id_param: &str) -> String {
+ match view {
+ PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox) => {
+ " AND m.is_draft = FALSE".to_string()
+ }
+ PreviewView::StandardLabel(PreviewViewStandardLabel::Sent) => {
+ " AND m.is_sent = TRUE".to_string()
+ }
+ PreviewView::StandardLabel(PreviewViewStandardLabel::Drafts) => {
+ " AND m.is_draft = TRUE".to_string()
+ }
+ PreviewView::StandardLabel(PreviewViewStandardLabel::Starred) => {
+ " AND m.is_starred = TRUE AND m.is_draft = FALSE".to_string()
+ }
+ PreviewView::StandardLabel(PreviewViewStandardLabel::All) => {
+ // All mail, no specific message filter
+ String::new()
+ }
+ PreviewView::StandardLabel(PreviewViewStandardLabel::Important) => {
+ format!(
+ r#" AND EXISTS (
+ SELECT 1 FROM email_message_labels ml
+ JOIN email_labels l ON ml.label_id = l.id
+ WHERE ml.message_id = m.id
+ AND l.name = 'IMPORTANT'
+ AND l.link_id = {}
+ )"#,
+ link_id_param
+ )
+ }
+ PreviewView::StandardLabel(PreviewViewStandardLabel::Other) => {
+ format!(
+ r#" AND NOT EXISTS (
+ SELECT 1 FROM email_message_labels ml
+ JOIN email_labels l ON ml.label_id = l.id
+ WHERE ml.message_id = m.id
+ AND l.name IN ('IMPORTANT', 'CATEGORY_PERSONAL')
+ AND l.link_id = {}
+ )"#,
+ link_id_param
+ )
+ }
+ PreviewView::UserLabel(label_name) => {
+ format!(
+ r#" AND EXISTS (
+ SELECT 1 FROM email_message_labels ml
+ JOIN email_labels l ON ml.label_id = l.id
+ WHERE ml.message_id = m.id
+ AND l.name = '{}'
+ AND l.link_id = {}
+ )"#,
+ label_name, link_id_param
+ )
+ }
+ }
+}
+
+/// Returns the appropriate timestamp field to use for sorting based on the view
+fn get_sort_timestamp_field(view: &PreviewView) -> &'static str {
+ match view {
+ PreviewView::StandardLabel(PreviewViewStandardLabel::Sent) => {
+ "t.latest_outbound_message_ts"
+ }
+ PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox) => {
+ "t.latest_inbound_message_ts"
+ }
+ _ => "t.latest_non_spam_message_ts",
+ }
+}
+
+/// Builds a dynamic email thread query with filters applied
+fn build_query<'a>(
+ view: &'a PreviewView,
+ email_filter: &'a Expr<EmailLiteral>,
+) -> QueryBuilder<'a, Postgres> {
+ let sort_ts_field = get_sort_timestamp_field(view);
+ let view_thread_filter = build_view_thread_filter(view);
+ let view_message_filter = build_view_message_filter(view, "t.link_id");
+
+ let mut builder = sqlx::QueryBuilder::new(
+ r#"
+ SELECT
+ t.id,
+ t.provider_id,
+ t.inbox_visible,
+ t.is_read,
+ t.effective_ts AS sort_ts,
+ t.created_at,
+ t.updated_at,
+ t.viewed_at,
+ lmp.subject AS name,
+ lmp.snippet,
+ lmp.is_draft,
+ (
+ SELECT EXISTS (
+ SELECT 1
+ FROM email_messages m_imp
+ JOIN email_message_labels ml ON m_imp.id = ml.message_id
+ JOIN email_labels l ON ml.label_id = l.id
+ WHERE m_imp.thread_id = t.id
+ AND l.name = 'IMPORTANT'
+ AND l.link_id = t.link_id
+ )
+ ) AS is_important,
+ c.email_address AS sender_email,
+ c.name AS sender_name,
+ c.sfs_photo_url as sender_photo_url
+ FROM (
+ -- Step 1: Efficiently find and sort candidate threads
+ SELECT
+ t.id,
+ t.provider_id,
+ t.link_id,
+ t.inbox_visible,
+ t.is_read,
+ "#,
+ );
+
+ // Add the appropriate timestamp fields based on view
+ builder.push(format!(
+ r#"
+ {} AS created_at,
+ {} AS updated_at,
+ uh.updated_at AS viewed_at,
+ CASE $2 -- sort_method_str
+ WHEN 'viewed_at' THEN COALESCE(uh."updated_at", '1970-01-01 00:00:00+00')
+ WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, {})
+ ELSE {}
+ END AS effective_ts
+ FROM email_threads t
+ LEFT JOIN email_user_history uh ON uh.thread_id = t.id AND uh.link_id = t.link_id
+ WHERE
+ t.link_id = $1
+ "#,
+ sort_ts_field, sort_ts_field, sort_ts_field, sort_ts_field
+ ));
+
+ // Add view-specific thread filters
+ if !view_thread_filter.is_empty() {
+ builder.push(view_thread_filter);
+ }
+
+ builder.push(
+ r#"
+ -- Cursor logic
+ AND (($4::timestamptz IS NULL) OR (
+ CASE $2 -- sort_method_str
+ WHEN 'viewed_at' THEN COALESCE(uh."updated_at", '1970-01-01 00:00:00+00')
+ "#,
+ );
+
+ builder.push(format!(
+ r#"
+ WHEN 'viewed_updated' THEN COALESCE(uh.updated_at, {})
+ ELSE {}
+ END, t.id
+ ) < ($4::timestamptz, $5::uuid))
+ ORDER BY effective_ts DESC, t.updated_at DESC
+ LIMIT $3
+ ) AS t
+ -- Step 2: For each thread, find its latest message matching the filter
+ CROSS JOIN LATERAL (
+ SELECT
+ m.subject,
+ m.snippet,
+ m.from_contact_id,
+ m.is_draft
+ FROM email_messages m
+ WHERE m.thread_id = t.id
+ AND NOT EXISTS (
+ SELECT 1 FROM email_message_labels ml JOIN email_labels l ON ml.label_id = l.id
+ WHERE ml.message_id = m.id AND l.name = 'TRASH' AND l.link_id = t.link_id
+ )
+ "#,
+ sort_ts_field, sort_ts_field
+ ));
+
+ // Add view-specific message filters
+ if !view_message_filter.is_empty() {
+ builder.push(view_message_filter);
+ }
+
+ // Add dynamic email filters
+ let filter_sql = build_email_filter(email_filter);
+ if !filter_sql.is_empty() {
+ builder.push(filter_sql);
+ }
+
+ builder.push(
+ r#"
+ ORDER BY m.internal_date_ts DESC
+ LIMIT 1
+ ) AS lmp
+ -- Step 3: Join to get the sender's details
+ LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id
+ ORDER BY t.effective_ts DESC, t.updated_at DESC
+ "#,
+ );
+
+ builder
+}
+
+/// Fetches a paginated list of thread previews with dynamic filtering based on EmailLiteral AST.
+/// This function provides a flexible alternative to the hardcoded view-specific queries,
+/// combining view-specific filters (Inbox, Sent, Drafts, etc.) with custom email filters
+/// (sender, recipient, cc, bcc).
+///
+/// # Arguments
+/// * `pool` - Database connection pool
+/// * `query` - Preview cursor query containing view, link_id, limit, cursor, and filter AST
+///
+/// # Returns
+/// A vector of ThreadPreviewCursorDbRow matching the view and filter criteria
+///
+/// # Example
+/// ```ignore
+/// // Get drafts from a specific sender
+/// let query = PreviewCursorQuery {
+/// view: PreviewView::StandardLabel(PreviewViewStandardLabel::Drafts),
+/// link_id,
+/// limit: 50,
+/// query: Query::new(Expr::Literal(EmailLiteral::Sender(
+/// Email::Complete(EmailStr::parse_from_str("[email protected]").unwrap().into_owned())
+/// ))),
+/// };
+/// let results = dynamic_email_thread_cursor(&pool, &query).await?;
+/// ```
+#[tracing::instrument(skip(pool), err)]
+pub(crate) async fn dynamic_email_thread_cursor(
+ pool: &PgPool,
+ link_id: &Uuid,
+ limit: u32,
+ view: &PreviewView,
+ query: Query<Uuid, SimpleSortMethod, Arc<Expr<EmailLiteral>>>,
+) -> Result<Vec<ThreadPreviewCursorDbRow>, sqlx::Error> {
+ let query_limit = limit as i64;
+ let sort_method_str = query.sort_method().to_string();
+ let (cursor_id, cursor_timestamp) = query.vals();
+ let cursor_id_str = cursor_id.as_ref().map(|u| u.to_string());
+
+ // Extract email filter from query
+ let email_filter = query.filter();
+
+ build_query(view, email_filter)
+ .build()
+ .bind(link_id) // $1
+ .bind(sort_method_str) // $2
+ .bind(query_limit) // $3
+ .bind(cursor_timestamp) // $4
+ .bind(cursor_id_str) // $5
+ .try_map(|row| {
+ Ok(ThreadPreviewCursorDbRow {
+ id: row.try_get("id")?,
+ provider_id: row.try_get("provider_id")?,
+ inbox_visible: row.try_get("inbox_visible")?,
+ is_read: row.try_get("is_read")?,
+ is_draft: row.try_get("is_draft")?,
+ is_important: row.try_get("is_important")?,
+ sort_ts: row.try_get("sort_ts")?,
+ name: row.try_get("name")?,
+ snippet: row.try_get("snippet")?,
+ sender_email: row.try_get("sender_email")?,
+ sender_name: row.try_get("sender_name")?,
+ sender_photo_url: row.try_get("sender_photo_url")?,
+ viewed_at: row.try_get("viewed_at")?,
+ created_at: row.try_get("created_at")?,
+ updated_at: row.try_get("updated_at")?,
+ })
+ })
+ .fetch_all(pool)
+ .await
+}
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/tests.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/tests.rs
new file mode 100644
index 0000000000..7ed493f9f0
--- /dev/null
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/tests.rs
@@ -0,0 +1,205 @@
+use super::*;
+use item_filters::ast::email::{Email, EmailLiteral};
+use macro_user_id::cowlike::CowLike;
+use macro_user_id::email::EmailStr;
+
+#[test]
+fn test_build_email_filter_sender_complete() {
+ let email = Email::Complete(
+ EmailStr::parse_from_str("[email protected]")
+ .unwrap()
+ .into_owned(),
+ );
+ let expr = Expr::Literal(EmailLiteral::Sender(email));
+ let result = build_email_filter(&expr);
+
+ assert!(result.contains("m.from_contact_id"));
+ assert!(result.contains("LOWER(c.email_address) = LOWER('[email protected]')"));
+}
+
+#[test]
+fn test_build_email_filter_sender_partial() {
+ let email = Email::Partial("example".to_string());
+ let expr = Expr::Literal(EmailLiteral::Sender(email));
+ let result = build_email_filter(&expr);
+
+ assert!(result.contains("m.from_contact_id"));
+ assert!(result.contains("c.email_address ILIKE '%example%'"));
+}
+
+#[test]
+fn test_build_email_filter_recipient() {
+ let email = Email::Complete(
+ EmailStr::parse_from_str("[email protected]")
+ .unwrap()
+ .into_owned(),
+ );
+ let expr = Expr::Literal(EmailLiteral::Recipient(email));
+ let result = build_email_filter(&expr);
+
+ assert!(result.contains("email_message_recipients"));
+ assert!(result.contains("recipient_type = 'TO'"));
+ assert!(result.contains("LOWER(c.email_address) = LOWER('[email protected]')"));
+}
+
+#[test]
+fn test_build_email_filter_cc() {
+ let email = Email::Complete(
+ EmailStr::parse_from_str("[email protected]")
+ .unwrap()
+ .into_owned(),
+ );
+ let expr = Expr::Literal(EmailLiteral::Cc(email));
+ let result = build_email_filter(&expr);
+
+ assert!(result.contains("recipient_type = 'CC'"));
+}
+
+#[test]
+fn test_build_email_filter_bcc() {
+ let email = Email::Complete(
+ EmailStr::parse_from_str("[email protected]")
+ .unwrap()
+ .into_owned(),
+ );
+ let expr = Expr::Literal(EmailLiteral::Bcc(email));
+ let result = build_email_filter(&expr);
+
+ assert!(result.contains("recipient_type = 'BCC'"));
+}
+
+#[test]
+fn test_build_email_filter_and() {
+ let email1 = Email::Complete(
+ EmailStr::parse_from_str("[email protected]")
+ .unwrap()
+ .into_owned(),
+ );
+ let email2 = Email::Complete(
+ EmailStr::parse_from_str("[email protected]")
+ .unwrap()
+ .into_owned(),
+ );
+ let expr = Expr::and(
+ Expr::Literal(EmailLiteral::Sender(email1)),
+ Expr::Literal(EmailLiteral::Recipient(email2)),
+ );
+ let result = build_email_filter(&expr);
+
+ assert!(result.contains("AND"));
+ assert!(result.contains("[email protected]"));
+ assert!(result.contains("[email protected]"));
+}
+
+#[test]
+fn test_build_email_filter_or() {
+ let email1 = Email::Complete(
+ EmailStr::parse_from_str("[email protected]")
+ .unwrap()
+ .into_owned(),
+ );
+ let email2 = Email::Complete(
+ EmailStr::parse_from_str("[email protected]")
+ .unwrap()
+ .into_owned(),
+ );
+ let expr = Expr::or(
+ Expr::Literal(EmailLiteral::Sender(email1)),
+ Expr::Literal(EmailLiteral::Sender(email2)),
+ );
+ let result = build_email_filter(&expr);
+
+ assert!(result.contains("OR"));
+ assert!(result.contains("[email protected]"));
+ assert!(result.contains("[email protected]"));
+}
+
+#[test]
+fn test_build_email_filter_not() {
+ let email = Email::Complete(
+ EmailStr::parse_from_str("[email protected]")
+ .unwrap()
+ .into_owned(),
+ );
+ let expr = Expr::is_not(Expr::Literal(EmailLiteral::Sender(email)));
+ let result = build_email_filter(&expr);
+
+ assert!(result.contains("NOT"));
+ assert!(result.contains("[email protected]"));
+}
+
+#[test]
+fn test_escape_like_pattern() {
+ assert_eq!(escape_like_pattern("test"), "test");
+ assert_eq!(escape_like_pattern("test%"), r"test\%");
+ assert_eq!(escape_like_pattern("test_"), r"test\_");
+ assert_eq!(escape_like_pattern(r"test\"), r"test\\");
+ assert_eq!(escape_like_pattern(r"test\%_"), r"test\\\%\_");
+}
+
+#[test]
+fn test_build_view_thread_filter_inbox() {
+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox);
+ let result = build_view_thread_filter(&view);
+ assert!(result.contains("inbox_visible = TRUE"));
+ assert!(result.contains("latest_inbound_message_ts IS NOT NULL"));
+}
+
+#[test]
+fn test_build_view_thread_filter_sent() {
+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::Sent);
+ let result = build_view_thread_filter(&view);
+ assert!(result.contains("latest_outbound_message_ts IS NOT NULL"));
+}
+
+#[test]
+fn test_build_view_message_filter_drafts() {
+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::Drafts);
+ let result = build_view_message_filter(&view, "$1");
+ assert!(result.contains("is_draft = TRUE"));
+}
+
+#[test]
+fn test_build_view_message_filter_starred() {
+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::Starred);
+ let result = build_view_message_filter(&view, "$1");
+ assert!(result.contains("is_starred = TRUE"));
+ assert!(result.contains("is_draft = FALSE"));
+}
+
+#[test]
+fn test_build_view_message_filter_important() {
+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::Important);
+ let result = build_view_message_filter(&view, "$1");
+ assert!(result.contains("IMPORTANT"));
+ assert!(result.contains("EXISTS"));
+}
+
+#[test]
+fn test_build_view_message_filter_user_label() {
+ let view = PreviewView::UserLabel("MyLabel".to_string());
+ let result = build_view_message_filter(&view, "$1");
+ assert!(result.contains("MyLabel"));
+ assert!(result.contains("EXISTS"));
+}
+
+#[test]
+fn test_get_sort_timestamp_field_sent() {
+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::Sent);
+ let result = get_sort_timestamp_field(&view);
+ assert_eq!(result, "t.latest_outbound_message_ts");
+}
+
+#[test]
+fn test_get_sort_timestamp_field_inbox() {
+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox);
+ let result = get_sort_timestamp_field(&view);
+ assert_eq!(result, "t.latest_inbound_message_ts");
+}
+
+#[test]
+fn test_get_sort_timestamp_field_default() {
+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::All);
+ let result = get_sort_timestamp_field(&view);
+ assert_eq!(result, "t.latest_non_spam_message_ts");
+}
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/all_mail.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/all_mail.rs
index 18bda4fc33..2b97f851ea 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/all_mail.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/all_mail.rs
@@ -1,7 +1,7 @@
use super::super::db_types::*;
-use crate::domain::models::PreviewCursorQuery;
-use macro_user_id::user_id::MacroUserIdStr;
+use models_pagination::{Query, SimpleSortMethod};
use sqlx::PgPool;
+use uuid::Uuid;
/// Fetches a paginated list of thread previews for the "All Mail" view using a
/// denormalized timestamp.
@@ -11,12 +11,13 @@ use sqlx::PgPool;
#[tracing::instrument(skip(pool), err)]
pub(crate) async fn all_mail_preview_cursor(
pool: &PgPool,
- query: &PreviewCursorQuery,
- user_id: MacroUserIdStr<'_>,
+ link_id: &Uuid,
+ limit: u32,
+ query: &Query<Uuid, SimpleSortMethod, ()>,
) -> Result<Vec<ThreadPreviewCursorDbRow>, sqlx::Error> {
- let query_limit = query.limit as i64;
- let sort_method_str = query.query.sort_method().to_string();
- let (cursor_id, cursor_timestamp) = query.query.vals();
+ let query_limit = limit as i64;
+ let sort_method_str = query.sort_method().to_string();
+ let (cursor_id, cursor_timestamp) = query.vals();
sqlx::query_as!(
ThreadPreviewCursorDbRow,
@@ -107,7 +108,7 @@ pub(crate) async fn all_mail_preview_cursor(
LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id
ORDER BY t.effective_ts DESC, t.updated_at DESC
"#,
- query.link_id, // $1
+ link_id, // $1
query_limit, // $2
cursor_timestamp, // $3
cursor_id, // $4
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/draft.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/draft.rs
index 90782ff788..7fdb48ebb8 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/draft.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/draft.rs
@@ -1,7 +1,7 @@
use super::super::db_types::*;
-use crate::domain::models::PreviewCursorQuery;
-use macro_user_id::user_id::MacroUserIdStr;
+use models_pagination::{Query, SimpleSortMethod};
use sqlx::PgPool;
+use uuid::Uuid;
/// Fetches a paginated list of thread previews for the "Drafts" view.
/// This view includes all threads that contain at least one draft message, sorted by the
@@ -9,12 +9,13 @@ use sqlx::PgPool;
#[tracing::instrument(skip(pool), err)]
pub(crate) async fn drafts_preview_cursor(
pool: &PgPool,
- query: &PreviewCursorQuery,
- user_id: MacroUserIdStr<'_>,
+ link_id: &Uuid,
+ limit: u32,
+ query: &Query<Uuid, SimpleSortMethod, ()>,
) -> Result<Vec<ThreadPreviewCursorDbRow>, sqlx::Error> {
- let query_limit = query.limit as i64;
- let sort_method_str = query.query.sort_method().to_string();
- let (cursor_id, cursor_timestamp) = query.query.vals();
+ let query_limit = limit as i64;
+ let sort_method_str = query.sort_method().to_string();
+ let (cursor_id, cursor_timestamp) = query.vals();
sqlx::query_as!(
ThreadPreviewCursorDbRow,
@@ -102,7 +103,7 @@ pub(crate) async fn drafts_preview_cursor(
LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id
ORDER BY t.effective_ts DESC, t.updated_at DESC
"#,
- query.link_id, // $1
+ link_id, // $1
query_limit, // $2
cursor_timestamp, // $3
cursor_id, // $4
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/important.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/important.rs
index af42f95f71..0de8da7ee8 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/important.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/important.rs
@@ -1,7 +1,7 @@
use super::super::db_types::*;
-use crate::domain::models::PreviewCursorQuery;
-use macro_user_id::user_id::MacroUserIdStr;
+use models_pagination::{Query, SimpleSortMethod};
use sqlx::PgPool;
+use uuid::Uuid;
/// Fetches a paginated list of thread previews for the "Important" view.
/// Includes threads that:
@@ -11,12 +11,13 @@ use sqlx::PgPool;
#[tracing::instrument(skip(pool), err)]
pub(crate) async fn important_preview_cursor(
pool: &PgPool,
- query: &PreviewCursorQuery,
- user_id: MacroUserIdStr<'_>,
+ link_id: &Uuid,
+ limit: u32,
+ query: &Query<Uuid, SimpleSortMethod, ()>,
) -> Result<Vec<ThreadPreviewCursorDbRow>, sqlx::Error> {
- let query_limit = query.limit as i64;
- let sort_method_str = query.query.sort_method().to_string();
- let (cursor_id, cursor_timestamp) = query.query.vals();
+ let query_limit = limit as i64;
+ let sort_method_str = query.sort_method().to_string();
+ let (cursor_id, cursor_timestamp) = query.vals();
sqlx::query_as!(
ThreadPreviewCursorDbRow,
@@ -126,7 +127,7 @@ pub(crate) async fn important_preview_cursor(
ORDER BY isk.effective_ts DESC, isk.thread_id DESC
LIMIT $2
"#,
- query.link_id, // $1
+ link_id, // $1
query_limit, // $2
cursor_timestamp, // $3
cursor_id, // $4
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/new_inbox.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/new_inbox.rs
index 8648d1dc71..ff76defb3e 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/new_inbox.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/new_inbox.rs
@@ -1,7 +1,7 @@
use super::super::db_types::*;
-use crate::domain::models::PreviewCursorQuery;
-use macro_user_id::user_id::MacroUserIdStr;
+use models_pagination::{Query, SimpleSortMethod};
use sqlx::PgPool;
+use uuid::Uuid;
/// Fetches a paginated list of thread previews for a given link_id.
/// Each thread preview includes details from the latest message (inbound or outbound)
@@ -10,12 +10,13 @@ use sqlx::PgPool;
#[tracing::instrument(skip(pool), err)]
pub(crate) async fn new_inbox_preview_cursor(
pool: &PgPool,
- query: &PreviewCursorQuery,
- user_id: MacroUserIdStr<'_>,
+ link_id: &Uuid,
+ limit: u32,
+ query: &Query<Uuid, SimpleSortMethod, ()>,
) -> Result<Vec<ThreadPreviewCursorDbRow>, sqlx::Error> {
- let query_limit = query.limit as i64;
- let sort_method_str = query.query.sort_method().to_string();
- let (cursor_id, cursor_timestamp) = query.query.vals();
+ let query_limit = limit as i64;
+ let sort_method_str = query.sort_method().to_string();
+ let (cursor_id, cursor_timestamp) = query.vals();
sqlx::query_as!(
ThreadPreviewCursorDbRow,
@@ -103,7 +104,7 @@ pub(crate) async fn new_inbox_preview_cursor(
-- Final ordering is preserved because the input `t` is already sorted.
ORDER BY t.effective_ts DESC, t.updated_at DESC -- fall back to updated_at if effective_ts is the same
"#,
- query.link_id, // $1
+ link_id, // $1
query_limit, // $2
cursor_timestamp, // $3
cursor_id, // $4
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/other_inbox.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/other_inbox.rs
index 6d8477f98e..ac1b9706b2 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/other_inbox.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/other_inbox.rs
@@ -1,7 +1,7 @@
use super::super::db_types::*;
-use crate::domain::models::PreviewCursorQuery;
-use macro_user_id::user_id::MacroUserIdStr;
+use models_pagination::{Query, SimpleSortMethod};
use sqlx::PgPool;
+use uuid::Uuid;
/// Fetches a paginated list of thread previews for the "Other" inbox view.
/// This view includes threads that have a category label (Promotions, Social, etc.)
@@ -9,12 +9,13 @@ use sqlx::PgPool;
#[tracing::instrument(skip(pool), err)]
pub(crate) async fn other_inbox_preview_cursor(
pool: &PgPool,
- query: &PreviewCursorQuery,
- user_id: MacroUserIdStr<'_>,
+ link_id: &Uuid,
+ limit: u32,
+ query: &Query<Uuid, SimpleSortMethod, ()>,
) -> Result<Vec<ThreadPreviewCursorDbRow>, sqlx::Error> {
- let query_limit = query.limit as i64;
- let sort_method_str = query.query.sort_method().to_string();
- let (cursor_id, cursor_timestamp) = query.query.vals();
+ let query_limit = limit as i64;
+ let sort_method_str = query.sort_method().to_string();
+ let (cursor_id, cursor_timestamp) = query.vals();
sqlx::query_as!(
ThreadPreviewCursorDbRow,
@@ -110,7 +111,7 @@ pub(crate) async fn other_inbox_preview_cursor(
LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id
ORDER BY t.effective_ts DESC, t.updated_at DESC
"#,
- query.link_id, // $1
+ link_id, // $1
query_limit, // $2
cursor_timestamp, // $3
cursor_id, // $4
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/sent.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/sent.rs
index c763307a0b..a57567d427 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/sent.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/sent.rs
@@ -1,7 +1,7 @@
use super::super::db_types::*;
-use crate::domain::models::PreviewCursorQuery;
-use macro_user_id::user_id::MacroUserIdStr;
+use models_pagination::{Query, SimpleSortMethod};
use sqlx::PgPool;
+use uuid::Uuid;
/// Fetches a paginated list of thread previews for the "Sent" view.
/// This view includes all threads (archived or not) sorted by the timestamp
@@ -10,12 +10,13 @@ use sqlx::PgPool;
#[tracing::instrument(skip(pool), err)]
pub(crate) async fn sent_preview_cursor(
pool: &PgPool,
- query: &PreviewCursorQuery,
- user_id: MacroUserIdStr<'_>,
+ link_id: &Uuid,
+ limit: u32,
+ query: &Query<Uuid, SimpleSortMethod, ()>,
) -> Result<Vec<ThreadPreviewCursorDbRow>, sqlx::Error> {
- let query_limit = query.limit as i64;
- let sort_method_str = query.query.sort_method().to_string();
- let (cursor_id, cursor_timestamp) = query.query.vals();
+ let query_limit = limit as i64;
+ let sort_method_str = query.sort_method().to_string();
+ let (cursor_id, cursor_timestamp) = query.vals();
sqlx::query_as!(
ThreadPreviewCursorDbRow,
@@ -103,7 +104,7 @@ pub(crate) async fn sent_preview_cursor(
-- Final ordering is preserved because the input `t` is already sorted.
ORDER BY t.effective_ts DESC, t.updated_at DESC
"#,
- query.link_id, // $1
+ link_id, // $1
query_limit, // $2
cursor_timestamp, // $3
cursor_id, // $4
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/starred.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/starred.rs
index ccb01f5036..dc93ba8f45 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/starred.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/starred.rs
@@ -1,7 +1,7 @@
use super::super::db_types::*;
-use crate::domain::models::PreviewCursorQuery;
-use macro_user_id::user_id::MacroUserIdStr;
+use models_pagination::{Query, SimpleSortMethod};
use sqlx::PgPool;
+use uuid::Uuid;
/// Fetches a paginated list of thread previews for the "Starred" view.
/// This view includes all threads that contain at least one starred message, sorted by the
@@ -10,12 +10,13 @@ use sqlx::PgPool;
#[tracing::instrument(skip(pool), err)]
pub(crate) async fn starred_preview_cursor(
pool: &PgPool,
- query: &PreviewCursorQuery,
- user_id: MacroUserIdStr<'_>,
+ link_id: &Uuid,
+ limit: u32,
+ query: &Query<Uuid, SimpleSortMethod, ()>,
) -> Result<Vec<ThreadPreviewCursorDbRow>, sqlx::Error> {
- let query_limit = query.limit as i64;
- let sort_method_str = query.query.sort_method().to_string();
- let (cursor_id, cursor_timestamp) = query.query.vals();
+ let query_limit = limit as i64;
+ let sort_method_str = query.sort_method().to_string();
+ let (cursor_id, cursor_timestamp) = query.vals();
sqlx::query_as!(
ThreadPreviewCursorDbRow,
@@ -101,7 +102,7 @@ pub(crate) async fn starred_preview_cursor(
LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id
ORDER BY t.effective_ts DESC, t.updated_at DESC
"#,
- query.link_id, // $1
+ link_id, // $1
query_limit, // $2
cursor_timestamp, // $3
cursor_id, // $4
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/user_label.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/user_label.rs
index 8b4e2abe74..8aecd403a8 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/user_label.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/queries/user_label.rs
@@ -1,7 +1,7 @@
use super::super::db_types::*;
-use crate::domain::models::PreviewCursorQuery;
-use macro_user_id::user_id::MacroUserIdStr;
+use models_pagination::{Query, SimpleSortMethod};
use sqlx::PgPool;
+use uuid::Uuid;
/// Fetches a paginated list of thread previews for a user label.
/// This view includes threads that have at least one message with the given label.
@@ -10,13 +10,14 @@ use sqlx::PgPool;
#[tracing::instrument(skip(pool), err)]
pub(crate) async fn user_label_preview_cursor(
pool: &PgPool,
- query: &PreviewCursorQuery,
+ link_id: &Uuid,
+ limit: u32,
+ query: &Query<Uuid, SimpleSortMethod, ()>,
label_name: &str,
- user_id: MacroUserIdStr<'_>,
) -> Result<Vec<ThreadPreviewCursorDbRow>, sqlx::Error> {
- let query_limit = query.limit as i64;
- let sort_method_str = query.query.sort_method().to_string();
- let (cursor_id, cursor_timestamp) = query.query.vals();
+ let query_limit = limit as i64;
+ let sort_method_str = query.sort_method().to_string();
+ let (cursor_id, cursor_timestamp) = query.vals();
sqlx::query_as!(
ThreadPreviewCursorDbRow,
@@ -107,7 +108,7 @@ pub(crate) async fn user_label_preview_cursor(
LEFT JOIN email_contacts c ON lmp.from_contact_id = c.id
ORDER BY t.effective_ts DESC, t.updated_at DESC
"#,
- query.link_id, // $1
+ link_id, // $1
query_limit, // $2
cursor_timestamp, // $3
cursor_id, // $4
diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/test.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/test.rs
index e90ab55264..80352d575f 100644
--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/test.rs
+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/test.rs
@@ -1,7 +1,14 @@
+use std::sync::Arc;
+
use super::*;
-use crate::domain::models::LabelType;
+use crate::domain::models::{LabelType, PreviewView, PreviewViewStandardLabel};
use crate::domain::ports::EmailRepo;
+use filter_ast::Expr;
+use item_filters::ast::email::{Email, EmailLiteral};
use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use macro_user_id::cowlike::CowLike;
+use macro_user_id::email::EmailStr;
+use models_pagination::{Cursor, CursorVal, Query, SimpleSortMethod};
use sqlx::{Pool, Postgres};
use uuid::Uuid;
@@ -135,3 +142,484 @@ async fn test_labels_by_thread_ids_different_label_types(
Ok(())
}
+// ============================================================================
+// Dynamic Query Builder Integration Tests
+// ============================================================================
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("email_dynamic_query"))
+)]
+async fn test_dynamic_query_inbox_view(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox);
+ let limit = 50;
+ // Use a broad filter that matches most emails
+ let filter = Arc::new(Expr::Literal(EmailLiteral::Sender(Email::Partial(
+ "example.com".to_string(),
+ ))));
+ let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);
+
+ let results =
+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;
+
+ // Should get inbox messages (threads 1, 4, 5, 7)
+ assert_eq!(
+ results.len(),
+ 4,
+ "Inbox view should return 4 threads with inbox_visible=true"
+ );
+
+ // Verify thread 1 is in results
+ assert!(
+ results
+ .iter()
+ .any(|r| r.id.to_string() == "20000001-0000-0000-0000-000000000001"),
+ "Should include inbox thread 1"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("email_dynamic_query"))
+)]
+async fn test_dynamic_query_sent_view(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::Sent);
+ let limit = 50;
+ let filter = Arc::new(Expr::Literal(EmailLiteral::Sender(Email::Partial(
+ "example.com".to_string(),
+ ))));
+ let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);
+
+ let results =
+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;
+
+ // Should get sent messages (thread 2)
+ assert_eq!(results.len(), 1, "Sent view should return 1 thread");
+ assert_eq!(
+ results[0].id.to_string(),
+ "20000002-0000-0000-0000-000000000002"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("email_dynamic_query"))
+)]
+async fn test_dynamic_query_drafts_view(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::Drafts);
+ let limit = 50;
+ let filter = Arc::new(Expr::Literal(EmailLiteral::Sender(Email::Partial(
+ "example.com".to_string(),
+ ))));
+ let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);
+
+ let results =
+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;
+
+ // Should get draft messages (thread 3)
+ assert_eq!(results.len(), 1, "Drafts view should return 1 thread");
+ assert_eq!(
+ results[0].id.to_string(),
+ "20000003-0000-0000-0000-000000000003"
+ );
+ assert!(results[0].is_draft, "Message should be marked as draft");
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("email_dynamic_query"))
+)]
+async fn test_dynamic_query_starred_view(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::Starred);
+ let limit = 50;
+ let filter = Arc::new(Expr::Literal(EmailLiteral::Sender(Email::Partial(
+ "example.com".to_string(),
+ ))));
+ let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);
+
+ let results =
+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;
+
+ // Should get starred messages (thread 4)
+ assert_eq!(results.len(), 1, "Starred view should return 1 thread");
+ assert_eq!(
+ results[0].id.to_string(),
+ "20000004-0000-0000-0000-000000000004"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("email_dynamic_query"))
+)]
+async fn test_dynamic_query_important_view(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::Important);
+ let limit = 50;
+ let filter = Arc::new(Expr::Literal(EmailLiteral::Sender(Email::Partial(
+ "example.com".to_string(),
+ ))));
+ let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);
+
+ let results =
+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;
+
+ // Should get important messages (thread 5)
+ assert_eq!(results.len(), 1, "Important view should return 1 thread");
+ assert_eq!(
+ results[0].id.to_string(),
+ "20000005-0000-0000-0000-000000000005"
+ );
+ assert!(
+ results[0].is_important,
+ "Message should be marked as important"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("email_dynamic_query"))
+)]
+async fn test_dynamic_query_user_label_view(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
+ let view = PreviewView::UserLabel("Work".to_string());
+ let limit = 50;
+ let filter = Arc::new(Expr::Literal(EmailLiteral::Sender(Email::Partial(
+ "example.com".to_string(),
+ ))));
+ let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);
+
+ let results =
+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;
+
+ // Should get messages with "Work" label (thread 6)
+ assert_eq!(results.len(), 1, "User label view should return 1 thread");
+ assert_eq!(
+ results[0].id.to_string(),
+ "20000006-0000-0000-0000-000000000006"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("email_dynamic_query"))
+)]
+async fn test_dynamic_query_with_sender_filter(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::All);
+ let limit = 50;
+
+ // Filter for emails from [email protected]
+ let email_filter = Arc::new(Expr::Literal(EmailLiteral::Sender(Email::Complete(
+ EmailStr::parse_from_str("[email protected]")?.into_owned(),
+ ))));
+ let query = Query::new(None, SimpleSortMethod::UpdatedAt, email_filter);
+
+ let results =
+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;
+
+ // Should get messages from [email protected] (threads 1, 2, 5)
+ assert!(
+ results.len() >= 2,
+ "Should return at least 2 threads from [email protected]"
+ );
+
+ // Verify sender is [email protected] for applicable threads
+ for result in &results {
+ if let Some(sender) = &result.sender_email {
+ assert_eq!(sender, "[email protected]");
+ }
+ }
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("email_dynamic_query"))
+)]
+async fn test_dynamic_query_with_partial_sender_filter(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::All);
+ let limit = 50;
+
+ // Filter for emails from anyone at example.com
+ let email_filter = Arc::new(Expr::Literal(EmailLiteral::Sender(Email::Partial(
+ "example.com".to_string(),
+ ))));
+ let query = Query::new(None, SimpleSortMethod::UpdatedAt, email_filter);
+
+ let results =
+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;
+
+ // Should get all messages since all contacts are from example.com
+ assert!(
+ results.len() >= 5,
+ "Should return multiple threads from example.com domain"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("email_dynamic_query"))
+)]
+async fn test_dynamic_query_with_recipient_filter(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::All);
+ let limit = 50;
+
+ // Filter for emails to [email protected]
+ let email_filter = Arc::new(Expr::Literal(EmailLiteral::Recipient(Email::Complete(
+ EmailStr::parse_from_str("[email protected]")?.into_owned(),
+ ))));
+ let query = Query::new(None, SimpleSortMethod::UpdatedAt, email_filter);
+
+ let results =
+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;
+
+ // Should get messages to [email protected] (threads 1, 3, 5, 7)
+ assert!(
+ results.len() >= 3,
+ "Should return threads sent to [email protected]"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("email_dynamic_query"))
+)]
+async fn test_dynamic_query_with_cc_filter(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::All);
+ let limit = 50;
+
+ // Filter for emails with [email protected] in CC
+ let email_filter = Arc::new(Expr::Literal(EmailLiteral::Cc(Email::Complete(
+ EmailStr::parse_from_str("[email protected]")?.into_owned(),
+ ))));
+ let query = Query::new(None, SimpleSortMethod::UpdatedAt, email_filter);
+
+ let results =
+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;
+
+ // Should get messages with [email protected] in CC (thread 7)
+ assert_eq!(results.len(), 1, "Should return 1 thread with CC to bob");
+ assert_eq!(
+ results[0].id.to_string(),
+ "20000007-0000-0000-0000-000000000007"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("email_dynamic_query"))
+)]
+async fn test_dynamic_query_inbox_with_sender_filter(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox);
+ let limit = 50;
+
+ // Combine Inbox view with sender filter
+ let email_filter = Arc::new(Expr::Literal(EmailLiteral::Sender(Email::Complete(
+ EmailStr::parse_from_str("[email protected]")?.into_owned(),
+ ))));
+ let query = Query::new(None, SimpleSortMethod::UpdatedAt, email_filter);
+
+ let results =
+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;
+
+ // Should get inbox messages from [email protected] (threads 1, 5)
+ assert_eq!(
+ results.len(),
+ 2,
+ "Should return 2 inbox threads from [email protected]"
+ );
+
+ // Verify all results are from john and in inbox
+ for result in &results {
+ assert!(result.inbox_visible, "Should be inbox visible");
+ if let Some(sender) = &result.sender_email {
+ assert_eq!(sender, "[email protected]");
+ }
+ }
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("email_dynamic_query"))
+)]
+async fn test_dynamic_query_drafts_with_recipient_filter(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::Drafts);
+ let limit = 50;
+
+ // Combine Drafts view with recipient filter
+ let email_filter = Arc::new(Expr::Literal(EmailLiteral::Recipient(Email::Complete(
+ EmailStr::parse_from_str("[email protected]")?.into_owned(),
+ ))));
+ let query = Query::new(None, SimpleSortMethod::UpdatedAt, email_filter);
+
+ let results =
+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;
+
+ // Should get draft messages to [email protected] (thread 3)
+ assert_eq!(
+ results.len(),
+ 1,
+ "Should return 1 draft thread to [email protected]"
+ );
+ assert!(results[0].is_draft, "Should be a draft");
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("email_dynamic_query"))
+)]
+async fn test_dynamic_query_with_and_filter(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::All);
+ let limit = 50;
+
+ // Filter for emails from [email protected] AND to [email protected]
+ let email_filter = Arc::new(Expr::and(
+ Expr::Literal(EmailLiteral::Sender(Email::Complete(
+ EmailStr::parse_from_str("[email protected]")?.into_owned(),
+ ))),
+ Expr::Literal(EmailLiteral::Recipient(Email::Complete(
+ EmailStr::parse_from_str("[email protected]")?.into_owned(),
+ ))),
+ ));
+ let query = Query::new(None, SimpleSortMethod::UpdatedAt, email_filter);
+
+ let results =
+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;
+
+ // Should get messages from john to alice (threads 1, 5)
+ assert!(
+ results.len() >= 1,
+ "Should return threads from john to alice"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("email_dynamic_query"))
+)]
+async fn test_dynamic_query_with_or_filter(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::All);
+ let limit = 50;
+
+ // Filter for emails from [email protected] OR [email protected]
+ let email_filter = Arc::new(Expr::or(
+ Expr::Literal(EmailLiteral::Sender(Email::Complete(
+ EmailStr::parse_from_str("[email protected]")?.into_owned(),
+ ))),
+ Expr::Literal(EmailLiteral::Sender(Email::Complete(
+ EmailStr::parse_from_str("[email protected]")?.into_owned(),
+ ))),
+ ));
+ let query = Query::new(None, SimpleSortMethod::UpdatedAt, email_filter);
+
+ let results =
+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;
+
+ // Should get messages from john or jane
+ assert!(
+ results.len() >= 3,
+ "Should return threads from john or jane"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("email_dynamic_query"))
+)]
+async fn test_dynamic_query_pagination(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;
+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox);
+ let limit = 2;
+
+ // First page with limit 2
+ let filter1 = Arc::new(Expr::Literal(EmailLiteral::Sender(Email::Partial(
+ "example.com".to_string(),
+ ))));
+ let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter1);
+ let first_page =
+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;
+
+ assert_eq!(first_page.len(), 2, "Should return 2 results");
+
+ // Get the cursor from the last item
+ let last_item = first_page.last().unwrap();
+ let cursor_ts = last_item.sort_ts;
+ let cursor_id = last_item.id;
+
+ // Second page using cursor
+ let filter2 = Arc::new(Expr::Literal(EmailLiteral::Sender(Email::Partial(
+ "example.com".to_string(),
+ ))));
+ let filter3 = Arc::new(Expr::Literal(EmailLiteral::Sender(Email::Partial(
+ "example.com".to_string(),
+ ))));
+ let cursor = Cursor {
+ id: cursor_id,
+ limit: 2,
+ val: CursorVal {
+ sort_type: SimpleSortMethod::UpdatedAt,
+ last_val: cursor_ts,
+ },
+ filter: filter2,
+ };
+ let query2 = Query::new(Some(cursor), SimpleSortMethod::UpdatedAt, filter3);
+ let second_page =
+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query2).await?;
+
+ assert!(
+ second_page.len() > 0,
+ "Should return additional results on second page"
+ );
+
+ // Verify no overlap between pages
+ let first_ids: Vec<_> = first_page.iter().map(|r| r.id).collect();
+ for result in &second_page {
+ assert!(
+ !first_ids.contains(&result.id),
+ "Second page should not contain IDs from first page"
+ );
+ }
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/filter_ast/src/lib.rs b/rust/cloud-storage/filter_ast/src/lib.rs
index 730ed5032c..acf03a7a31 100644
--- a/rust/cloud-storage/filter_ast/src/lib.rs
+++ b/rust/cloud-storage/filter_ast/src/lib.rs
@@ -1,12 +1,23 @@
+use std::convert::Infallible;
+
use recursion::{Collapsible, Expandable, MappableFrame, PartiallyApplied};
use serde::{Deserialize, Serialize};
-pub trait TryExpandNode: Iterator {
+pub trait TryExpandNode: Iterator + Sized {
fn try_expand<U, E>(
self,
cb: impl FnMut(<Self as Iterator>::Item) -> Result<U, E>,
fold: impl Fn(Expr<U>, Expr<U>) -> Expr<U>,
) -> Result<Option<Expr<U>>, E>;
+
+ fn expand<U>(
+ self,
+ mut cb: impl FnMut(<Self as Iterator>::Item) -> U,
+ fold: impl Fn(Expr<U>, Expr<U>) -> Expr<U>,
+ ) -> Option<Expr<U>> {
+ self.try_expand(move |v| Result::<U, Infallible>::Ok(cb(v)), fold)
+ .unwrap()
+ }
}
impl<I> TryExpandNode for I
diff --git a/rust/cloud-storage/frecency/src/outbound/postgres/dynamic.rs b/rust/cloud-storage/frecency/src/outbound/postgres/dynamic.rs
index c846f1012d..321767513e 100644
--- a/rust/cloud-storage/frecency/src/outbound/postgres/dynamic.rs
+++ b/rust/cloud-storage/frecency/src/outbound/postgres/dynamic.rs
@@ -139,23 +139,19 @@ fn build_query(filter_ast: &EntityFilterAst) -> QueryBuilder<'_, Postgres> {
// Document clause
builder.push(DOCUMENT_CLAUSE);
- builder.push(build_document_filter(
- filter_ast.inner.document_filter.as_ref(),
- ));
+ builder.push(build_document_filter(filter_ast.document_filter.as_deref()));
builder.push(" UNION ALL ");
// Chat clause
builder.push(CHAT_CLAUSE);
- builder.push(build_chat_filter(filter_ast.inner.chat_filter.as_ref()));
+ builder.push(build_chat_filter(filter_ast.chat_filter.as_deref()));
builder.push(" UNION ALL ");
// Project clause
builder.push(PROJECT_CLAUSE);
- builder.push(build_project_filter(
- filter_ast.inner.project_filter.as_ref(),
- ));
+ builder.push(build_project_filter(filter_ast.project_filter.as_deref()));
builder.push(") ");
builder.push(SUFFIX);
diff --git a/rust/cloud-storage/item_filters/Cargo.toml b/rust/cloud-storage/item_filters/Cargo.toml
index 08946501d1..d150e5c6ee 100644
--- a/rust/cloud-storage/item_filters/Cargo.toml
+++ b/rust/cloud-storage/item_filters/Cargo.toml
@@ -6,6 +6,7 @@ version = "0.1.0"
[features]
mock = []
+schema = ["dep:schemars", "dep:utoipa"]
[dependencies]
chrono = { workspace = true }
@@ -13,12 +14,12 @@ filter_ast = { path = "../filter_ast" }
macro_user_id = { path = "../macro_user_id" }
model_file_type = { path = "../model_file_type" }
non_empty = { path = "../non_empty" }
-schemars = { workspace = true }
+schemars = { workspace = true, optional = true }
serde = { workspace = true, features = ["rc"] }
serde_json = { workspace = true }
strum = { workspace = true }
thiserror = { workspace = true }
-utoipa = { workspace = true }
+utoipa = { workspace = true, optional = true }
uuid = { workspace = true }
[dev-dependencies]
diff --git a/rust/cloud-storage/item_filters/src/ast.rs b/rust/cloud-storage/item_filters/src/ast.rs
index 88dbc04c7b..f520e89288 100644
--- a/rust/cloud-storage/item_filters/src/ast.rs
+++ b/rust/cloud-storage/item_filters/src/ast.rs
@@ -2,9 +2,10 @@
//! This is used to construct a strictly typed ast for the input filters, allowing consumers to have a logical represenation of the required operations
use crate::{
- ChatFilters, DocumentFilters, EntityFilters, ProjectFilters,
+ ChatFilters, DocumentFilters, EmailFilters, EntityFilters, ProjectFilters,
ast::{
chat::{ChatLiteral, ChatRole},
+ email::EmailLiteral,
project::ProjectLiteral,
},
};
@@ -55,27 +56,25 @@ pub enum ExpandErr {
MacroIdErr(#[from] macro_user_id::error::ParseErr),
}
+/// type alias for a maybe empty, cheaply cloneable ast literal tree
+pub type LiteralTree<T> = Option<Arc<Expr<T>>>;
+
/// Describes a bundle of filters that should be applied across different entity types
-#[derive(Debug, Serialize, Deserialize)]
+#[derive(Debug, Serialize, Deserialize, Clone)]
#[non_exhaustive]
-pub struct EntityFilterInner {
+pub struct EntityFilterAst {
/// the filters that should be applied to the document entity
#[serde(default)]
- pub document_filter: Option<Expr<DocumentLiteral>>,
+ pub document_filter: LiteralTree<DocumentLiteral>,
/// the filters that should be applied to the project entity
#[serde(default)]
- pub project_filter: Option<Expr<ProjectLiteral>>,
+ pub project_filter: LiteralTree<ProjectLiteral>,
/// the filters that should be applied to the chat entity
#[serde(default)]
- pub chat_filter: Option<Expr<ChatLiteral>>,
-}
-
-/// wrapper over [EntityFilterInner] which gives us cheaper clones
-#[derive(Debug, Serialize, Deserialize, Clone)]
-#[non_exhaustive]
-pub struct EntityFilterAst {
- /// we wrap the inner type in an arc to avoid large allocations when cloning boxed values
- pub inner: Arc<EntityFilterInner>,
+ pub chat_filter: LiteralTree<ChatLiteral>,
+ /// the filters that should be applied to the email entity
+ #[serde(default)]
+ pub email_filter: LiteralTree<EmailLiteral>,
}
impl EntityFilterAst {
@@ -84,12 +83,13 @@ impl EntityFilterAst {
if entity_filter.is_empty() {
return Ok(None);
}
- Ok(Some(Self {
- inner: Arc::new(EntityFilterInner {
- document_filter: DocumentFilters::expand_ast(entity_filter.document_filters)?,
- project_filter: ProjectFilters::expand_ast(entity_filter.project_filters)?,
- chat_filter: ChatFilters::expand_ast(entity_filter.chat_filters)?,
- }),
+ Ok(Some(EntityFilterAst {
+ document_filter: DocumentFilters::expand_ast(entity_filter.document_filters)?
+ .map(Arc::new),
+ project_filter: ProjectFilters::expand_ast(entity_filter.project_filters)?
+ .map(Arc::new),
+ chat_filter: ChatFilters::expand_ast(entity_filter.chat_filters)?.map(Arc::new),
+ email_filter: EmailFilters::expand_ast(entity_filter.email_filters)?.map(Arc::new),
}))
}
@@ -97,22 +97,25 @@ impl EntityFilterAst {
#[cfg(feature = "mock")]
pub fn mock_empty() -> Self {
Self {
- inner: Arc::new(EntityFilterInner {
- document_filter: None,
- project_filter: None,
- chat_filter: None,
- }),
+ document_filter: None,
+ project_filter: None,
+ chat_filter: None,
+ email_filter: None,
}
}
}
impl IsEmpty for EntityFilterAst {
fn is_empty(&self) -> bool {
- let EntityFilterInner {
+ let EntityFilterAst {
document_filter,
project_filter,
chat_filter,
- } = &*self.inner;
- document_filter.is_none() && project_filter.is_none() && chat_filter.is_none()
+ email_filter,
+ } = self;
+ document_filter.is_none()
+ && project_filter.is_none()
+ && chat_filter.is_none()
+ && email_filter.is_none()
}
}
diff --git a/rust/cloud-storage/item_filters/src/ast/document.rs b/rust/cloud-storage/item_filters/src/ast/document.rs
index 4f041b68c8..d3891c3695 100644
--- a/rust/cloud-storage/item_filters/src/ast/document.rs
+++ b/rust/cloud-storage/item_filters/src/ast/document.rs
@@ -6,7 +6,7 @@ use serde::{Deserialize, Serialize};
use std::str::FromStr;
use uuid::Uuid;
-/// the literal type that can appear in the item filer ast
+/// the literal type that can appear in the item filter ast
#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum DocumentLiteral {
/// this node value filters by [FileType]
diff --git a/rust/cloud-storage/item_filters/src/ast/email.rs b/rust/cloud-storage/item_filters/src/ast/email.rs
index 8b13789179..7ef9446bdb 100644
--- a/rust/cloud-storage/item_filters/src/ast/email.rs
+++ b/rust/cloud-storage/item_filters/src/ast/email.rs
@@ -1 +1,67 @@
+use filter_ast::{ExpandFrame, Expr, FoldTree, TryExpandNode};
+use macro_user_id::{cowlike::CowLike, email::EmailStr};
+use serde::{Deserialize, Serialize};
+use crate::{EmailFilters, ast::ExpandErr};
+
+/// Possible email values in the ast
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub enum Email {
+ /// A string which is not a valid fully qualified email
+ Partial(String),
+ /// a fully valid qualified [EmailStr]
+ Complete(EmailStr<'static>),
+}
+
+/// The literal type that can appear in the item filter ast
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub enum EmailLiteral {
+ /// The sender field of the email
+ Sender(Email),
+ /// The cc field of the email
+ Cc(Email),
+ /// The bcc field of the email
+ Bcc(Email),
+ /// The recipient field of the email
+ Recipient(Email),
+}
+
+impl ExpandFrame<EmailLiteral> for EmailFilters {
+ type Err = ExpandErr;
+ fn expand_ast(input: Self) -> Result<Option<filter_ast::Expr<EmailLiteral>>, Self::Err> {
+ let EmailFilters {
+ senders,
+ cc,
+ bcc,
+ recipients,
+ } = input;
+
+ fn map_email(s: String) -> Email {
+ match EmailStr::parse_from_str(&s) {
+ Ok(e) => Email::Complete(e.into_owned()),
+ Err(_) => Email::Partial(s),
+ }
+ }
+
+ let sender_nodes = senders
+ .into_iter()
+ .map(map_email)
+ .expand(EmailLiteral::Sender, Expr::or);
+ let cc_nodes = cc
+ .into_iter()
+ .map(map_email)
+ .expand(EmailLiteral::Cc, Expr::or);
+ let bcc_nodes = bcc
+ .into_iter()
+ .map(map_email)
+ .expand(EmailLiteral::Bcc, Expr::or);
+ let recipient_nodes = recipients
+ .into_iter()
+ .map(map_email)
+ .expand(EmailLiteral::Recipient, Expr::or);
+
+ Ok([sender_nodes, cc_nodes, bcc_nodes, recipient_nodes]
+ .into_iter()
+ .fold_with(Expr::and))
+ }
+}
diff --git a/rust/cloud-storage/item_filters/src/ast/tests.rs b/rust/cloud-storage/item_filters/src/ast/tests.rs
index 0bb8a80556..5e865e5687 100644
--- a/rust/cloud-storage/item_filters/src/ast/tests.rs
+++ b/rust/cloud-storage/item_filters/src/ast/tests.rs
@@ -33,10 +33,14 @@ fn it_expands_filters() {
..Default::default()
};
- let ast = Arc::into_inner(EntityFilterAst::new_from_filters(f).unwrap().unwrap().inner)
- .unwrap()
- .document_filter
- .unwrap();
+ let ast = Arc::into_inner(
+ EntityFilterAst::new_from_filters(f)
+ .unwrap()
+ .unwrap()
+ .document_filter
+ .unwrap(),
+ )
+ .unwrap();
let json = serde_json::to_value(ast).unwrap();
let exp = json!({
diff --git a/rust/cloud-storage/item_filters/src/lib.rs b/rust/cloud-storage/item_filters/src/lib.rs
index 46a139f686..e47ee5ed88 100644
--- a/rust/cloud-storage/item_filters/src/lib.rs
+++ b/rust/cloud-storage/item_filters/src/lib.rs
@@ -2,29 +2,16 @@
//! This crate contains all filters for various item types to be used in soup/search.
use non_empty::IsEmpty;
-use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use strum::{Display, EnumString};
-use utoipa::ToSchema;
pub mod ast;
/// Fields that can be searched on in search queries
-#[derive(
- Serialize,
- Deserialize,
- Debug,
- ToSchema,
- Copy,
- Clone,
- EnumString,
- Display,
- PartialEq,
- JsonSchema,
- Default,
-)]
+#[derive(Serialize, Deserialize, Debug, Copy, Clone, EnumString, Display, PartialEq, Default)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema, schemars::JsonSchema))]
pub enum SearchOn {
/// Search on the name/title field only
Name,
@@ -36,7 +23,8 @@ pub enum SearchOn {
}
/// The document filters used to filter down what documents you search over.
-#[derive(Debug, Serialize, Deserialize, ToSchema, Default, PartialEq, Clone, JsonSchema)]
+#[derive(Debug, Serialize, Deserialize, Default, PartialEq, Clone)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema, schemars::JsonSchema))]
pub struct DocumentFilters {
/// Document file types to search. Examples: ['pdf'], ['md', 'txt']. Empty to search all file types.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
@@ -72,7 +60,8 @@ impl IsEmpty for DocumentFilters {
}
/// The chat filters used to filter down what chats you search over.
-#[derive(Debug, Serialize, Deserialize, ToSchema, Default, PartialEq, Clone, JsonSchema)]
+#[derive(Debug, Serialize, Deserialize, Default, PartialEq, Clone)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema, schemars::JsonSchema))]
pub struct ChatFilters {
/// Chat message roles to search. Examples: ['user'], ['assistant']. Empty to search all roles.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
@@ -104,7 +93,8 @@ impl IsEmpty for ChatFilters {
}
/// The email filters used to filter down what emails you search over.
-#[derive(Debug, Serialize, Deserialize, ToSchema, Default, PartialEq, Clone, JsonSchema)]
+#[derive(Debug, Serialize, Deserialize, Default, PartialEq, Clone)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema, schemars::JsonSchema))]
pub struct EmailFilters {
/// Email sender addresses to filter by. Examples: ['[email protected]']. Empty to search all senders.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
@@ -133,7 +123,8 @@ impl IsEmpty for EmailFilters {
}
/// The channel message filters used to filter down what channel messages you search over.
-#[derive(Debug, Serialize, Deserialize, ToSchema, Default, PartialEq, Clone, JsonSchema)]
+#[derive(Debug, Serialize, Deserialize, Default, PartialEq, Clone)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema, schemars::JsonSchema))]
pub struct ChannelFilters {
/// Channel thread IDs to search within. Examples: ['thread123']. Empty to search all threads.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
@@ -170,7 +161,8 @@ impl IsEmpty for ChannelFilters {
}
/// The project filters used to filter down what projects you search over.
-#[derive(Debug, Serialize, Deserialize, ToSchema, Default, PartialEq, Clone, JsonSchema)]
+#[derive(Debug, Serialize, Deserialize, Default, PartialEq, Clone)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema, schemars::JsonSchema))]
pub struct ProjectFilters {
/// Project IDs to search within. Examples: ['project1']. Empty to search all accessible projects.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
@@ -192,7 +184,8 @@ impl IsEmpty for ProjectFilters {
}
/// a bundle of all of the filters for each entity type
-#[derive(Debug, Clone, Default, Deserialize, ToSchema)]
+#[derive(Debug, Clone, Default, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema, schemars::JsonSchema))]
pub struct EntityFilters {
/// the bundled [ProjectFilters]
#[serde(default)]
diff --git a/rust/cloud-storage/macro_user_id/src/email.rs b/rust/cloud-storage/macro_user_id/src/email.rs
index 2da73bb0ce..a082cb35ce 100644
--- a/rust/cloud-storage/macro_user_id/src/email.rs
+++ b/rust/cloud-storage/macro_user_id/src/email.rs
@@ -113,6 +113,15 @@ pub struct EmailStr<'a>(pub Email<ArcCowStr<'a>>);
impl<'a> doppleganger::Primitive for EmailStr<'a> {}
+impl<'a> EmailStr<'a> {
+ /// parse the inner value from the input string
+ pub fn parse_from_str(s: &'a str) -> Result<Self, ParseErr> {
+ <Email<ArcCowStr>>::parse_from_str(s)
+ .map(EmailStr)
+ .map_err(ParseErr::from)
+ }
+}
+
impl TryFrom<String> for EmailStr<'static> {
type Error = ParseErr;
diff --git a/rust/cloud-storage/models_pagination/src/cursor.rs b/rust/cloud-storage/models_pagination/src/cursor.rs
index a707d654e3..d8e2ef1aae 100644
--- a/rust/cloud-storage/models_pagination/src/cursor.rs
+++ b/rust/cloud-storage/models_pagination/src/cursor.rs
@@ -455,3 +455,38 @@ impl<I, T: Sortable, F> Query<I, T, F> {
}
}
}
+
+impl<I, T, F> Query<I, T, Option<F>>
+where
+ T: Sortable,
+{
+ /// Factors out an [Option] from the filter, splitting the type into an [Either]
+ pub fn split_option(self) -> Either<Query<I, T, ()>, Query<I, T, F>> {
+ match self {
+ Query::Sort(t, None) => Either::Left(Query::Sort(t, ())),
+ Query::Sort(t, Some(f)) => Either::Right(Query::Sort(t, f)),
+ Query::Cursor(Cursor {
+ id,
+ limit,
+ val,
+ filter: None,
+ }) => Either::Left(Query::Cursor(Cursor {
+ id,
+ limit,
+ val,
+ filter: (),
+ })),
+ Query::Cursor(Cursor {
+ id,
+ limit,
+ val,
+ filter: Some(f),
+ }) => Either::Right(Query::Cursor(Cursor {
+ id,
+ limit,
+ val,
+ filter: f,
+ })),
+ }
+ }
+}
diff --git a/rust/cloud-storage/models_search/Cargo.toml b/rust/cloud-storage/models_search/Cargo.toml
index d0e21dc09b..d18b930696 100644
--- a/rust/cloud-storage/models_search/Cargo.toml
+++ b/rust/cloud-storage/models_search/Cargo.toml
@@ -6,9 +6,9 @@ version = "0.1.0"
[dependencies]
chrono = { workspace = true }
-item_filters = { path = "../item_filters" }
-opensearch_client = { path = "../opensearch_client" }
+item_filters = { path = "../item_filters", features = ["schema"] }
models_opensearch = { path = "../models_opensearch" }
+opensearch_client = { path = "../opensearch_client" }
schemars = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
diff --git a/rust/cloud-storage/soup/src/domain/models.rs b/rust/cloud-storage/soup/src/domain/models.rs
index b741253472..2252ee9dfc 100644
--- a/rust/cloud-storage/soup/src/domain/models.rs
+++ b/rust/cloud-storage/soup/src/domain/models.rs
@@ -115,6 +115,8 @@ pub struct SoupRequest {
}
impl SoupRequest {
+ /// take the parts of the [SoupRequest] that are only relevant to email
+ /// and move them into a [GetEmailsRequest] if it is possible to create one
pub(crate) fn build_email_request(&self) -> Option<GetEmailsRequest> {
Some(GetEmailsRequest {
view: self.email_preview_view.clone(),
@@ -122,20 +124,22 @@ impl SoupRequest {
macro_id: self.user.clone(),
limit: Some(self.limit as u32),
query: match &self.cursor {
- SoupQuery::Simple(Query::Sort(t, _f)) => Some(Query::Sort(*t, ())),
+ SoupQuery::Simple(Query::Sort(t, f)) => Some(Query::Sort(
+ *t,
+ f.as_ref().and_then(|f| f.email_filter.clone()),
+ )),
SoupQuery::Simple(Query::Cursor(CursorWithValAndFilter {
id,
limit,
val,
- filter: _,
+ filter,
})) => Some(Query::Cursor(CursorWithValAndFilter {
id: *id,
limit: *limit,
val: val.clone(),
- filter: (),
+ filter: filter.as_ref().and_then(|f| f.email_filter.clone()),
})),
// we don't yet have sort by frecency implemented for emails yet
- // so we fallback to viewedupdated
SoupQuery::Frecency(_) => None,
}?,
})
diff --git a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/dynamic.rs b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/dynamic.rs
index 4af07b52d0..15726c0c9c 100644
--- a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/dynamic.rs
+++ b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/dynamic.rs
@@ -267,23 +267,19 @@ fn build_query(filter_ast: &EntityFilterAst, exclude_frecency: bool) -> QueryBui
// Document clause
builder.push(DOCUMENT_CLAUSE);
- builder.push(build_document_filter(
- filter_ast.inner.document_filter.as_ref(),
- ));
+ builder.push(build_document_filter(filter_ast.document_filter.as_deref()));
builder.push(" UNION ALL ");
// Chat clause
builder.push(CHAT_CLAUSE);
- builder.push(build_chat_filter(filter_ast.inner.chat_filter.as_ref()));
+ builder.push(build_chat_filter(filter_ast.chat_filter.as_deref()));
builder.push(" UNION ALL ");
// Project clause
builder.push(PROJECT_CLAUSE);
- builder.push(build_project_filter(
- filter_ast.inner.project_filter.as_ref(),
- ));
+ builder.push(build_project_filter(filter_ast.project_filter.as_deref()));
builder.push(") ");