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(email-service): List, remove, upsert scheduled drafts (#974)

Evan Hutnike405dc1a8412
diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-ac72213b35da176efad40d8acc0b77bede612a071cd8b18bb8d68965c1414204.json b/rust/cloud-storage/email_db_client/.sqlx/query-ac72213b35da176efad40d8acc0b77bede612a071cd8b18bb8d68965c1414204.json
new file mode 100644
index 0000000000..63cf281d00
--- /dev/null
+++ b/rust/cloud-storage/email_db_client/.sqlx/query-ac72213b35da176efad40d8acc0b77bede612a071cd8b18bb8d68965c1414204.json
@@ -0,0 +1,174 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n m.id,\n m.provider_id,\n m.global_id,\n m.thread_id,\n m.provider_thread_id,\n m.replying_to_id,\n m.link_id,\n m.provider_history_id,\n m.internal_date_ts,\n m.snippet,\n m.size_estimate,\n m.subject,\n m.from_name,\n m.from_contact_id,\n m.sent_at,\n m.has_attachments,\n m.is_read,\n m.is_starred,\n m.is_sent,\n m.is_draft,\n m.body_text,\n m.body_html_sanitized,\n m.body_macro,\n m.headers_jsonb,\n m.created_at,\n m.updated_at\n FROM email_messages m\n JOIN email_scheduled_messages sm ON m.id = sm.message_id\n WHERE m.link_id = $1 AND sm.sent = false\n ORDER BY m.created_at DESC\n LIMIT $2 OFFSET $3\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "provider_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "global_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "thread_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 4,
+ "name": "provider_thread_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "replying_to_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 6,
+ "name": "link_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 7,
+ "name": "provider_history_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 8,
+ "name": "internal_date_ts",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 9,
+ "name": "snippet",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 10,
+ "name": "size_estimate",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 11,
+ "name": "subject",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 12,
+ "name": "from_name",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 13,
+ "name": "from_contact_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 14,
+ "name": "sent_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 15,
+ "name": "has_attachments",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 16,
+ "name": "is_read",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 17,
+ "name": "is_starred",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 18,
+ "name": "is_sent",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 19,
+ "name": "is_draft",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 20,
+ "name": "body_text",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 21,
+ "name": "body_html_sanitized",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 22,
+ "name": "body_macro",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 23,
+ "name": "headers_jsonb",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 24,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 25,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Int8",
+ "Int8"
+ ]
+ },
+ "nullable": [
+ false,
+ true,
+ true,
+ false,
+ true,
+ true,
+ false,
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ false,
+ false,
+ false,
+ false,
+ false,
+ true,
+ true,
+ true,
+ true,
+ false,
+ false
+ ]
+ },
+ "hash": "ac72213b35da176efad40d8acc0b77bede612a071cd8b18bb8d68965c1414204"
+}
diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-326921c8d4c376b76fec155370092b00ce0572b34c5a6243ef9001fd4a9f1a75.json b/rust/cloud-storage/email_db_client/.sqlx/query-b8b844a48297ecdd487dde0f6057c97793378b825cf227dd6f891e27e87a987a.json
similarity index 77%
rename from rust/cloud-storage/email_db_client/.sqlx/query-326921c8d4c376b76fec155370092b00ce0572b34c5a6243ef9001fd4a9f1a75.json
rename to rust/cloud-storage/email_db_client/.sqlx/query-b8b844a48297ecdd487dde0f6057c97793378b825cf227dd6f891e27e87a987a.json
index becd36a7d8..ca5719693b 100644
--- a/rust/cloud-storage/email_db_client/.sqlx/query-326921c8d4c376b76fec155370092b00ce0572b34c5a6243ef9001fd4a9f1a75.json
+++ b/rust/cloud-storage/email_db_client/.sqlx/query-b8b844a48297ecdd487dde0f6057c97793378b825cf227dd6f891e27e87a987a.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT \n id,\n provider_id,\n global_id,\n thread_id,\n provider_thread_id,\n replying_to_id,\n link_id,\n provider_history_id,\n internal_date_ts,\n snippet,\n size_estimate,\n subject,\n from_name,\n from_contact_id,\n sent_at,\n has_attachments,\n is_read,\n is_starred,\n is_sent,\n is_draft,\n body_text,\n body_html_sanitized,\n body_macro,\n headers_jsonb,\n created_at,\n updated_at\n FROM email_messages\n WHERE thread_id = $1\n ORDER BY internal_date_ts DESC\n LIMIT $2 OFFSET $3\n ",
+ "query": "\n SELECT\n id,\n provider_id,\n global_id,\n thread_id,\n provider_thread_id,\n replying_to_id,\n link_id,\n provider_history_id,\n internal_date_ts,\n snippet,\n size_estimate,\n subject,\n from_name,\n from_contact_id,\n sent_at,\n has_attachments,\n is_read,\n is_starred,\n is_sent,\n is_draft,\n body_text,\n body_html_sanitized,\n body_macro,\n headers_jsonb,\n created_at,\n updated_at\n FROM email_messages\n WHERE thread_id = $1\n ORDER BY internal_date_ts DESC\n LIMIT $2 OFFSET $3\n ",
"describe": {
"columns": [
{
@@ -170,5 +170,5 @@
false
]
},
- "hash": "326921c8d4c376b76fec155370092b00ce0572b34c5a6243ef9001fd4a9f1a75"
+ "hash": "b8b844a48297ecdd487dde0f6057c97793378b825cf227dd6f891e27e87a987a"
}
diff --git a/rust/cloud-storage/email_db_client/fixtures/get_scheduled_db_messages.sql b/rust/cloud-storage/email_db_client/fixtures/get_scheduled_db_messages.sql
new file mode 100644
index 0000000000..12a2c46633
--- /dev/null
+++ b/rust/cloud-storage/email_db_client/fixtures/get_scheduled_db_messages.sql
@@ -0,0 +1,157 @@
+-- SQL fixture for get_scheduled_db_messages_by_link_id tests
+-- Tests fetching unsent scheduled messages with pagination
+
+------------------------------------------------------------
+-- Link 1: Primary test link with multiple scheduled messages
+------------------------------------------------------------
+
+INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-000000000001', 'macro|[email protected]', '00000000-0000-0000-0000-0000000a0001',
+ '[email protected]', 'GMAIL', true, NOW(), NOW());
+
+-- Contact for link 1
+INSERT INTO email_contacts (id, link_id, email_address, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-0000000c0001', '00000000-0000-0000-0000-000000000001',
+ '[email protected]', NOW(), NOW());
+
+-- Thread for link 1
+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-0000000b0001', '00000000-0000-0000-0000-000000000001',
+ true, false, NOW(), NOW());
+
+------------------------------------------------------------
+-- Message 1: Unsent scheduled message (oldest)
+------------------------------------------------------------
+
+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts,
+ has_attachments, is_read, is_starred, is_draft, subject, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-0000000d0001',
+ '00000000-0000-0000-0000-0000000b0001',
+ '00000000-0000-0000-0000-000000000001',
+ 'provider-msg-001',
+ FALSE,
+ '00000000-0000-0000-0000-0000000c0001',
+ '2025-01-01 10:00:00 +00:00',
+ false, false, false, true,
+ 'Oldest scheduled message',
+ NOW() - INTERVAL '3 days', NOW() - INTERVAL '3 days');
+
+INSERT INTO email_scheduled_messages (link_id, message_id, send_time, sent, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-0000000d0001',
+ NOW() + INTERVAL '1 day', false, NOW(), NOW());
+
+------------------------------------------------------------
+-- Message 2: Unsent scheduled message (middle)
+------------------------------------------------------------
+
+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts,
+ has_attachments, is_read, is_starred, is_draft, subject, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-0000000d0002',
+ '00000000-0000-0000-0000-0000000b0001',
+ '00000000-0000-0000-0000-000000000001',
+ 'provider-msg-002',
+ FALSE,
+ '00000000-0000-0000-0000-0000000c0001',
+ '2025-01-02 10:00:00 +00:00',
+ false, false, false, true,
+ 'Middle scheduled message',
+ NOW() - INTERVAL '2 days', NOW() - INTERVAL '2 days');
+
+INSERT INTO email_scheduled_messages (link_id, message_id, send_time, sent, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-0000000d0002',
+ NOW() + INTERVAL '2 days', false, NOW(), NOW());
+
+------------------------------------------------------------
+-- Message 3: Unsent scheduled message (newest)
+------------------------------------------------------------
+
+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts,
+ has_attachments, is_read, is_starred, is_draft, subject, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-0000000d0003',
+ '00000000-0000-0000-0000-0000000b0001',
+ '00000000-0000-0000-0000-000000000001',
+ 'provider-msg-003',
+ FALSE,
+ '00000000-0000-0000-0000-0000000c0001',
+ '2025-01-03 10:00:00 +00:00',
+ false, false, false, true,
+ 'Newest scheduled message',
+ NOW() - INTERVAL '1 day', NOW() - INTERVAL '1 day');
+
+INSERT INTO email_scheduled_messages (link_id, message_id, send_time, sent, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-0000000d0003',
+ NOW() + INTERVAL '3 days', false, NOW(), NOW());
+
+------------------------------------------------------------
+-- Message 4: ALREADY SENT scheduled message (should be excluded)
+------------------------------------------------------------
+
+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts,
+ has_attachments, is_read, is_starred, is_draft, subject, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-0000000d0004',
+ '00000000-0000-0000-0000-0000000b0001',
+ '00000000-0000-0000-0000-000000000001',
+ 'provider-msg-004',
+ TRUE,
+ '00000000-0000-0000-0000-0000000c0001',
+ '2025-01-04 10:00:00 +00:00',
+ false, true, false, false,
+ 'Already sent message',
+ NOW() - INTERVAL '5 days', NOW() - INTERVAL '4 days');
+
+INSERT INTO email_scheduled_messages (link_id, message_id, send_time, sent, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-0000000d0004',
+ NOW() - INTERVAL '4 days', true, NOW(), NOW());
+
+------------------------------------------------------------
+-- Message 5: Regular message (NOT scheduled, should be excluded)
+------------------------------------------------------------
+
+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts,
+ has_attachments, is_read, is_starred, is_draft, subject, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-0000000d0005',
+ '00000000-0000-0000-0000-0000000b0001',
+ '00000000-0000-0000-0000-000000000001',
+ 'provider-msg-005',
+ TRUE,
+ '00000000-0000-0000-0000-0000000c0001',
+ '2025-01-05 10:00:00 +00:00',
+ false, true, false, false,
+ 'Regular non-scheduled message',
+ NOW(), NOW());
+
+------------------------------------------------------------
+-- Link 2: Different user (for isolation test)
+------------------------------------------------------------
+
+INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider, is_sync_active, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-000000000002', 'macro|[email protected]', '00000000-0000-0000-0000-0000000a0002',
+ '[email protected]', 'GMAIL', true, NOW(), NOW());
+
+-- Contact for link 2
+INSERT INTO email_contacts (id, link_id, email_address, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-0000000c0002', '00000000-0000-0000-0000-000000000002',
+ '[email protected]', NOW(), NOW());
+
+-- Thread for link 2
+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-0000000b0002', '00000000-0000-0000-0000-000000000002',
+ true, false, NOW(), NOW());
+
+-- Scheduled message for link 2 (should NOT appear in link 1 queries)
+INSERT INTO email_messages (id, thread_id, link_id, provider_id, is_sent, from_contact_id, internal_date_ts,
+ has_attachments, is_read, is_starred, is_draft, subject, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-0000000d0006',
+ '00000000-0000-0000-0000-0000000b0002',
+ '00000000-0000-0000-0000-000000000002',
+ 'provider-msg-006',
+ FALSE,
+ '00000000-0000-0000-0000-0000000c0002',
+ '2025-01-06 10:00:00 +00:00',
+ false, false, false, true,
+ 'Other user scheduled message',
+ NOW(), NOW());
+
+INSERT INTO email_scheduled_messages (link_id, message_id, send_time, sent, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-000000000002', '00000000-0000-0000-0000-0000000d0006',
+ NOW() + INTERVAL '1 day', false, NOW(), NOW());
\ No newline at end of file
diff --git a/rust/cloud-storage/email_db_client/src/messages/get.rs b/rust/cloud-storage/email_db_client/src/messages/get.rs
index fe4bbd7398..9da873c5fe 100644
--- a/rust/cloud-storage/email_db_client/src/messages/get.rs
+++ b/rust/cloud-storage/email_db_client/src/messages/get.rs
@@ -1,11 +1,14 @@
use std::collections::HashMap;
-use crate::contacts;
use crate::labels::get;
use crate::parse::db_to_service;
+use crate::parse::db_to_service::map_attachmentless_db_message_to_service;
+use crate::{attachments, contacts, labels, messages};
use anyhow::Context;
+use futures::future::try_join_all;
use models_email::email::db;
use models_email::email::service::message::Message;
+use models_email::service;
use models_email::service::address::ContactInfo;
use models_email::service::message::{MessageSenderInfo, MessageToSend};
use sqlx::PgPool;
@@ -442,3 +445,132 @@ pub async fn draft_exists_with_id(
Ok(exists)
}
+
+/// Fetches messages for a thread with pagination
+#[tracing::instrument(skip(pool), err)]
+pub async fn get_messages_by_thread_id(
+ pool: &PgPool,
+ thread_db_id: Uuid,
+ offset: i64,
+ limit: i64,
+) -> anyhow::Result<Vec<db::message::Message>> {
+ let db_messages = sqlx::query_as!(
+ db::message::Message,
+ r#"
+ SELECT
+ id,
+ provider_id,
+ global_id,
+ thread_id,
+ provider_thread_id,
+ replying_to_id,
+ link_id,
+ provider_history_id,
+ internal_date_ts,
+ snippet,
+ size_estimate,
+ subject,
+ from_name,
+ from_contact_id,
+ sent_at,
+ has_attachments,
+ is_read,
+ is_starred,
+ is_sent,
+ is_draft,
+ body_text,
+ body_html_sanitized,
+ body_macro,
+ headers_jsonb,
+ created_at,
+ updated_at
+ FROM email_messages
+ WHERE thread_id = $1
+ ORDER BY internal_date_ts DESC
+ LIMIT $2 OFFSET $3
+ "#,
+ thread_db_id,
+ limit,
+ offset
+ )
+ .fetch_all(pool)
+ .await
+ .with_context(|| {
+ format!(
+ "Failed to fetch paginated messages for thread DB ID {}",
+ thread_db_id
+ )
+ })?;
+
+ Ok(db_messages)
+}
+
+/// Converts a list of db messages to service messages by fetching associated data concurrently
+pub async fn convert_db_messages_to_service(
+ pool: &PgPool,
+ db_messages: Vec<db::message::Message>,
+) -> anyhow::Result<Vec<service::message::Message>> {
+ let message_processing_futures = db_messages.into_iter().map(|db_message| {
+ let pool_clone = pool.clone();
+ async move { get_service_message_data(&pool_clone, db_message).await }
+ });
+
+ try_join_all(message_processing_futures)
+ .await
+ .context("Failed processing messages concurrently")
+}
+
+/// Fetches associated data for a db message and converts it to a service message
+#[tracing::instrument(skip(pool, db_message), err)]
+pub async fn get_service_message_data(
+ pool: &PgPool,
+ db_message: db::message::Message,
+) -> anyhow::Result<service::message::Message> {
+ // fetch data from each table concurrently
+ let (
+ sender_res,
+ recipients_res,
+ scheduled_res,
+ labels_res,
+ attachments_res,
+ macro_attachments_res,
+ draft_attachments_res,
+ ) = tokio::try_join!(
+ contacts::get::get_sender_by_message_id(pool, db_message.id),
+ contacts::get::fetch_db_recipients(pool, db_message.id),
+ messages::scheduled::get::get_scheduled_message_no_auth(pool, db_message.id),
+ labels::get::fetch_message_labels(pool, db_message.id),
+ async {
+ if db_message.has_attachments {
+ attachments::provider::fetch_db_attachments(pool, db_message.id).await
+ } else {
+ Ok(Vec::new())
+ }
+ },
+ async { attachments::marco::fetch_db_macro_attachments(pool, db_message.id).await },
+ async {
+ // only need to check if the message is a draft created in Macro
+ if db_message.is_draft && db_message.provider_id.is_none() {
+ attachments::draft::fetch_db_draft_attachments(pool, db_message.id).await
+ } else {
+ Ok(Vec::new())
+ }
+ },
+ )?;
+
+ let service_message = map_attachmentless_db_message_to_service(
+ db_message,
+ sender_res,
+ recipients_res,
+ scheduled_res,
+ labels_res,
+ );
+
+ // parse db-layer structs into service-layer message struct
+ db_to_service::map_db_message_attachments_to_service(
+ service_message,
+ attachments_res,
+ macro_attachments_res,
+ draft_attachments_res,
+ )
+}
diff --git a/rust/cloud-storage/email_db_client/src/messages/insert.rs b/rust/cloud-storage/email_db_client/src/messages/insert.rs
index 61d46db148..cef6f00771 100644
--- a/rust/cloud-storage/email_db_client/src/messages/insert.rs
+++ b/rust/cloud-storage/email_db_client/src/messages/insert.rs
@@ -1,6 +1,7 @@
use crate::attachments::{marco, provider};
use crate::messages::replying_to_id;
-use crate::messages::scheduled::{delete_scheduled_message, upsert_scheduled_message};
+use crate::messages::scheduled::delete::delete_scheduled_message;
+use crate::messages::scheduled::upsert::upsert_scheduled_message;
use crate::parse::service_to_db::{addresses_from_message, map_message_to_send_to_db};
use crate::{contacts, labels, parse, threads};
use anyhow::Context;
diff --git a/rust/cloud-storage/email_db_client/src/messages/scheduled.rs b/rust/cloud-storage/email_db_client/src/messages/scheduled.rs
deleted file mode 100644
index 836c998431..0000000000
--- a/rust/cloud-storage/email_db_client/src/messages/scheduled.rs
+++ /dev/null
@@ -1,167 +0,0 @@
-use anyhow::Context;
-use models_email::{db, service};
-
-/// Upserts a scheduled message entry
-#[tracing::instrument(skip(tx, scheduled_message))]
-pub async fn upsert_scheduled_message(
- tx: &mut sqlx::PgConnection,
- scheduled_message: service::message::ScheduledMessage,
-) -> anyhow::Result<()> {
- let db_message = db::message::ScheduledMessage::from(scheduled_message);
- sqlx::query!(
- r#"
- INSERT INTO email_scheduled_messages (
- link_id, message_id, send_time, sent,
- created_at, updated_at
- )
- VALUES ($1, $2, $3, $4, NOW(), NOW())
- ON CONFLICT (link_id, message_id) DO UPDATE SET
- send_time = EXCLUDED.send_time,
- sent = EXCLUDED.sent,
- updated_at = NOW()
- "#,
- db_message.link_id,
- db_message.message_id,
- db_message.send_time,
- db_message.sent,
- )
- .execute(&mut *tx)
- .await
- .with_context(|| {
- format!(
- "Failed to upsert scheduled message with link_id {} and message_id {}",
- db_message.link_id, db_message.message_id
- )
- })?;
-
- Ok(())
-}
-
-/// Marks a scheduled message as sent
-#[tracing::instrument(skip(executor))]
-pub async fn mark_scheduled_message_as_sent<'e, E>(
- executor: E,
- link_id: sqlx::types::Uuid,
- message_id: sqlx::types::Uuid,
-) -> anyhow::Result<bool>
-where
- E: sqlx::Executor<'e, Database = sqlx::Postgres>,
-{
- let result = sqlx::query!(
- r#"
- UPDATE email_scheduled_messages
- SET
- sent = true,
- updated_at = NOW()
- WHERE link_id = $1 AND message_id = $2
- "#,
- link_id,
- message_id,
- )
- .execute(executor)
- .await
- .with_context(|| {
- format!(
- "Failed to mark scheduled message as sent with link_id {} and message_id {}",
- link_id, message_id
- )
- })?;
-
- // Return whether a row was actually updated
- Ok(result.rows_affected() > 0)
-}
-
-/// Deletes a scheduled message if it exists
-#[tracing::instrument(skip(tx))]
-pub async fn delete_scheduled_message(
- tx: &mut sqlx::PgConnection,
- link_id: sqlx::types::Uuid,
- message_id: sqlx::types::Uuid,
-) -> anyhow::Result<()> {
- sqlx::query!(
- r#"
- DELETE FROM email_scheduled_messages
- WHERE link_id = $1 AND message_id = $2
- "#,
- link_id,
- message_id,
- )
- .execute(&mut *tx)
- .await
- .with_context(|| {
- format!(
- "Failed to delete scheduled message with link_id {} and message_id {}",
- link_id, message_id
- )
- })?;
-
- Ok(())
-}
-
-/// Retrieves a scheduled message by link_id and message_id
-/// Returns None if the message doesn't exist
-#[tracing::instrument(skip(db))]
-pub async fn get_scheduled_message(
- db: &sqlx::PgPool,
- link_id: sqlx::types::Uuid,
- message_id: sqlx::types::Uuid,
-) -> anyhow::Result<Option<service::message::ScheduledMessage>> {
- let record = sqlx::query!(
- r#"
- SELECT link_id, message_id, send_time, sent
- FROM email_scheduled_messages
- WHERE link_id = $1 AND message_id = $2
- "#,
- link_id,
- message_id,
- )
- .fetch_optional(db)
- .await
- .with_context(|| {
- format!(
- "Failed to retrieve scheduled message with link_id {} and message_id {}",
- link_id, message_id
- )
- })?;
-
- // Convert the database record to a ScheduledMessage struct if found
- Ok(record.map(|r| service::message::ScheduledMessage {
- link_id: r.link_id,
- message_id: r.message_id,
- send_time: r.send_time,
- sent: r.sent,
- }))
-}
-
-/// Retrieves scheduled messages for drafts that have not been sent yet. used for populating
-/// messages in get thread by id endpoint
-#[tracing::instrument(skip(db))]
-pub async fn get_scheduled_message_no_auth(
- db: &sqlx::PgPool,
- message_id: sqlx::types::Uuid,
-) -> anyhow::Result<Option<db::message::ScheduledMessage>> {
- let record = sqlx::query!(
- r#"
- SELECT link_id, message_id, send_time, sent
- FROM email_scheduled_messages
- WHERE message_id = $1 and sent = false
- "#,
- message_id,
- )
- .fetch_optional(db)
- .await
- .with_context(|| {
- format!(
- "Failed to retrieve scheduled message with message_id {}",
- message_id
- )
- })?;
-
- // Convert the database record to a ScheduledMessage struct if found
- Ok(record.map(|r| db::message::ScheduledMessage {
- link_id: r.link_id,
- message_id: r.message_id,
- send_time: r.send_time,
- sent: r.sent,
- }))
-}
diff --git a/rust/cloud-storage/email_db_client/src/messages/scheduled/delete.rs b/rust/cloud-storage/email_db_client/src/messages/scheduled/delete.rs
new file mode 100644
index 0000000000..da106f1a1f
--- /dev/null
+++ b/rust/cloud-storage/email_db_client/src/messages/scheduled/delete.rs
@@ -0,0 +1,25 @@
+use sqlx::types::Uuid;
+
+/// Deletes a scheduled message if it exists
+#[tracing::instrument(skip(executor), err)]
+pub async fn delete_scheduled_message<'e, E>(
+ executor: E,
+ link_id: Uuid,
+ message_id: Uuid,
+) -> anyhow::Result<()>
+where
+ E: sqlx::Executor<'e, Database = sqlx::Postgres>,
+{
+ sqlx::query!(
+ r#"
+ DELETE FROM email_scheduled_messages
+ WHERE link_id = $1 AND message_id = $2
+ "#,
+ link_id,
+ message_id,
+ )
+ .execute(executor)
+ .await?;
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/email_db_client/src/messages/scheduled/get.rs b/rust/cloud-storage/email_db_client/src/messages/scheduled/get.rs
new file mode 100644
index 0000000000..a640ea0918
--- /dev/null
+++ b/rust/cloud-storage/email_db_client/src/messages/scheduled/get.rs
@@ -0,0 +1,123 @@
+use crate::messages::get::convert_db_messages_to_service;
+use models_email::{db, service};
+use sqlx::PgPool;
+use sqlx::types::Uuid;
+
+/// Retrieves a scheduled message by link_id and message_id
+/// Returns None if the message doesn't exist
+#[tracing::instrument(skip(db), err)]
+pub async fn get_scheduled_message<'e, E>(
+ db: E,
+ link_id: Uuid,
+ message_id: Uuid,
+) -> anyhow::Result<Option<service::message::ScheduledMessage>>
+where
+ E: sqlx::Executor<'e, Database = sqlx::Postgres>,
+{
+ let record = sqlx::query_as!(
+ service::message::ScheduledMessage,
+ r#"
+ SELECT link_id, message_id, send_time, sent
+ FROM email_scheduled_messages
+ WHERE link_id = $1 AND message_id = $2
+ "#,
+ link_id,
+ message_id,
+ )
+ .fetch_optional(db)
+ .await?;
+
+ Ok(record)
+}
+
+/// Retrieves scheduled messages for drafts that have not been sent yet. used for populating
+/// messages in get thread by id endpoint
+#[tracing::instrument(skip(db), err)]
+pub async fn get_scheduled_message_no_auth(
+ db: &sqlx::PgPool,
+ message_id: sqlx::types::Uuid,
+) -> anyhow::Result<Option<db::message::ScheduledMessage>> {
+ let record = sqlx::query_as!(
+ db::message::ScheduledMessage,
+ r#"
+ SELECT link_id, message_id, send_time, sent
+ FROM email_scheduled_messages
+ WHERE message_id = $1 and sent = false
+ "#,
+ message_id,
+ )
+ .fetch_optional(db)
+ .await?;
+
+ Ok(record)
+}
+
+/// Fetches unsent scheduled messages for a link with pagination
+#[tracing::instrument(skip(pool), err)]
+pub async fn get_scheduled_messages_by_link_id(
+ pool: &PgPool,
+ link_id: Uuid,
+ offset: u32,
+ limit: u32,
+) -> anyhow::Result<Vec<service::message::Message>> {
+ if limit == 0 {
+ anyhow::bail!("limit must be positive");
+ }
+
+ let db_messages = get_scheduled_db_messages_by_link_id(pool, link_id, offset, limit).await?;
+ convert_db_messages_to_service(pool, db_messages).await
+}
+
+/// Fetches unsent scheduled db messages for a link with pagination
+#[tracing::instrument(skip(pool), err)]
+pub async fn get_scheduled_db_messages_by_link_id(
+ pool: &PgPool,
+ link_id: Uuid,
+ offset: u32,
+ limit: u32,
+) -> anyhow::Result<Vec<db::message::Message>> {
+ let db_messages = sqlx::query_as!(
+ db::message::Message,
+ r#"
+ SELECT
+ m.id,
+ m.provider_id,
+ m.global_id,
+ m.thread_id,
+ m.provider_thread_id,
+ m.replying_to_id,
+ m.link_id,
+ m.provider_history_id,
+ m.internal_date_ts,
+ m.snippet,
+ m.size_estimate,
+ m.subject,
+ m.from_name,
+ m.from_contact_id,
+ m.sent_at,
+ m.has_attachments,
+ m.is_read,
+ m.is_starred,
+ m.is_sent,
+ m.is_draft,
+ m.body_text,
+ m.body_html_sanitized,
+ m.body_macro,
+ m.headers_jsonb,
+ m.created_at,
+ m.updated_at
+ FROM email_messages m
+ JOIN email_scheduled_messages sm ON m.id = sm.message_id
+ WHERE m.link_id = $1 AND sm.sent = false
+ ORDER BY m.created_at DESC
+ LIMIT $2 OFFSET $3
+ "#,
+ link_id,
+ limit as i64,
+ offset as i64
+ )
+ .fetch_all(pool)
+ .await?;
+
+ Ok(db_messages)
+}
diff --git a/rust/cloud-storage/email_db_client/src/messages/scheduled/mod.rs b/rust/cloud-storage/email_db_client/src/messages/scheduled/mod.rs
new file mode 100644
index 0000000000..b99105e525
--- /dev/null
+++ b/rust/cloud-storage/email_db_client/src/messages/scheduled/mod.rs
@@ -0,0 +1,3 @@
+pub mod delete;
+pub mod get;
+pub mod upsert;
diff --git a/rust/cloud-storage/email_db_client/src/messages/scheduled/upsert.rs b/rust/cloud-storage/email_db_client/src/messages/scheduled/upsert.rs
new file mode 100644
index 0000000000..ea11f9976e
--- /dev/null
+++ b/rust/cloud-storage/email_db_client/src/messages/scheduled/upsert.rs
@@ -0,0 +1,59 @@
+use models_email::{db, service};
+
+/// Upserts a scheduled message entry
+#[tracing::instrument(skip(tx, scheduled_message), err)]
+pub async fn upsert_scheduled_message(
+ tx: &mut sqlx::PgConnection,
+ scheduled_message: service::message::ScheduledMessage,
+) -> anyhow::Result<()> {
+ let db_message = db::message::ScheduledMessage::from(scheduled_message);
+ sqlx::query!(
+ r#"
+ INSERT INTO email_scheduled_messages (
+ link_id, message_id, send_time, sent,
+ created_at, updated_at
+ )
+ VALUES ($1, $2, $3, $4, NOW(), NOW())
+ ON CONFLICT (link_id, message_id) DO UPDATE SET
+ send_time = EXCLUDED.send_time,
+ sent = EXCLUDED.sent,
+ updated_at = NOW()
+ "#,
+ db_message.link_id,
+ db_message.message_id,
+ db_message.send_time,
+ db_message.sent,
+ )
+ .execute(&mut *tx)
+ .await?;
+
+ Ok(())
+}
+
+/// Marks a scheduled message as sent
+#[tracing::instrument(skip(executor), err)]
+pub async fn mark_scheduled_message_as_sent<'e, E>(
+ executor: E,
+ link_id: sqlx::types::Uuid,
+ message_id: sqlx::types::Uuid,
+) -> anyhow::Result<bool>
+where
+ E: sqlx::Executor<'e, Database = sqlx::Postgres>,
+{
+ let result = sqlx::query!(
+ r#"
+ UPDATE email_scheduled_messages
+ SET
+ sent = true,
+ updated_at = NOW()
+ WHERE link_id = $1 AND message_id = $2
+ "#,
+ link_id,
+ message_id,
+ )
+ .execute(executor)
+ .await?;
+
+ // Return whether a row was actually updated
+ Ok(result.rows_affected() > 0)
+}
diff --git a/rust/cloud-storage/email_db_client/src/messages/test.rs b/rust/cloud-storage/email_db_client/src/messages/test.rs
index b9e6b56a42..1d10b24238 100644
--- a/rust/cloud-storage/email_db_client/src/messages/test.rs
+++ b/rust/cloud-storage/email_db_client/src/messages/test.rs
@@ -1,4 +1,5 @@
use crate::messages::get::draft_exists_with_id;
+use crate::messages::scheduled::get::get_scheduled_db_messages_by_link_id;
use macro_db_migrator::MACRO_DB_MIGRATIONS;
use sqlx::types::Uuid;
use sqlx::{Pool, Postgres};
@@ -71,3 +72,227 @@ async fn draft_exists_with_id_returns_false_for_nonexistent_message(
Ok(())
}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("get_scheduled_db_messages"))
+)]
+async fn get_scheduled_db_messages_returns_unsent_only(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000001")?;
+ let result = get_scheduled_db_messages_by_link_id(&pool, link_id, 0, 100).await?;
+
+ // Should return 3 unsent scheduled messages
+ assert_eq!(result.len(), 3);
+
+ // Verify all returned messages are unsent scheduled messages
+ let returned_ids: Vec<Uuid> = result.iter().map(|m| m.id).collect();
+
+ let unsent_1 = Uuid::parse_str("00000000-0000-0000-0000-0000000d0001")?;
+ let unsent_2 = Uuid::parse_str("00000000-0000-0000-0000-0000000d0002")?;
+ let unsent_3 = Uuid::parse_str("00000000-0000-0000-0000-0000000d0003")?;
+
+ assert!(
+ returned_ids.contains(&unsent_1),
+ "Should include unsent message 1"
+ );
+ assert!(
+ returned_ids.contains(&unsent_2),
+ "Should include unsent message 2"
+ );
+ assert!(
+ returned_ids.contains(&unsent_3),
+ "Should include unsent message 3"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("get_scheduled_db_messages"))
+)]
+async fn get_scheduled_db_messages_excludes_sent_messages(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000001")?;
+ let result = get_scheduled_db_messages_by_link_id(&pool, link_id, 0, 100).await?;
+
+ let returned_ids: Vec<Uuid> = result.iter().map(|m| m.id).collect();
+
+ // Already sent scheduled message should NOT be included
+ let sent_msg = Uuid::parse_str("00000000-0000-0000-0000-0000000d0004")?;
+ assert!(
+ !returned_ids.contains(&sent_msg),
+ "Should not include already sent message"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("get_scheduled_db_messages"))
+)]
+async fn get_scheduled_db_messages_excludes_non_scheduled_messages(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000001")?;
+ let result = get_scheduled_db_messages_by_link_id(&pool, link_id, 0, 100).await?;
+
+ let returned_ids: Vec<Uuid> = result.iter().map(|m| m.id).collect();
+
+ // Regular non-scheduled message should NOT be included
+ let regular_msg = Uuid::parse_str("00000000-0000-0000-0000-0000000d0005")?;
+ assert!(
+ !returned_ids.contains(&regular_msg),
+ "Should not include non-scheduled message"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("get_scheduled_db_messages"))
+)]
+async fn get_scheduled_db_messages_isolates_by_link_id(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000001")?;
+ let result = get_scheduled_db_messages_by_link_id(&pool, link_id, 0, 100).await?;
+
+ let returned_ids: Vec<Uuid> = result.iter().map(|m| m.id).collect();
+
+ // Message from other link should NOT be included
+ let other_link_msg = Uuid::parse_str("00000000-0000-0000-0000-0000000d0006")?;
+ assert!(
+ !returned_ids.contains(&other_link_msg),
+ "Should not include messages from other links"
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("get_scheduled_db_messages"))
+)]
+async fn get_scheduled_db_messages_orders_by_created_at_desc(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000001")?;
+ let result = get_scheduled_db_messages_by_link_id(&pool, link_id, 0, 100).await?;
+
+ // Should be ordered by created_at DESC (newest first)
+ assert_eq!(
+ result[0].subject,
+ Some("Newest scheduled message".to_string())
+ );
+ assert_eq!(
+ result[1].subject,
+ Some("Middle scheduled message".to_string())
+ );
+ assert_eq!(
+ result[2].subject,
+ Some("Oldest scheduled message".to_string())
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("get_scheduled_db_messages"))
+)]
+async fn get_scheduled_db_messages_respects_limit(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000001")?;
+
+ // Request only 2 messages
+ let result = get_scheduled_db_messages_by_link_id(&pool, link_id, 0, 2).await?;
+
+ assert_eq!(result.len(), 2);
+
+ // Should return the 2 newest (ordered by created_at DESC)
+ assert_eq!(
+ result[0].subject,
+ Some("Newest scheduled message".to_string())
+ );
+ assert_eq!(
+ result[1].subject,
+ Some("Middle scheduled message".to_string())
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("get_scheduled_db_messages"))
+)]
+async fn get_scheduled_db_messages_respects_offset(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000001")?;
+
+ // Skip first 2 messages
+ let result = get_scheduled_db_messages_by_link_id(&pool, link_id, 2, 100).await?;
+
+ assert_eq!(result.len(), 1);
+
+ // Should return only the oldest message
+ assert_eq!(
+ result[0].subject,
+ Some("Oldest scheduled message".to_string())
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("get_scheduled_db_messages"))
+)]
+async fn get_scheduled_db_messages_pagination_works(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000001")?;
+
+ // Page 1: limit 1, offset 0
+ let page1 = get_scheduled_db_messages_by_link_id(&pool, link_id, 0, 1).await?;
+ assert_eq!(page1.len(), 1);
+ assert_eq!(
+ page1[0].subject,
+ Some("Newest scheduled message".to_string())
+ );
+
+ // Page 2: limit 1, offset 1
+ let page2 = get_scheduled_db_messages_by_link_id(&pool, link_id, 1, 1).await?;
+ assert_eq!(page2.len(), 1);
+ assert_eq!(
+ page2[0].subject,
+ Some("Middle scheduled message".to_string())
+ );
+
+ // Page 3: limit 1, offset 2
+ let page3 = get_scheduled_db_messages_by_link_id(&pool, link_id, 2, 1).await?;
+ assert_eq!(page3.len(), 1);
+ assert_eq!(
+ page3[0].subject,
+ Some("Oldest scheduled message".to_string())
+ );
+
+ // Page 4: limit 1, offset 3 (no more results)
+ let page4 = get_scheduled_db_messages_by_link_id(&pool, link_id, 3, 1).await?;
+ assert!(page4.is_empty());
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("get_scheduled_db_messages"))
+)]
+async fn get_scheduled_db_messages_returns_empty_for_nonexistent_link(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let nonexistent_link_id = Uuid::parse_str("00000000-0000-0000-0000-999999999999")?;
+ let result = get_scheduled_db_messages_by_link_id(&pool, nonexistent_link_id, 0, 100).await?;
+
+ assert!(result.is_empty());
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/email_db_client/src/threads/get.rs b/rust/cloud-storage/email_db_client/src/threads/get.rs
index f940cad8d4..136ca5868e 100644
--- a/rust/cloud-storage/email_db_client/src/threads/get.rs
+++ b/rust/cloud-storage/email_db_client/src/threads/get.rs
@@ -1,13 +1,11 @@
+use crate::messages::get::{convert_db_messages_to_service, get_messages_by_thread_id};
use crate::parse::db_to_service;
-use crate::parse::db_to_service::map_attachmentless_db_message_to_service;
-use crate::{attachments, contacts, labels, messages};
use anyhow::{Context, anyhow};
-use futures::future::try_join_all;
use models_email::email::db;
+use models_email::email::service::thread;
use models_email::email::service::thread::{
ThreadProviderMap, ThreadUserInfo, UserThreadIds, UserThreadsPage,
};
-use models_email::email::service::{message, thread};
use sqlx::PgPool;
use sqlx::types::Uuid;
use std::collections::{HashMap, HashSet};
@@ -39,7 +37,7 @@ pub async fn get_paginated_thread_ids_with_macro_user_id(
}
/// fetch thread with number of most recent messages specified by limit and offset
-#[tracing::instrument(skip(pool), level = "info")]
+#[tracing::instrument(skip(pool), err)]
pub async fn fetch_thread_with_messages_paginated(
pool: &PgPool,
thread_db_id: Uuid,
@@ -69,118 +67,9 @@ pub async fn fetch_thread_with_messages_paginated(
return Ok(None);
};
- let db_messages = sqlx::query_as!(
- db::message::Message,
- r#"
- SELECT
- id,
- provider_id,
- global_id,
- thread_id,
- provider_thread_id,
- replying_to_id,
- link_id,
- provider_history_id,
- internal_date_ts,
- snippet,
- size_estimate,
- subject,
- from_name,
- from_contact_id,
- sent_at,
- has_attachments,
- is_read,
- is_starred,
- is_sent,
- is_draft,
- body_text,
- body_html_sanitized,
- body_macro,
- headers_jsonb,
- created_at,
- updated_at
- FROM email_messages
- WHERE thread_id = $1
- ORDER BY internal_date_ts DESC
- LIMIT $2 OFFSET $3
- "#,
- thread_db_id,
- limit,
- offset
- )
- .fetch_all(pool)
- .await
- .with_context(|| {
- format!(
- "Failed to fetch paginated messages for thread DB ID {}",
- thread_db_id
- )
- })?;
-
- // concurrently fetch data for each message
- let mut message_processing_futures = Vec::new();
-
- for db_message in db_messages {
- let pool_clone = pool.clone();
- message_processing_futures.push(async move {
- // fetch data from each table concurrently
- let (
- sender_res,
- recipients_res,
- scheduled_res,
- labels_res,
- attachments_res,
- macro_attachments_res,
- draft_attachments_res,
- ) = tokio::try_join!(
- contacts::get::get_sender_by_message_id(&pool_clone, db_message.id),
- contacts::get::fetch_db_recipients(&pool_clone, db_message.id),
- messages::scheduled::get_scheduled_message_no_auth(&pool_clone, db_message.id),
- labels::get::fetch_message_labels(&pool_clone, db_message.id),
- async {
- if db_message.has_attachments {
- attachments::provider::fetch_db_attachments(&pool_clone, db_message.id)
- .await
- } else {
- Ok(Vec::new())
- }
- },
- async {
- attachments::marco::fetch_db_macro_attachments(&pool_clone, db_message.id).await
- },
- async {
- // only need to check if the message is a draft created in Macro
- if db_message.is_draft && db_message.provider_id.is_none() {
- attachments::draft::fetch_db_draft_attachments(&pool_clone, db_message.id)
- .await
- } else {
- Ok(Vec::new())
- }
- },
- )?;
-
- let service_message = map_attachmentless_db_message_to_service(
- db_message,
- sender_res,
- recipients_res,
- scheduled_res,
- labels_res,
- );
-
- // parse db-layer structs into service-layer message struct
- db_to_service::map_db_message_attachments_to_service(
- service_message,
- attachments_res,
- macro_attachments_res,
- draft_attachments_res,
- )
- });
- }
+ let db_messages = get_messages_by_thread_id(pool, thread_db_id, offset, limit).await?;
- // Wait for all message processing futures to complete
- let processed_messages: Vec<message::Message> = try_join_all(message_processing_futures)
- .await
- .context("Failed processing messages concurrently")?;
+ let processed_messages = convert_db_messages_to_service(pool, db_messages).await?;
let full_thread = db_to_service::map_db_thread_to_service(db_thread, processed_messages);
diff --git a/rust/cloud-storage/email_service/src/api/email/drafts/mod.rs b/rust/cloud-storage/email_service/src/api/email/drafts/mod.rs
index b4a7206a40..460bbe2b99 100644
--- a/rust/cloud-storage/email_service/src/api/email/drafts/mod.rs
+++ b/rust/cloud-storage/email_service/src/api/email/drafts/mod.rs
@@ -2,15 +2,16 @@ pub(crate) mod add_attachment;
pub(crate) mod create;
pub(crate) mod delete;
pub(crate) mod remove_attachment;
+pub(crate) mod scheduled;
+use crate::api::ApiContext;
use axum::Router;
use axum::routing::{delete, post};
-use crate::api::ApiContext;
-
pub fn router(state: ApiContext) -> Router<ApiContext> {
Router::new()
.route("/", post(create::handler))
+ .nest("/scheduled", scheduled::router())
.route("/:id", delete(delete::handler))
.route("/:id/attachments", post(add_attachment::handler))
.route(
diff --git a/rust/cloud-storage/email_service/src/api/email/drafts/scheduled/list.rs b/rust/cloud-storage/email_service/src/api/email/drafts/scheduled/list.rs
new file mode 100644
index 0000000000..8aefb612c4
--- /dev/null
+++ b/rust/cloud-storage/email_service/src/api/email/drafts/scheduled/list.rs
@@ -0,0 +1,109 @@
+use crate::api::context::ApiContext;
+use axum::extract::{Query, State};
+use axum::http::StatusCode;
+use axum::response::{IntoResponse, Response};
+use axum::{Extension, Json};
+use model::response::ErrorResponse;
+use models_email::service::link::Link;
+use models_email::service::message::Message;
+use strum_macros::AsRefStr;
+use thiserror::Error;
+use utoipa::{IntoParams, ToSchema};
+
+const DEFAULT_LIMIT: u32 = 100;
+const MAX_LIMIT: u32 = 1000;
+
+#[derive(Debug, Error, AsRefStr)]
+pub enum GetScheduledError {
+ #[error("Validation error: {0}")]
+ Validation(String),
+
+ #[error("Failed to fetch scheduled messages")]
+ QueryError(#[from] anyhow::Error),
+}
+
+impl IntoResponse for GetScheduledError {
+ fn into_response(self) -> Response {
+ let status_code = match &self {
+ GetScheduledError::Validation(_) => StatusCode::BAD_REQUEST,
+ GetScheduledError::QueryError(_) => StatusCode::INTERNAL_SERVER_ERROR,
+ };
+
+ (
+ status_code,
+ Json(ErrorResponse {
+ message: self.to_string().as_str(),
+ }),
+ )
+ .into_response()
+ }
+}
+
+#[derive(Debug, serde::Serialize, serde::Deserialize, IntoParams)]
+pub struct GetScheduledQueryParams {
+ /// The number of scheduled messages to skip.
+ #[serde(default)]
+ pub offset: u32,
+ /// The maximum number of scheduled messages to return.
+ #[serde(default = "default_limit")]
+ pub limit: u32,
+}
+
+impl GetScheduledQueryParams {
+ fn validate(&self) -> Result<(), GetScheduledError> {
+ if self.limit == 0 {
+ return Err(GetScheduledError::Validation(
+ "Limit must be positive".to_string(),
+ ));
+ }
+ if self.limit > MAX_LIMIT {
+ return Err(GetScheduledError::Validation(format!(
+ "Limit must not exceed {}",
+ MAX_LIMIT
+ )));
+ }
+ Ok(())
+ }
+}
+
+fn default_limit() -> u32 {
+ DEFAULT_LIMIT
+}
+
+#[derive(Debug, serde::Serialize, serde::Deserialize, ToSchema)]
+pub struct GetScheduledResponse {
+ pub messages: Vec<Message>,
+}
+
+/// List scheduled drafts.
+#[utoipa::path(
+ get,
+ tag = "Draft Scheduling",
+ path = "/email/drafts/scheduled",
+ operation_id = "get_scheduled_messages",
+ params(GetScheduledQueryParams),
+ responses(
+ (status = 200, body = GetScheduledResponse),
+ (status = 400, body = ErrorResponse),
+ (status = 401, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ )
+)]
+#[tracing::instrument(skip(ctx), err)]
+pub async fn handler(
+ State(ctx): State<ApiContext>,
+ link: Extension<Link>,
+ Query(params): Query<GetScheduledQueryParams>,
+) -> Result<Json<GetScheduledResponse>, GetScheduledError> {
+ params.validate()?;
+
+ let messages = email_db_client::messages::scheduled::get::get_scheduled_messages_by_link_id(
+ &ctx.db,
+ link.id,
+ params.offset,
+ params.limit,
+ )
+ .await?;
+
+ Ok(Json(GetScheduledResponse { messages }))
+}
diff --git a/rust/cloud-storage/email_service/src/api/email/drafts/scheduled/mod.rs b/rust/cloud-storage/email_service/src/api/email/drafts/scheduled/mod.rs
new file mode 100644
index 0000000000..49084b28d1
--- /dev/null
+++ b/rust/cloud-storage/email_service/src/api/email/drafts/scheduled/mod.rs
@@ -0,0 +1,13 @@
+use crate::api::context::ApiContext;
+use axum::Router;
+use axum::routing::{delete, get};
+
+pub(crate) mod list;
+pub(crate) mod remove;
+pub(crate) mod upsert;
+
+pub fn router() -> Router<ApiContext> {
+ Router::new()
+ .route("/", get(list::handler))
+ .route("/:message_id", delete(remove::handler).put(upsert::handler))
+}
diff --git a/rust/cloud-storage/email_service/src/api/email/drafts/scheduled/remove.rs b/rust/cloud-storage/email_service/src/api/email/drafts/scheduled/remove.rs
new file mode 100644
index 0000000000..e12998636e
--- /dev/null
+++ b/rust/cloud-storage/email_service/src/api/email/drafts/scheduled/remove.rs
@@ -0,0 +1,91 @@
+use crate::api::context::ApiContext;
+use axum::extract::{Path, State};
+use axum::http::StatusCode;
+use axum::response::{IntoResponse, Response};
+use axum::{Extension, Json};
+use model::response::ErrorResponse;
+use models_email::service::link::Link;
+use strum_macros::AsRefStr;
+use thiserror::Error;
+use uuid::Uuid;
+
+#[derive(Debug, Error, AsRefStr)]
+pub enum DeleteScheduledError {
+ #[error("Scheduled message not found")]
+ NotFound,
+
+ #[error("Message has already been sent")]
+ AlreadySent,
+
+ #[error("Failed to delete scheduled message")]
+ QueryError(#[from] anyhow::Error),
+
+ #[error("Database error")]
+ DatabaseError(#[from] sqlx::Error),
+}
+
+impl IntoResponse for DeleteScheduledError {
+ fn into_response(self) -> Response {
+ let status_code = match &self {
+ DeleteScheduledError::NotFound => StatusCode::NOT_FOUND,
+ DeleteScheduledError::AlreadySent => StatusCode::BAD_REQUEST,
+ DeleteScheduledError::QueryError(_) | DeleteScheduledError::DatabaseError(_) => {
+ StatusCode::INTERNAL_SERVER_ERROR
+ }
+ };
+
+ (
+ status_code,
+ Json(ErrorResponse {
+ message: self.to_string().as_str(),
+ }),
+ )
+ .into_response()
+ }
+}
+
+/// Remove the scheduled send from a draft.
+#[utoipa::path(
+ delete,
+ tag = "Draft Scheduling",
+ path = "/email/drafts/scheduled/{message_id}",
+ operation_id = "delete_scheduled_draft",
+ params(
+ ("message_id" = Uuid, Path, description = "The ID of the draft")
+ ),
+ responses(
+ (status = 204, description = "Scheduled send deleted successfully"),
+ (status = 400, body = ErrorResponse),
+ (status = 401, body = ErrorResponse),
+ (status = 404, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ )
+)]
+#[tracing::instrument(skip(ctx), err)]
+pub async fn handler(
+ State(ctx): State<ApiContext>,
+ link: Extension<Link>,
+ Path(message_id): Path<Uuid>,
+) -> Result<StatusCode, DeleteScheduledError> {
+ let mut tx = ctx.db.begin().await?;
+
+ // Check if the scheduled message exists and hasn't been sent
+ let scheduled_message = email_db_client::messages::scheduled::get::get_scheduled_message(
+ &mut *tx, link.id, message_id,
+ )
+ .await?
+ .ok_or(DeleteScheduledError::NotFound)?;
+
+ if scheduled_message.sent {
+ return Err(DeleteScheduledError::AlreadySent);
+ }
+
+ email_db_client::messages::scheduled::delete::delete_scheduled_message(
+ &mut *tx, link.id, message_id,
+ )
+ .await?;
+
+ tx.commit().await?;
+
+ Ok(StatusCode::NO_CONTENT)
+}
diff --git a/rust/cloud-storage/email_service/src/api/email/drafts/scheduled/upsert.rs b/rust/cloud-storage/email_service/src/api/email/drafts/scheduled/upsert.rs
new file mode 100644
index 0000000000..9a2881891c
--- /dev/null
+++ b/rust/cloud-storage/email_service/src/api/email/drafts/scheduled/upsert.rs
@@ -0,0 +1,111 @@
+use crate::api::context::ApiContext;
+use axum::extract::{Path, State};
+use axum::http::StatusCode;
+use axum::response::{IntoResponse, Response};
+use axum::{Extension, Json};
+use model::response::ErrorResponse;
+use models_email::service::link::Link;
+use models_email::service::message::ScheduledMessage;
+use sqlx_core::types::chrono::{DateTime, Utc};
+use strum_macros::AsRefStr;
+use thiserror::Error;
+use utoipa::ToSchema;
+use uuid::Uuid;
+
+#[derive(Debug, Error, AsRefStr)]
+pub enum UpsertScheduledError {
+ #[error("Draft not found")]
+ NotFound,
+
+ #[error("Failed to upsert scheduled message")]
+ QueryError(#[from] anyhow::Error),
+
+ #[error("Database error")]
+ DatabaseError(#[from] sqlx::Error),
+}
+
+impl IntoResponse for UpsertScheduledError {
+ fn into_response(self) -> Response {
+ let status_code = match &self {
+ UpsertScheduledError::NotFound => StatusCode::NOT_FOUND,
+ UpsertScheduledError::QueryError(_) | UpsertScheduledError::DatabaseError(_) => {
+ StatusCode::INTERNAL_SERVER_ERROR
+ }
+ };
+
+ (
+ status_code,
+ Json(ErrorResponse {
+ message: self.to_string().as_str(),
+ }),
+ )
+ .into_response()
+ }
+}
+
+#[derive(Debug, serde::Deserialize, ToSchema)]
+pub struct UpsertScheduledRequest {
+ /// The time to send the message (ISO 8601 format)
+ pub send_time: DateTime<Utc>,
+}
+
+#[derive(Debug, serde::Serialize, ToSchema)]
+pub struct UpsertScheduledResponse {
+ pub message_id: Uuid,
+ pub send_time: DateTime<Utc>,
+}
+
+/// Schedule or update a scheduled draft.
+#[utoipa::path(
+ put,
+ tag = "Draft Scheduling",
+ path = "/email/drafts/scheduled/{id}",
+ operation_id = "upsert_scheduled_message",
+ params(
+ ("id" = Uuid, Path, description = "The ID of the draft message to schedule")
+ ),
+ request_body = UpsertScheduledRequest,
+ responses(
+ (status = 200, body = UpsertScheduledResponse),
+ (status = 401, body = ErrorResponse),
+ (status = 404, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ )
+)]
+#[tracing::instrument(skip(ctx), err)]
+pub async fn handler(
+ State(ctx): State<ApiContext>,
+ link: Extension<Link>,
+ Path(draft_id): Path<Uuid>,
+ Json(request): Json<UpsertScheduledRequest>,
+) -> Result<Json<UpsertScheduledResponse>, UpsertScheduledError> {
+ // Check if the draft exists
+ let draft_exists =
+ email_db_client::messages::get::draft_exists_with_id(&ctx.db, link.id, draft_id).await?;
+
+ if !draft_exists {
+ return Err(UpsertScheduledError::NotFound);
+ }
+
+ // Create the scheduled message
+ let scheduled_message = ScheduledMessage {
+ link_id: link.id,
+ message_id: draft_id,
+ send_time: request.send_time,
+ sent: false,
+ };
+
+ // Upsert the scheduled message
+ let mut tx = ctx.db.begin().await?;
+ email_db_client::messages::scheduled::upsert::upsert_scheduled_message(
+ &mut tx,
+ scheduled_message,
+ )
+ .await?;
+ tx.commit().await?;
+
+ Ok(Json(UpsertScheduledResponse {
+ message_id: draft_id,
+ send_time: request.send_time,
+ }))
+}
diff --git a/rust/cloud-storage/email_service/src/api/swagger.rs b/rust/cloud-storage/email_service/src/api/swagger.rs
index 134dd7df20..44141264e0 100644
--- a/rust/cloud-storage/email_service/src/api/swagger.rs
+++ b/rust/cloud-storage/email_service/src/api/swagger.rs
@@ -47,6 +47,9 @@ use utoipa::OpenApi;
email::init::handler,
email::drafts::create::handler,
email::drafts::delete::handler,
+ email::drafts::scheduled::list::handler,
+ email::drafts::scheduled::remove::handler,
+ email::drafts::scheduled::upsert::handler,
email::drafts::add_attachment::handler,
email::drafts::remove_attachment::handler,
email::messages::get::handler,
diff --git a/rust/cloud-storage/email_service/src/pubsub/scheduled/process.rs b/rust/cloud-storage/email_service/src/pubsub/scheduled/process.rs
index 20515d5f3f..4d8758a80d 100644
--- a/rust/cloud-storage/email_service/src/pubsub/scheduled/process.rs
+++ b/rust/cloud-storage/email_service/src/pubsub/scheduled/process.rs
@@ -4,7 +4,7 @@ use crate::util::gmail::send::{
cleanup_draft_attachments, fetch_and_attach_draft_attachments, generate_email_threading_headers,
};
use anyhow::Context;
-use email_db_client::messages::scheduled::get_scheduled_message;
+use email_db_client::messages::scheduled::get::get_scheduled_message;
use models_email::service::message::MessageToSend;
use models_email::service::pubsub::ScheduledPubsubMessage;
use sqlx_core::any::AnyConnectionBackend;
@@ -172,7 +172,7 @@ async fn mark_messages_as_sent(
message: &MessageToSend,
) -> anyhow::Result<()> {
// mark scheduled message as sent
- email_db_client::messages::scheduled::mark_scheduled_message_as_sent(
+ email_db_client::messages::scheduled::upsert::mark_scheduled_message_as_sent(
tx.as_mut(),
message.link_id,
message.db_id.unwrap(),