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): Delay sending emails for undo functionality (#1071)

Evan Hutnika11965d4e4a4
diff --git a/infra/stacks/email-service/Pulumi.dev.yaml b/infra/stacks/email-service/Pulumi.dev.yaml
index c3a0205b71..3840228fd7 100644
--- a/infra/stacks/email-service/Pulumi.dev.yaml
+++ b/infra/stacks/email-service/Pulumi.dev.yaml
@@ -9,6 +9,7 @@ config:
email-service:internal_auth_key: document-storage-service-auth-key-dev
email-service:cf_private_key: email-attachments-private-key-dev
email-service:notifications_enabled: true
+ email-service:sent_undo_delay_secs: 5
email-service:redis_rate_limit_reqs: 14000
email-service:redis_rate_limit_reqs_backfill: 13000
email-service:redis_rate_limit_window_secs: 60
diff --git a/infra/stacks/email-service/Pulumi.prod.yaml b/infra/stacks/email-service/Pulumi.prod.yaml
index 53bce2e16a..ceb397c922 100644
--- a/infra/stacks/email-service/Pulumi.prod.yaml
+++ b/infra/stacks/email-service/Pulumi.prod.yaml
@@ -9,6 +9,7 @@ config:
email-service:internal_auth_key: document-storage-service-auth-key-prod
email-service:cf_private_key: email-attachments-private-key-prod
email-service:notifications_enabled: true
+ email-service:sent_undo_delay_secs: 5
email-service:redis_rate_limit_reqs: 14000
email-service:redis_rate_limit_reqs_backfill: 13000
email-service:redis_rate_limit_window_secs: 60
diff --git a/infra/stacks/email-service/index.ts b/infra/stacks/email-service/index.ts
index 7e099526a0..e26f192e75 100644
--- a/infra/stacks/email-service/index.ts
+++ b/infra/stacks/email-service/index.ts
@@ -42,6 +42,7 @@ const AUDIENCE = aws.secretsmanager
.apply((secret) => secret.secretString);
const ISSUER = config.require(`fusionauth_issuer`);
const NOTIFICATIONS_ENABLED = config.require(`notifications_enabled`);
+const SENT_UNDO_DELAY_SECS = config.require(`sent_undo_delay_secs`);
const REDIS_RATE_LIMIT_REQS = config.require(`redis_rate_limit_reqs`);
const REDIS_RATE_LIMIT_REQS_BACKFILL = config.require(
`redis_rate_limit_reqs_backfill`
@@ -178,7 +179,6 @@ export const linkManagerQueueName = pulumi.interpolate`${link_manager_queue.queu
const scheduled_queue = new Queue('email-service-scheduled', {
tags,
- fifoQueue: true,
});
export const scheduledQueueArn = pulumi.interpolate`${scheduled_queue.queue.arn}`;
@@ -438,6 +438,10 @@ const containerEnvVars = [
name: 'SEARCH_EVENT_QUEUE',
value: pulumi.interpolate`${searchEventQueueName}`,
},
+ {
+ name: 'SENT_UNDO_DELAY_SECS',
+ value: pulumi.interpolate`${SENT_UNDO_DELAY_SECS}`,
+ },
{
name: 'REDIS_RATE_LIMIT_REQS',
value: pulumi.interpolate`${REDIS_RATE_LIMIT_REQS}`,
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 1400b41a8d..ef93e16b0c 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -3136,6 +3136,7 @@ dependencies = [
"aws_lambda_events",
"chrono",
"lambda_runtime",
+ "macro_db_migrator",
"macro_entrypoint",
"macro_env",
"models_email",
@@ -3159,6 +3160,7 @@ dependencies = [
"axum-extra",
"base64 0.22.1",
"bytes",
+ "chrono",
"cloudfront_sign",
"connection_gateway",
"document_storage_service_client",
diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-49cbada51408e2501723f7a1de4e170efcab0fcd922e2c5a79772256c1e51baa.json b/rust/cloud-storage/email_db_client/.sqlx/query-49cbada51408e2501723f7a1de4e170efcab0fcd922e2c5a79772256c1e51baa.json
new file mode 100644
index 0000000000..08ee66140d
--- /dev/null
+++ b/rust/cloud-storage/email_db_client/.sqlx/query-49cbada51408e2501723f7a1de4e170efcab0fcd922e2c5a79772256c1e51baa.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE email_messages\n SET\n is_draft = $1,\n updated_at = NOW()\n WHERE\n id = $2\n AND link_id = $3\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Bool",
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "49cbada51408e2501723f7a1de4e170efcab0fcd922e2c5a79772256c1e51baa"
+}
diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-0894fb0e110cd45fb7e1c09b4c322b011244ddd93854f2ed17dcc91f1b4ed353.json b/rust/cloud-storage/email_db_client/.sqlx/query-4dd84a2e543e14d4ed1655a0895eab7815948fcad38c5ce05925ebc4a5ebea69.json
similarity index 69%
rename from rust/cloud-storage/email_db_client/.sqlx/query-0894fb0e110cd45fb7e1c09b4c322b011244ddd93854f2ed17dcc91f1b4ed353.json
rename to rust/cloud-storage/email_db_client/.sqlx/query-4dd84a2e543e14d4ed1655a0895eab7815948fcad38c5ce05925ebc4a5ebea69.json
index 32c362ef60..dfc668e9a2 100644
--- a/rust/cloud-storage/email_db_client/.sqlx/query-0894fb0e110cd45fb7e1c09b4c322b011244ddd93854f2ed17dcc91f1b4ed353.json
+++ b/rust/cloud-storage/email_db_client/.sqlx/query-4dd84a2e543e14d4ed1655a0895eab7815948fcad38c5ce05925ebc4a5ebea69.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT link_id, message_id, send_time, sent\n FROM email_scheduled_messages\n WHERE link_id = $1 AND message_id = $2\n ",
+ "query": "\n SELECT link_id, message_id, send_time, sent, processing\n FROM email_scheduled_messages\n WHERE link_id = $1 AND message_id = $2\n ",
"describe": {
"columns": [
{
@@ -22,6 +22,11 @@
"ordinal": 3,
"name": "sent",
"type_info": "Bool"
+ },
+ {
+ "ordinal": 4,
+ "name": "processing",
+ "type_info": "Bool"
}
],
"parameters": {
@@ -34,8 +39,9 @@
false,
false,
false,
+ false,
false
]
},
- "hash": "0894fb0e110cd45fb7e1c09b4c322b011244ddd93854f2ed17dcc91f1b4ed353"
+ "hash": "4dd84a2e543e14d4ed1655a0895eab7815948fcad38c5ce05925ebc4a5ebea69"
}
diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-afc61b70dea215da99c078aeb2c7b45549cbf1c118b342ac0644921d3978869d.json b/rust/cloud-storage/email_db_client/.sqlx/query-5a45cbeeb6fa756b256688f6c4e05be4abae89c4eb3c5532a96b91f3d07e232f.json
similarity index 68%
rename from rust/cloud-storage/email_db_client/.sqlx/query-afc61b70dea215da99c078aeb2c7b45549cbf1c118b342ac0644921d3978869d.json
rename to rust/cloud-storage/email_db_client/.sqlx/query-5a45cbeeb6fa756b256688f6c4e05be4abae89c4eb3c5532a96b91f3d07e232f.json
index 53e6c69b8e..e76379715c 100644
--- a/rust/cloud-storage/email_db_client/.sqlx/query-afc61b70dea215da99c078aeb2c7b45549cbf1c118b342ac0644921d3978869d.json
+++ b/rust/cloud-storage/email_db_client/.sqlx/query-5a45cbeeb6fa756b256688f6c4e05be4abae89c4eb3c5532a96b91f3d07e232f.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT link_id, message_id, send_time, sent\n FROM email_scheduled_messages\n WHERE message_id = $1 and sent = false\n ",
+ "query": "\n SELECT link_id, message_id, send_time, sent, processing\n FROM email_scheduled_messages\n WHERE message_id = $1 and sent = false\n ",
"describe": {
"columns": [
{
@@ -22,6 +22,11 @@
"ordinal": 3,
"name": "sent",
"type_info": "Bool"
+ },
+ {
+ "ordinal": 4,
+ "name": "processing",
+ "type_info": "Bool"
}
],
"parameters": {
@@ -33,8 +38,9 @@
false,
false,
false,
+ false,
false
]
},
- "hash": "afc61b70dea215da99c078aeb2c7b45549cbf1c118b342ac0644921d3978869d"
+ "hash": "5a45cbeeb6fa756b256688f6c4e05be4abae89c4eb3c5532a96b91f3d07e232f"
}
diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-c631a415b25cf9edaf194dc022a044463339682b132e007d56eae675e4795169.json b/rust/cloud-storage/email_db_client/.sqlx/query-c631a415b25cf9edaf194dc022a044463339682b132e007d56eae675e4795169.json
new file mode 100644
index 0000000000..b5f354e820
--- /dev/null
+++ b/rust/cloud-storage/email_db_client/.sqlx/query-c631a415b25cf9edaf194dc022a044463339682b132e007d56eae675e4795169.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE email_scheduled_messages\n SET\n processing = false,\n updated_at = NOW()\n WHERE link_id = $1 AND message_id = $2\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "c631a415b25cf9edaf194dc022a044463339682b132e007d56eae675e4795169"
+}
diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-e2cadbb29d007b092339274024c3638798761653ca72db90aa2ce7417976ef61.json b/rust/cloud-storage/email_db_client/.sqlx/query-e2cadbb29d007b092339274024c3638798761653ca72db90aa2ce7417976ef61.json
new file mode 100644
index 0000000000..a24ebef4da
--- /dev/null
+++ b/rust/cloud-storage/email_db_client/.sqlx/query-e2cadbb29d007b092339274024c3638798761653ca72db90aa2ce7417976ef61.json
@@ -0,0 +1,47 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH old AS (\n SELECT link_id, message_id, send_time, sent, processing\n FROM email_scheduled_messages\n WHERE link_id = $1 AND message_id = $2\n ), updated AS (\n UPDATE email_scheduled_messages\n SET processing = true, updated_at = NOW()\n WHERE link_id = $1 AND message_id = $2\n )\n SELECT link_id, message_id, send_time, sent, processing\n FROM old\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "link_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "message_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "send_time",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 3,
+ "name": "sent",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 4,
+ "name": "processing",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "e2cadbb29d007b092339274024c3638798761653ca72db90aa2ce7417976ef61"
+}
diff --git a/rust/cloud-storage/email_db_client/fixtures/get_process_scheduled_messages.sql b/rust/cloud-storage/email_db_client/fixtures/get_process_scheduled_messages.sql
new file mode 100644
index 0000000000..dcba44898a
--- /dev/null
+++ b/rust/cloud-storage/email_db_client/fixtures/get_process_scheduled_messages.sql
@@ -0,0 +1,103 @@
+-- SQL fixture for scheduled_messages tests
+-- Tests get_and_start_processing_scheduled_message operation
+
+------------------------------------------------------------
+-- User Link
+------------------------------------------------------------
+
+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-000000000e01', 'macro|[email protected]', '00000000-0000-0000-0000-000000000e01',
+ '[email protected]', 'GMAIL', true, NOW(), NOW());
+
+-- Second link for testing cross-link access prevention
+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-000000000e02', 'macro|[email protected]', '00000000-0000-0000-0000-000000000e02',
+ '[email protected]', 'GMAIL', true, NOW(), NOW());
+
+------------------------------------------------------------
+-- Contact
+------------------------------------------------------------
+
+INSERT INTO email_contacts (id, link_id, email_address, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-0000000ce001',
+ '00000000-0000-0000-0000-000000000e01',
+ NOW(), NOW());
+
+------------------------------------------------------------
+-- Thread
+------------------------------------------------------------
+
+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-00000000e201',
+ '00000000-0000-0000-0000-000000000e01',
+ true, false, NOW(), NOW());
+
+------------------------------------------------------------
+-- Message 1: Scheduled message not yet processing (processing = false, sent = false)
+------------------------------------------------------------
+
+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, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-00000000e501',
+ '00000000-0000-0000-0000-00000000e201',
+ '00000000-0000-0000-0000-000000000e01',
+ 'provider-scheduled-501',
+ FALSE,
+ '00000000-0000-0000-0000-0000000ce001',
+ '2025-01-10 10:00:00 +00:00',
+ false, false, false, true, NOW(), NOW());
+
+INSERT INTO email_scheduled_messages (link_id, message_id, send_time, sent, processing, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-000000000e01',
+ '00000000-0000-0000-0000-00000000e501',
+ '2025-01-15 10:00:00 +00:00',
+ false,
+ false,
+ NOW(), NOW());
+
+------------------------------------------------------------
+-- Message 2: Scheduled message already processing (processing = true, sent = false)
+------------------------------------------------------------
+
+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, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-00000000e502',
+ '00000000-0000-0000-0000-00000000e201',
+ '00000000-0000-0000-0000-000000000e01',
+ 'provider-scheduled-502',
+ FALSE,
+ '00000000-0000-0000-0000-0000000ce001',
+ '2025-01-10 11:00:00 +00:00',
+ false, false, false, true, NOW(), NOW());
+
+INSERT INTO email_scheduled_messages (link_id, message_id, send_time, sent, processing, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-000000000e01',
+ '00000000-0000-0000-0000-00000000e502',
+ '2025-01-15 11:00:00 +00:00',
+ false,
+ true,
+ NOW(), NOW());
+
+------------------------------------------------------------
+-- Message 3: Scheduled message already sent (processing = false, sent = true)
+------------------------------------------------------------
+
+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, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-00000000e503',
+ '00000000-0000-0000-0000-00000000e201',
+ '00000000-0000-0000-0000-000000000e01',
+ 'provider-scheduled-503',
+ TRUE,
+ '00000000-0000-0000-0000-0000000ce001',
+ '2025-01-10 12:00:00 +00:00',
+ false, false, false, false, NOW(), NOW());
+
+INSERT INTO email_scheduled_messages (link_id, message_id, send_time, sent, processing, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-000000000e01',
+ '00000000-0000-0000-0000-00000000e503',
+ '2025-01-15 12:00:00 +00:00',
+ true,
+ false,
+ NOW(), NOW());
\ No newline at end of file
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 cef6f00771..35ef546962 100644
--- a/rust/cloud-storage/email_db_client/src/messages/insert.rs
+++ b/rust/cloud-storage/email_db_client/src/messages/insert.rs
@@ -219,9 +219,10 @@ pub async fn insert_message(
/// insert message that user created via macro frontend
#[tracing::instrument(skip(tx, service_message), err)]
-pub async fn insert_message_to_send(
+pub async fn insert_message_to_send_db(
tx: &mut sqlx::PgConnection,
service_message: &mut message::MessageToSend,
+ send_time: Option<chrono::DateTime<Utc>>,
thread_id: Uuid,
from_contact_id: Option<Uuid>,
is_draft: bool,
@@ -281,7 +282,7 @@ pub async fn insert_message_to_send(
.is_some_and(|x| !x.is_empty()),
true,
false,
- !is_draft,
+ false,
is_draft,
db_message_to_send.body_text,
db_message_to_send.body_html,
@@ -295,7 +296,7 @@ pub async fn insert_message_to_send(
service_message.db_id = Some(message_db_id);
- process_scheduled_message(tx, service_message, message_db_id, is_draft).await?;
+ process_scheduled_message(tx, service_message, send_time, message_db_id).await?;
if let Some(mut attachments) = service_message.attachments_macro.clone() {
marco::insert_macro_attachments(tx, message_db_id, &mut attachments).await?;
@@ -310,33 +311,23 @@ pub async fn insert_message_to_send(
async fn process_scheduled_message(
tx: &mut sqlx::PgConnection,
service_message: &message::MessageToSend,
+ send_time: Option<chrono::DateTime<Utc>>,
message_db_id: Uuid,
- is_draft: bool,
) -> anyhow::Result<()> {
- // if a draft is created with a specified send_time, upsert scheduled message row in database
- let upsert_scheduled_time = is_draft && service_message.send_time.is_some();
- // if a draft is created without a specified end_time, delete any existing scheduled entry.
- // this handles the case where a user removes a previously set send_time from a draft
- // if a user sends a message via the API, delete any existing scheduled entry for the message.
- // this covers the case where a user scheduled a message to be sent, then ended up just
- // sending it themselves.
- let delete_scheduled = !(is_draft && service_message.send_time.is_some());
-
- if upsert_scheduled_time {
+ if send_time.is_some() {
upsert_scheduled_message(
tx,
ScheduledMessage {
link_id: service_message.link_id,
message_id: message_db_id,
- send_time: service_message.send_time.unwrap(),
+ send_time: send_time.unwrap(),
sent: false,
+ processing: false,
},
)
.await
.context("Failed to insert scheduled message")?;
- }
-
- if delete_scheduled {
+ } else {
delete_scheduled_message(tx, service_message.link_id, message_db_id)
.await
.context("Failed to delete scheduled message")?;
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
index a640ea0918..f5555fa5b7 100644
--- a/rust/cloud-storage/email_db_client/src/messages/scheduled/get.rs
+++ b/rust/cloud-storage/email_db_client/src/messages/scheduled/get.rs
@@ -17,7 +17,7 @@ where
let record = sqlx::query_as!(
service::message::ScheduledMessage,
r#"
- SELECT link_id, message_id, send_time, sent
+ SELECT link_id, message_id, send_time, sent, processing
FROM email_scheduled_messages
WHERE link_id = $1 AND message_id = $2
"#,
@@ -30,6 +30,39 @@ where
Ok(record)
}
+/// Retrieves a scheduled message by link_id and message_id, and sets processing to true
+/// Returns the message with the OLD processing value (before it was set to true)
+/// Returns None if the message doesn't exist
+#[tracing::instrument(skip(db), err)]
+pub async fn get_and_start_processing_scheduled_message(
+ db: &sqlx::PgPool,
+ link_id: Uuid,
+ message_id: Uuid,
+) -> anyhow::Result<Option<service::message::ScheduledMessage>> {
+ let record = sqlx::query_as!(
+ service::message::ScheduledMessage,
+ r#"
+ WITH old AS (
+ SELECT link_id, message_id, send_time, sent, processing
+ FROM email_scheduled_messages
+ WHERE link_id = $1 AND message_id = $2
+ ), updated AS (
+ UPDATE email_scheduled_messages
+ SET processing = true, updated_at = NOW()
+ WHERE link_id = $1 AND message_id = $2
+ )
+ SELECT link_id, message_id, send_time, sent, processing
+ FROM old
+ "#,
+ 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)]
@@ -40,7 +73,7 @@ pub async fn get_scheduled_message_no_auth(
let record = sqlx::query_as!(
db::message::ScheduledMessage,
r#"
- SELECT link_id, message_id, send_time, sent
+ SELECT link_id, message_id, send_time, sent, processing
FROM email_scheduled_messages
WHERE message_id = $1 and sent = false
"#,
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
index b99105e525..a5bddfa697 100644
--- a/rust/cloud-storage/email_db_client/src/messages/scheduled/mod.rs
+++ b/rust/cloud-storage/email_db_client/src/messages/scheduled/mod.rs
@@ -1,3 +1,5 @@
pub mod delete;
pub mod get;
+#[cfg(test)]
+mod test;
pub mod upsert;
diff --git a/rust/cloud-storage/email_db_client/src/messages/scheduled/test.rs b/rust/cloud-storage/email_db_client/src/messages/scheduled/test.rs
new file mode 100644
index 0000000000..4d5e4447cc
--- /dev/null
+++ b/rust/cloud-storage/email_db_client/src/messages/scheduled/test.rs
@@ -0,0 +1,160 @@
+use crate::messages::scheduled::get::get_and_start_processing_scheduled_message;
+use anyhow::Result;
+use chrono::{TimeZone, Utc};
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use sqlx::types::Uuid;
+use sqlx::{Pool, Postgres};
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("get_process_scheduled_messages"))
+)]
+async fn get_and_start_processing_returns_message_with_old_processing_value(
+ pool: Pool<Postgres>,
+) -> Result<()> {
+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;
+
+ let link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000e01")?;
+ let message_id = Uuid::parse_str("00000000-0000-0000-0000-00000000e501")?;
+
+ let result = get_and_start_processing_scheduled_message(&pool, link_id, message_id).await?;
+
+ assert!(result.is_some());
+ let scheduled_message = result.unwrap();
+
+ // Should return the OLD processing value (false) before the update
+ assert_eq!(scheduled_message.link_id, link_id);
+ assert_eq!(scheduled_message.message_id, message_id);
+ assert!(!scheduled_message.processing);
+ assert!(!scheduled_message.sent);
+ assert_eq!(
+ scheduled_message.send_time,
+ Utc.with_ymd_and_hms(2025, 1, 15, 10, 0, 0).unwrap()
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("get_process_scheduled_messages"))
+)]
+async fn get_and_start_processing_sets_processing_to_true_in_database(
+ pool: Pool<Postgres>,
+) -> Result<()> {
+ let link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000e01")?;
+ let message_id = Uuid::parse_str("00000000-0000-0000-0000-00000000e501")?;
+
+ // First call should return processing = false (old value)
+ let result = get_and_start_processing_scheduled_message(&pool, link_id, message_id).await?;
+ assert!(result.is_some());
+ assert!(!result.unwrap().processing);
+
+ // Second call should return processing = true (the new old value after first update)
+ let result2 = get_and_start_processing_scheduled_message(&pool, link_id, message_id).await?;
+ assert!(result2.is_some());
+ assert!(result2.unwrap().processing);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("get_process_scheduled_messages"))
+)]
+async fn get_and_start_processing_returns_message_already_processing(
+ pool: Pool<Postgres>,
+) -> Result<()> {
+ let link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000e01")?;
+ let message_id = Uuid::parse_str("00000000-0000-0000-0000-00000000e502")?;
+
+ let result = get_and_start_processing_scheduled_message(&pool, link_id, message_id).await?;
+
+ assert!(result.is_some());
+ let scheduled_message = result.unwrap();
+
+ // Should return the OLD processing value which is already true
+ assert!(scheduled_message.processing);
+ assert!(!scheduled_message.sent);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("get_process_scheduled_messages"))
+)]
+async fn get_and_start_processing_returns_already_sent_message(pool: Pool<Postgres>) -> Result<()> {
+ let link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000e01")?;
+ let message_id = Uuid::parse_str("00000000-0000-0000-0000-00000000e503")?;
+
+ let result = get_and_start_processing_scheduled_message(&pool, link_id, message_id).await?;
+
+ assert!(result.is_some());
+ let scheduled_message = result.unwrap();
+
+ assert!(scheduled_message.sent);
+ assert!(!scheduled_message.processing);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("get_process_scheduled_messages"))
+)]
+async fn get_and_start_processing_returns_none_for_wrong_link_id(
+ pool: Pool<Postgres>,
+) -> Result<()> {
+ let wrong_link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000e02")?;
+ let message_id = Uuid::parse_str("00000000-0000-0000-0000-00000000e501")?;
+
+ let result =
+ get_and_start_processing_scheduled_message(&pool, wrong_link_id, message_id).await?;
+
+ assert!(result.is_none());
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("get_process_scheduled_messages"))
+)]
+async fn get_and_start_processing_returns_none_for_nonexistent_message(
+ pool: Pool<Postgres>,
+) -> Result<()> {
+ let link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000e01")?;
+ let nonexistent_message_id = Uuid::parse_str("00000000-0000-0000-0000-00000000ffff")?;
+
+ let result =
+ get_and_start_processing_scheduled_message(&pool, link_id, nonexistent_message_id).await?;
+
+ assert!(result.is_none());
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("get_process_scheduled_messages"))
+)]
+async fn get_and_start_processing_does_not_affect_other_messages(
+ pool: Pool<Postgres>,
+) -> Result<()> {
+ let link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000e01")?;
+ let message_id_1 = Uuid::parse_str("00000000-0000-0000-0000-00000000e501")?;
+ let message_id_2 = Uuid::parse_str("00000000-0000-0000-0000-00000000e502")?;
+
+ // Process message 1
+ let result1 = get_and_start_processing_scheduled_message(&pool, link_id, message_id_1).await?;
+ assert!(result1.is_some());
+ assert!(!result1.unwrap().processing);
+
+ // Message 2 should still have its original processing state (true)
+ let result2 = get_and_start_processing_scheduled_message(&pool, link_id, message_id_2).await?;
+ assert!(result2.is_some());
+ assert!(result2.unwrap().processing);
+
+ Ok(())
+}
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
index ea11f9976e..ee7c59ce74 100644
--- a/rust/cloud-storage/email_db_client/src/messages/scheduled/upsert.rs
+++ b/rust/cloud-storage/email_db_client/src/messages/scheduled/upsert.rs
@@ -57,3 +57,30 @@ where
// Return whether a row was actually updated
Ok(result.rows_affected() > 0)
}
+
+/// Set processing to false, on failure of sending scheduled message
+#[tracing::instrument(skip(executor), err)]
+pub async fn clear_scheduled_message_processing<'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
+ processing = false,
+ updated_at = NOW()
+ WHERE link_id = $1 AND message_id = $2
+ "#,
+ link_id,
+ message_id,
+ )
+ .execute(executor)
+ .await?;
+
+ Ok(result.rows_affected() > 0)
+}
diff --git a/rust/cloud-storage/email_db_client/src/messages/update.rs b/rust/cloud-storage/email_db_client/src/messages/update.rs
index 59a2015fba..17613a4d99 100644
--- a/rust/cloud-storage/email_db_client/src/messages/update.rs
+++ b/rust/cloud-storage/email_db_client/src/messages/update.rs
@@ -1,7 +1,6 @@
-use anyhow::Context;
use sqlx::types::Uuid;
-#[tracing::instrument(skip(tx), level = "info")]
+#[tracing::instrument(skip(tx), err)]
pub async fn update_message_read_status(
tx: &mut sqlx::PgConnection,
message_id: Uuid,
@@ -26,13 +25,7 @@ pub async fn update_message_read_status(
fusionauth_user_id
)
.fetch_optional(tx)
- .await
- .with_context(|| {
- format!(
- "Failed to update read status for message {} for user {}",
- message_id, fusionauth_user_id
- )
- })?;
+ .await?;
if result.is_none() {
tracing::warn!(
@@ -96,7 +89,7 @@ where
Ok(updated_count)
}
-#[tracing::instrument(skip(pool), level = "info")]
+#[tracing::instrument(skip(pool), err)]
pub async fn update_message_starred_status_batch(
pool: &sqlx::PgPool,
message_ids: Vec<Uuid>,
@@ -125,14 +118,7 @@ pub async fn update_message_starred_status_batch(
fusionauth_user_id
)
.fetch_all(pool)
- .await
- .with_context(|| {
- format!(
- "Failed to update starred status for {} messages for user {}",
- message_ids.len(),
- fusionauth_user_id
- )
- })?;
+ .await?;
let updated_count = result.len();
@@ -149,7 +135,7 @@ pub async fn update_message_starred_status_batch(
}
/// Updates draft in database to be sent, and populates with provider IDs
-#[tracing::instrument(skip(tx), level = "info")]
+#[tracing::instrument(skip(tx), err)]
pub async fn mark_message_as_sent(
tx: &mut sqlx::PgConnection,
provider_id: &str,
@@ -157,7 +143,7 @@ pub async fn mark_message_as_sent(
link_id: Uuid,
db_id: Uuid,
) -> anyhow::Result<()> {
- let result = sqlx::query!(
+ sqlx::query!(
r#"
UPDATE email_messages
SET
@@ -176,21 +162,35 @@ pub async fn mark_message_as_sent(
link_id
)
.execute(tx)
- .await
- .with_context(|| {
- format!(
- "Failed to mark message as sent for message {} in link {}",
- db_id, link_id
- )
- })?;
-
- if result.rows_affected() == 0 {
- tracing::warn!(
- message_id = %db_id,
- link_id = %link_id,
- "No message was updated - message may not exist or link_id doesn't match"
- );
- }
+ .await?;
+
+ Ok(())
+}
+
+/// Updates the is_draft status of a message
+#[tracing::instrument(skip(tx), err)]
+pub async fn update_message_draft_status(
+ tx: &mut sqlx::PgConnection,
+ message_id: Uuid,
+ link_id: Uuid,
+ is_draft: bool,
+) -> anyhow::Result<()> {
+ sqlx::query!(
+ r#"
+ UPDATE email_messages
+ SET
+ is_draft = $1,
+ updated_at = NOW()
+ WHERE
+ id = $2
+ AND link_id = $3
+ "#,
+ is_draft,
+ message_id,
+ link_id
+ )
+ .execute(tx)
+ .await?;
Ok(())
}
diff --git a/rust/cloud-storage/email_scheduled_handler/.sqlx/query-146bbdcb331e7503ba92aea61d9da3b321b1950707a533f737f55ea99449b829.json b/rust/cloud-storage/email_scheduled_handler/.sqlx/query-146bbdcb331e7503ba92aea61d9da3b321b1950707a533f737f55ea99449b829.json
deleted file mode 100644
index 891c7bc225..0000000000
--- a/rust/cloud-storage/email_scheduled_handler/.sqlx/query-146bbdcb331e7503ba92aea61d9da3b321b1950707a533f737f55ea99449b829.json
+++ /dev/null
@@ -1,26 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT\n link_id, message_id\n FROM email_scheduled_messages\n WHERE\n send_time < now()\n AND sent = FALSE\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "link_id",
- "type_info": "Uuid"
- },
- {
- "ordinal": 1,
- "name": "message_id",
- "type_info": "Uuid"
- }
- ],
- "parameters": {
- "Left": []
- },
- "nullable": [
- false,
- false
- ]
- },
- "hash": "146bbdcb331e7503ba92aea61d9da3b321b1950707a533f737f55ea99449b829"
-}
diff --git a/rust/cloud-storage/email_scheduled_handler/.sqlx/query-2386c156456dbaea33ec5071907677174bdfc3048719f1be818c11b6dd7ada01.json b/rust/cloud-storage/email_scheduled_handler/.sqlx/query-2386c156456dbaea33ec5071907677174bdfc3048719f1be818c11b6dd7ada01.json
new file mode 100644
index 0000000000..5c0001485c
--- /dev/null
+++ b/rust/cloud-storage/email_scheduled_handler/.sqlx/query-2386c156456dbaea33ec5071907677174bdfc3048719f1be818c11b6dd7ada01.json
@@ -0,0 +1,26 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n esm.link_id, esm.message_id\n FROM email_scheduled_messages esm\n JOIN email_messages em ON em.id = esm.message_id\n WHERE\n esm.send_time < now()\n AND esm.sent = FALSE\n AND em.is_draft = TRUE\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "link_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "message_id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "2386c156456dbaea33ec5071907677174bdfc3048719f1be818c11b6dd7ada01"
+}
diff --git a/rust/cloud-storage/email_scheduled_handler/Cargo.toml b/rust/cloud-storage/email_scheduled_handler/Cargo.toml
index 1634e0f5f7..3c3f7e4466 100644
--- a/rust/cloud-storage/email_scheduled_handler/Cargo.toml
+++ b/rust/cloud-storage/email_scheduled_handler/Cargo.toml
@@ -21,3 +21,6 @@ tracing = { workspace = true }
[package.metadata.cargo-machete]
ignored = ["openssl"]
+
+[dev-dependencies]
+macro_db_migrator = { path = "../macro_db_migrator" }
\ No newline at end of file
diff --git a/rust/cloud-storage/email_scheduled_handler/src/handler.rs b/rust/cloud-storage/email_scheduled_handler/src/handler.rs
index 8a58cf2f22..6124137641 100644
--- a/rust/cloud-storage/email_scheduled_handler/src/handler.rs
+++ b/rust/cloud-storage/email_scheduled_handler/src/handler.rs
@@ -5,30 +5,20 @@ use lambda_runtime::{
tracing::{self},
};
use models_email::service::pubsub::ScheduledPubsubMessage;
+use sqlx::PgPool;
#[tracing::instrument(skip(ctx, _event))]
pub async fn handler(
ctx: context::Context,
_event: LambdaEvent<EventBridgeEvent>,
) -> Result<(), Error> {
- // grab all messages with passed send_time that have not been sent already
- let notifications = sqlx::query_as!(
- ScheduledPubsubMessage,
- r#"
- SELECT
- link_id, message_id
- FROM email_scheduled_messages
- WHERE
- send_time < now()
- AND sent = FALSE
- "#,
- )
- .fetch_all(&ctx.db)
- .await
- .unwrap_or_else(|e| {
- tracing::error!("Error fetching scheduled messages: {}", e);
- Vec::new()
- });
+ // grab all drafts with passed send_time that have not been sent already
+ let notifications = fetch_pending_scheduled_messages(&ctx.db)
+ .await
+ .unwrap_or_else(|e| {
+ tracing::error!(error=?e, "Error fetching scheduled messages");
+ Vec::new()
+ });
if !notifications.is_empty() {
tracing::info!(notifications = ?notifications, "Sending scheduled email pubsub messages");
@@ -37,7 +27,11 @@ pub async fn handler(
for notif in notifications.into_iter() {
let message_id = notif.message_id;
let link_id = notif.link_id;
- if let Err(e) = ctx.sqs_client.enqueue_email_scheduled_message(notif).await {
+ if let Err(e) = ctx
+ .sqs_client
+ .enqueue_email_scheduled_message(notif, None)
+ .await
+ {
tracing::error!(
error = ?e,
link_id = link_id.to_string(),
@@ -49,3 +43,31 @@ pub async fn handler(
Ok(())
}
+
+/// Fetches all scheduled messages that are ready to be sent.
+/// Only returns messages where:
+/// - send_time has passed (< now())
+/// - sent = false
+/// - the associated email message is still a draft (is_draft = true)
+#[tracing::instrument(skip(pool), err)]
+pub async fn fetch_pending_scheduled_messages(
+ pool: &PgPool,
+) -> anyhow::Result<Vec<ScheduledPubsubMessage>> {
+ let messages = sqlx::query_as!(
+ ScheduledPubsubMessage,
+ r#"
+ SELECT
+ esm.link_id, esm.message_id
+ FROM email_scheduled_messages esm
+ JOIN email_messages em ON em.id = esm.message_id
+ WHERE
+ esm.send_time < now()
+ AND esm.sent = FALSE
+ AND em.is_draft = TRUE
+ "#,
+ )
+ .fetch_all(pool)
+ .await?;
+
+ Ok(messages)
+}
diff --git a/rust/cloud-storage/email_scheduled_handler/src/main.rs b/rust/cloud-storage/email_scheduled_handler/src/main.rs
index 2cc418d27d..8fefc73ccb 100644
--- a/rust/cloud-storage/email_scheduled_handler/src/main.rs
+++ b/rust/cloud-storage/email_scheduled_handler/src/main.rs
@@ -1,6 +1,8 @@
mod config;
mod context;
mod handler;
+#[cfg(test)]
+mod test;
use anyhow::Context;
use aws_lambda_events::event::eventbridge::EventBridgeEvent;
diff --git a/rust/cloud-storage/email_scheduled_handler/src/test/fixtures/fetch_pending_scheduled_messages.sql b/rust/cloud-storage/email_scheduled_handler/src/test/fixtures/fetch_pending_scheduled_messages.sql
new file mode 100644
index 0000000000..35a69c4d52
--- /dev/null
+++ b/rust/cloud-storage/email_scheduled_handler/src/test/fixtures/fetch_pending_scheduled_messages.sql
@@ -0,0 +1,154 @@
+-- SQL fixture for fetch_pending_scheduled_messages tests
+-- Tests fetching scheduled messages that are ready to be sent
+
+------------------------------------------------------------
+-- User Links
+------------------------------------------------------------
+
+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-000000000f01', 'macro|[email protected]', '00000000-0000-0000-0000-000000000f01',
+ '[email protected]', 'GMAIL', true, NOW(), NOW());
+
+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-000000000f02', 'macro|[email protected]', '00000000-0000-0000-0000-000000000f02',
+ '[email protected]', 'GMAIL', true, NOW(), NOW());
+
+------------------------------------------------------------
+-- Contacts
+------------------------------------------------------------
+
+INSERT INTO email_contacts (id, link_id, email_address, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-0000000cf001',
+ '00000000-0000-0000-0000-000000000f01',
+ NOW(), NOW());
+
+INSERT INTO email_contacts (id, link_id, email_address, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-0000000cf002',
+ '00000000-0000-0000-0000-000000000f02',
+ NOW(), NOW());
+
+------------------------------------------------------------
+-- Threads
+------------------------------------------------------------
+
+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-00000000f201',
+ '00000000-0000-0000-0000-000000000f01',
+ true, false, NOW(), NOW());
+
+INSERT INTO email_threads (id, link_id, inbox_visible, is_read, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-00000000f202',
+ '00000000-0000-0000-0000-000000000f02',
+ true, false, NOW(), NOW());
+
+------------------------------------------------------------
+-- Message 1: Draft with past send_time, not sent (SHOULD BE RETURNED)
+------------------------------------------------------------
+
+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, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-00000000f501',
+ '00000000-0000-0000-0000-00000000f201',
+ '00000000-0000-0000-0000-000000000f01',
+ 'provider-pending-501',
+ FALSE,
+ '00000000-0000-0000-0000-0000000cf001',
+ '2025-01-10 10:00:00 +00:00',
+ false, false, false, true, NOW(), NOW());
+
+INSERT INTO email_scheduled_messages (link_id, message_id, send_time, sent, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-000000000f01',
+ '00000000-0000-0000-0000-00000000f501',
+ '2020-01-01 10:00:00 +00:00', -- Past date
+ false,
+ NOW(), NOW());
+
+------------------------------------------------------------
+-- Message 2: Draft with future send_time, not sent (SHOULD NOT BE RETURNED)
+------------------------------------------------------------
+
+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, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-00000000f502',
+ '00000000-0000-0000-0000-00000000f201',
+ '00000000-0000-0000-0000-000000000f01',
+ 'provider-pending-502',
+ FALSE,
+ '00000000-0000-0000-0000-0000000cf001',
+ '2025-01-10 11:00:00 +00:00',
+ false, false, false, true, NOW(), NOW());
+
+INSERT INTO email_scheduled_messages (link_id, message_id, send_time, sent, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-000000000f01',
+ '00000000-0000-0000-0000-00000000f502',
+ '2099-12-31 23:59:59 +00:00', -- Future date
+ false,
+ NOW(), NOW());
+
+------------------------------------------------------------
+-- Message 3: Draft with past send_time, already sent (SHOULD NOT BE RETURNED)
+------------------------------------------------------------
+
+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, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-00000000f503',
+ '00000000-0000-0000-0000-00000000f201',
+ '00000000-0000-0000-0000-000000000f01',
+ 'provider-pending-503',
+ FALSE,
+ '00000000-0000-0000-0000-0000000cf001',
+ '2025-01-10 12:00:00 +00:00',
+ false, false, false, true, NOW(), NOW());
+
+INSERT INTO email_scheduled_messages (link_id, message_id, send_time, sent, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-000000000f01',
+ '00000000-0000-0000-0000-00000000f503',
+ '2020-01-01 12:00:00 +00:00', -- Past date
+ true, -- Already sent
+ NOW(), NOW());
+
+------------------------------------------------------------
+-- Message 4: NOT a draft (is_draft = false) with past send_time, not sent (SHOULD NOT BE RETURNED)
+------------------------------------------------------------
+
+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, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-00000000f504',
+ '00000000-0000-0000-0000-00000000f201',
+ '00000000-0000-0000-0000-000000000f01',
+ 'provider-pending-504',
+ TRUE,
+ '00000000-0000-0000-0000-0000000cf001',
+ '2025-01-10 13:00:00 +00:00',
+ false, false, false, false, NOW(), NOW()); -- is_draft = false
+
+INSERT INTO email_scheduled_messages (link_id, message_id, send_time, sent, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-000000000f01',
+ '00000000-0000-0000-0000-00000000f504',
+ '2020-01-01 13:00:00 +00:00', -- Past date
+ false,
+ NOW(), NOW());
+
+------------------------------------------------------------
+-- Message 5: Another draft with past send_time from different link (SHOULD BE RETURNED)
+------------------------------------------------------------
+
+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, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-00000000f505',
+ '00000000-0000-0000-0000-00000000f202',
+ '00000000-0000-0000-0000-000000000f02',
+ 'provider-pending-505',
+ FALSE,
+ '00000000-0000-0000-0000-0000000cf002',
+ '2025-01-10 14:00:00 +00:00',
+ false, false, false, true, NOW(), NOW());
+
+INSERT INTO email_scheduled_messages (link_id, message_id, send_time, sent, created_at, updated_at)
+VALUES ('00000000-0000-0000-0000-000000000f02',
+ '00000000-0000-0000-0000-00000000f505',
+ '2020-01-01 14:00:00 +00:00', -- Past date
+ false,
+ NOW(), NOW());
\ No newline at end of file
diff --git a/rust/cloud-storage/email_scheduled_handler/src/test/mod.rs b/rust/cloud-storage/email_scheduled_handler/src/test/mod.rs
new file mode 100644
index 0000000000..405da9b545
--- /dev/null
+++ b/rust/cloud-storage/email_scheduled_handler/src/test/mod.rs
@@ -0,0 +1,111 @@
+use crate::handler::fetch_pending_scheduled_messages;
+use anyhow::Result;
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use sqlx::types::Uuid;
+use sqlx::{Pool, Postgres};
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "fixtures", scripts("fetch_pending_scheduled_messages"))
+)]
+async fn fetch_pending_returns_only_eligible_messages(pool: Pool<Postgres>) -> Result<()> {
+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;
+
+ let results = fetch_pending_scheduled_messages(&pool).await?;
+
+ // Should return exactly 2 messages:
+ // - Message 1: Draft with past send_time, not sent
+ // - Message 5: Draft with past send_time, not sent (different link)
+ assert_eq!(results.len(), 2);
+
+ let message_ids: Vec<Uuid> = results.iter().map(|r| r.message_id).collect();
+
+ assert!(message_ids.contains(&Uuid::parse_str("00000000-0000-0000-0000-00000000f501")?));
+ assert!(message_ids.contains(&Uuid::parse_str("00000000-0000-0000-0000-00000000f505")?));
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "fixtures", scripts("fetch_pending_scheduled_messages"))
+)]
+async fn fetch_pending_excludes_future_send_time(pool: Pool<Postgres>) -> Result<()> {
+ let results = fetch_pending_scheduled_messages(&pool).await?;
+
+ let message_ids: Vec<Uuid> = results.iter().map(|r| r.message_id).collect();
+
+ // Message 2 has future send_time, should not be included
+ assert!(!message_ids.contains(&Uuid::parse_str("00000000-0000-0000-0000-00000000f502")?));
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "fixtures", scripts("fetch_pending_scheduled_messages"))
+)]
+async fn fetch_pending_excludes_already_sent(pool: Pool<Postgres>) -> Result<()> {
+ let results = fetch_pending_scheduled_messages(&pool).await?;
+
+ let message_ids: Vec<Uuid> = results.iter().map(|r| r.message_id).collect();
+
+ // Message 3 has sent = true, should not be included
+ assert!(!message_ids.contains(&Uuid::parse_str("00000000-0000-0000-0000-00000000f503")?));
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "fixtures", scripts("fetch_pending_scheduled_messages"))
+)]
+async fn fetch_pending_excludes_non_drafts(pool: Pool<Postgres>) -> Result<()> {
+ let results = fetch_pending_scheduled_messages(&pool).await?;
+
+ let message_ids: Vec<Uuid> = results.iter().map(|r| r.message_id).collect();
+
+ // Message 4 has is_draft = false, should not be included
+ assert!(!message_ids.contains(&Uuid::parse_str("00000000-0000-0000-0000-00000000f504")?));
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "fixtures", scripts("fetch_pending_scheduled_messages"))
+)]
+async fn fetch_pending_returns_correct_link_ids(pool: Pool<Postgres>) -> Result<()> {
+ let results = fetch_pending_scheduled_messages(&pool).await?;
+
+ let link_id_1 = Uuid::parse_str("00000000-0000-0000-0000-000000000f01")?;
+ let link_id_2 = Uuid::parse_str("00000000-0000-0000-0000-000000000f02")?;
+
+ // Find message from link 1
+ let msg_from_link_1 = results
+ .iter()
+ .find(|r| r.message_id == Uuid::parse_str("00000000-0000-0000-0000-00000000f501").unwrap());
+ assert!(msg_from_link_1.is_some());
+ assert_eq!(msg_from_link_1.unwrap().link_id, link_id_1);
+
+ // Find message from link 2
+ let msg_from_link_2 = results
+ .iter()
+ .find(|r| r.message_id == Uuid::parse_str("00000000-0000-0000-0000-00000000f505").unwrap());
+ assert!(msg_from_link_2.is_some());
+ assert_eq!(msg_from_link_2.unwrap().link_id, link_id_2);
+
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn fetch_pending_returns_empty_when_no_scheduled_messages(
+ pool: Pool<Postgres>,
+) -> Result<()> {
+ // No fixtures loaded, database is empty
+ let results = fetch_pending_scheduled_messages(&pool).await?;
+
+ assert!(results.is_empty());
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/email_service/Cargo.toml b/rust/cloud-storage/email_service/Cargo.toml
index 9130e8c827..1ba71598f4 100644
--- a/rust/cloud-storage/email_service/Cargo.toml
+++ b/rust/cloud-storage/email_service/Cargo.toml
@@ -61,6 +61,7 @@ axum = { workspace = true }
axum-extra = { workspace = true }
base64 = { workspace = true }
bytes = { workspace = true }
+chrono = { workspace = true }
cloudfront_sign = { workspace = true }
connection_gateway = { path = "../connection_gateway" }
document_storage_service_client = { path = "../document_storage_service_client" }
diff --git a/rust/cloud-storage/email_service/justfile b/rust/cloud-storage/email_service/justfile
index 1a65509fa1..696b7e202f 100644
--- a/rust/cloud-storage/email_service/justfile
+++ b/rust/cloud-storage/email_service/justfile
@@ -31,8 +31,7 @@ create-queues:
AWS_REGION=us-east-1 aws --endpoint-url=http://localhost:4566 sqs create-queue \
--queue-name my-test-link-manager-queue
AWS_REGION=us-east-1 aws --endpoint-url=http://localhost:4566 sqs create-queue \
- --queue-name my-test-scheduled-queue.fifo \
- --attributes FifoQueue=true,ContentBasedDeduplication=true
+ --queue-name my-test-scheduled-queue
AWS_REGION=us-east-1 aws --endpoint-url=http://localhost:4566 sqs create-queue \
--queue-name backfill-queue --attributes VisibilityTimeout=61
AWS_REGION=us-east-1 aws --endpoint-url=http://localhost:4566 sqs create-queue \
@@ -54,7 +53,7 @@ purge-queues:
AWS_REGION=us-east-1 aws --endpoint-url=http://localhost:4566 sqs purge-queue \
--queue-url http://sqs.us-east-1.localhost.localstack.cloud:4566/000000000000/my-test-link-manager-queue
AWS_REGION=us-east-1 aws --endpoint-url=http://localhost:4566 sqs purge-queue \
- --queue-url http://sqs.us-east-1.localhost.localstack.cloud:4566/000000000000/my-test-scheduled-queue.fifo
+ --queue-url http://sqs.us-east-1.localhost.localstack.cloud:4566/000000000000/my-test-scheduled-queue
AWS_REGION=us-east-1 aws --endpoint-url=http://localhost:4566 sqs purge-queue \
--queue-url http://sqs.us-east-1.localhost.localstack.cloud:4566/000000000000/search-queue
AWS_REGION=us-east-1 aws --endpoint-url=http://localhost:4566 sqs purge-queue \
diff --git a/rust/cloud-storage/email_service/src/api/email/drafts/create.rs b/rust/cloud-storage/email_service/src/api/email/drafts/create.rs
index a25a9b21a5..72528164c4 100644
--- a/rust/cloud-storage/email_service/src/api/email/drafts/create.rs
+++ b/rust/cloud-storage/email_service/src/api/email/drafts/create.rs
@@ -4,8 +4,10 @@ use axum::extract::State;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::{Extension, Json};
+use base64::Engine;
+use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use email_db_client::contacts::upsert_message::parse_and_upsert_message_contacts;
-use email_db_client::messages::insert::insert_message_to_send;
+use email_db_client::messages::insert::insert_message_to_send_db;
use email_db_client::parse::service_to_db::addresses_from_message;
use email_db_client::user_history::upsert_user_history;
use model::response::ErrorResponse;
@@ -13,6 +15,7 @@ use model::user::UserContext;
use models_email::email::db::address::UpsertedRecipients;
use models_email::service::link::Link;
use models_email::service::{message, thread};
+use sqlx::PgPool;
use sqlx::types::chrono::{DateTime, Utc};
use strum_macros::AsRefStr;
use thiserror::Error;
@@ -28,25 +31,26 @@ pub enum CreateDraftError {
#[error("A database transaction error occurred")]
TransactionError(#[from] sqlx::Error),
+
+ #[error("Failed to decode base64 HTML body")]
+ Base64DecodeError(#[from] base64::DecodeError),
+
+ #[error("Failed to convert decoded HTML body to UTF-8")]
+ Utf8Error(#[from] std::string::FromUtf8Error),
}
impl IntoResponse for CreateDraftError {
fn into_response(self) -> Response {
let status_code = match &self {
CreateDraftError::Validation(e) => e.status_code(),
+ CreateDraftError::Base64DecodeError(_) | CreateDraftError::Utf8Error(_) => {
+ StatusCode::BAD_REQUEST
+ }
CreateDraftError::InsertError(_) | CreateDraftError::TransactionError(_) => {
StatusCode::INTERNAL_SERVER_ERROR
}
};
- if status_code.is_server_error() {
- tracing::error!(
- nested_error = ?self,
- error_type = "CreateDraftError",
- variant = self.as_ref(),
- "Internal server error");
- }
-
(status_code, self.to_string()).into_response()
}
}
@@ -55,6 +59,7 @@ impl IntoResponse for CreateDraftError {
#[derive(Debug, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct CreateDraftRequest {
pub draft: message::MessageToSend,
+ pub send_time: Option<DateTime<Utc>>,
}
#[derive(Debug, serde::Serialize, serde::Deserialize, ToSchema)]
@@ -81,7 +86,8 @@ pub struct CreateDraftResponse {
fields(
user_id = user_context.user_id,
fusionauth_user_id = user_context.fusion_user_id
- )
+ ),
+ err
)]
pub async fn handler(
State(ctx): State<ApiContext>,
@@ -89,31 +95,56 @@ pub async fn handler(
link: Extension<Link>,
Json(request_body): Json<CreateDraftRequest>,
) -> Result<Response, CreateDraftError> {
- let mut draft = request_body.draft;
+ // falling back to old value for backwards compatability for now.
+ let send_time = request_body.send_time.or(request_body.draft.send_time);
+ let draft =
+ process_message_to_send(&ctx.db, &link, request_body.draft, send_time, true).await?;
+ Ok((StatusCode::CREATED, Json(CreateDraftResponse { draft })).into_response())
+}
+
+pub async fn process_message_to_send(
+ db: &PgPool,
+ link: &Link,
+ mut draft: message::MessageToSend,
+ send_time: Option<DateTime<Utc>>,
+ is_draft: bool,
+) -> Result<message::MessageToSend, CreateDraftError> {
// TODO: Create api layer struct that doesn't have this value
draft.link_id = link.id;
- validation::validate_existing_message(&ctx.db, &link.fusionauth_user_id, &mut draft).await?;
+ validation::validate_existing_message(db, &link.fusionauth_user_id, &mut draft).await?;
- validation::validate_replying_to_id(&ctx.db, &mut draft, &link).await?;
+ validation::validate_replying_to_id(db, &mut draft, link).await?;
let from_email = link.email_address.0.as_ref();
+ // html comes in as a base64 encoded string, need to decode before inserting
+ if let Some(html_body) = draft.body_html {
+ let decoded_html = URL_SAFE_NO_PAD.decode(html_body.as_bytes())?;
+ let decoded_html_str = String::from_utf8(decoded_html)?;
+
+ // Store the decoded HTML back into the message
+ draft.body_html = Some(decoded_html_str);
+ }
+
// Parse and upsert contacts before starting the transaction to avoid deadlocks.
// Contacts are shared across messages so they must be inserted outside the transaction.
let addresses = addresses_from_message(&draft);
- let recipients = parse_and_upsert_message_contacts(&ctx.db, link.id, addresses)
+ let recipients = parse_and_upsert_message_contacts(db, link.id, addresses)
.await
.map_err(CreateDraftError::InsertError)?;
- let mut tx = ctx.db.begin().await?;
+ let mut tx = db.begin().await?;
- let result = insert_draft(&mut tx, &mut draft, from_email, recipients).await;
+ let result = insert_message_to_send(
+ &mut tx, &mut draft, send_time, is_draft, from_email, recipients,
+ )
+ .await;
match result {
Ok(_) => {
tx.commit().await?;
- Ok((StatusCode::CREATED, Json(CreateDraftResponse { draft })).into_response())
+ Ok(draft)
}
Err(e) => {
if let Err(rollback_err) = tx.rollback().await {
@@ -125,9 +156,11 @@ pub async fn handler(
}
#[tracing::instrument(skip(tx, recipients), err)]
-async fn insert_draft(
+async fn insert_message_to_send(
tx: &mut sqlx::PgConnection,
draft: &mut message::MessageToSend,
+ send_time: Option<DateTime<Utc>>,
+ is_draft: bool,
from_email: &str,
recipients: UpsertedRecipients,
) -> anyhow::Result<()> {
@@ -162,7 +195,16 @@ async fn insert_draft(
let from_email_id =
email_db_client::contacts::get::fetch_id_by_email(tx, link_id, from_email).await?;
- insert_message_to_send(tx, draft, thread_db_id, from_email_id, true, recipients).await?;
+ insert_message_to_send_db(
+ tx,
+ draft,
+ send_time,
+ thread_db_id,
+ from_email_id,
+ is_draft,
+ recipients,
+ )
+ .await?;
upsert_user_history(tx, link_id, thread_db_id).await?;
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
index e12998636e..c3bafc5736 100644
--- 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
@@ -76,7 +76,7 @@ pub async fn handler(
.await?
.ok_or(DeleteScheduledError::NotFound)?;
- if scheduled_message.sent {
+ if scheduled_message.sent || scheduled_message.processing {
return Err(DeleteScheduledError::AlreadySent);
}
@@ -85,6 +85,12 @@ pub async fn handler(
)
.await?;
+ // if we undo send for a message, turn it back into a draft
+ email_db_client::messages::update::update_message_draft_status(
+ &mut tx, message_id, link.id, true,
+ )
+ .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
index 9a2881891c..658499f8fe 100644
--- 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
@@ -93,6 +93,7 @@ pub async fn handler(
message_id: draft_id,
send_time: request.send_time,
sent: false,
+ processing: false,
};
// Upsert the scheduled message
diff --git a/rust/cloud-storage/email_service/src/api/email/messages/mod.rs b/rust/cloud-storage/email_service/src/api/email/messages/mod.rs
index fc9230db31..f68fed49fd 100644
--- a/rust/cloud-storage/email_service/src/api/email/messages/mod.rs
+++ b/rust/cloud-storage/email_service/src/api/email/messages/mod.rs
@@ -11,13 +11,7 @@ const BATCH_UPDATE_MESSAGE_LIMIT: usize = 10;
pub fn router(state: ApiContext) -> Router<ApiContext> {
Router::new()
- .route(
- "/",
- post(send::send_handler).layer(axum::middleware::from_fn_with_state(
- state.clone(),
- crate::api::middleware::gmail_token::attach_gmail_token,
- )),
- )
+ .route("/", post(send::send_handler))
.route(
"/labels",
patch(labels::handler).layer(axum::middleware::from_fn_with_state(
diff --git a/rust/cloud-storage/email_service/src/api/email/messages/send.rs b/rust/cloud-storage/email_service/src/api/email/messages/send.rs
index a7d4963d8e..fbb9ca4c9f 100644
--- a/rust/cloud-storage/email_service/src/api/email/messages/send.rs
+++ b/rust/cloud-storage/email_service/src/api/email/messages/send.rs
@@ -1,83 +1,43 @@
use crate::api::context::ApiContext;
-use crate::api::email::validation::{self, ValidationError};
-use anyhow::Context;
+use crate::api::email::drafts::create::{CreateDraftError, process_message_to_send};
use axum::extract::State;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::{Extension, Json};
-use base64::Engine;
-use base64::engine::general_purpose::URL_SAFE_NO_PAD;
-use email_db_client::contacts::upsert_message::parse_and_upsert_message_contacts;
-use email_db_client::messages::insert::insert_message_to_send;
-use email_db_client::parse::service_to_db::addresses_from_message;
-use email_service::util::gmail::send;
+use chrono::Duration;
use model::response::ErrorResponse;
use model::user::UserContext;
-use models_email::email::db::address::UpsertedRecipients;
-use models_email::email::service::address::ContactInfo;
-use models_email::email::service::{message, thread};
+use models_email::email::service::message;
use models_email::service::link::Link;
-use sqlx::types::chrono::{DateTime, Utc};
+use models_email::service::pubsub::ScheduledPubsubMessage;
+use sqlx::types::chrono::Utc;
use strum_macros::AsRefStr;
use thiserror::Error;
use utoipa::ToSchema;
-
#[derive(Debug, Error, AsRefStr)]
pub enum SendMessageError {
- #[error("Validation error: {0}")]
- Validation(#[from] ValidationError),
-
- #[error("Sender contact not found")]
- SenderContactNotFound,
-
- #[error("Failed to decode base64 HTML body")]
- Base64DecodeError(#[from] base64::DecodeError),
+ #[error("Failed to create draft: {0}")]
+ DraftError(#[from] CreateDraftError),
- #[error("Failed to convert decoded HTML body to UTF-8")]
- Utf8Error(#[from] std::string::FromUtf8Error),
+ #[error("Failed to enqueue scheduled message: {0}")]
+ EnqueueError(#[from] anyhow::Error),
- #[error("Failed to send message via Gmail")]
- GmailSendError(#[from] anyhow::Error),
-
- #[error("Failed to fetch attachments for message: {0}")]
- AttachmentError(anyhow::Error),
-
- #[error("Internal error")]
- InternalError(#[from] sqlx::Error),
+ #[error("Draft ID not found after creation")]
+ MissingDraftId,
}
impl IntoResponse for SendMessageError {
fn into_response(self) -> Response {
- let status_code = match &self {
- SendMessageError::Validation(e) => e.status_code(),
- SendMessageError::Base64DecodeError(_) | SendMessageError::Utf8Error(_) => {
- StatusCode::BAD_REQUEST
- }
- SendMessageError::SenderContactNotFound
- | SendMessageError::GmailSendError(_)
- | SendMessageError::AttachmentError(_)
- | SendMessageError::InternalError(_) => StatusCode::INTERNAL_SERVER_ERROR,
- };
-
- let error_message = match &self {
- SendMessageError::AttachmentError(_) => {
- "Failed to fetch attachments for message".to_string()
- }
- SendMessageError::Validation(_)
- | SendMessageError::SenderContactNotFound
- | SendMessageError::Base64DecodeError(_)
- | SendMessageError::Utf8Error(_)
- | SendMessageError::GmailSendError(_)
- | SendMessageError::InternalError(_) => self.to_string(),
- };
-
- (
- status_code,
- Json(ErrorResponse {
- message: error_message.as_str(),
- }),
- )
- .into_response()
+ match self {
+ SendMessageError::DraftError(e) => e.into_response(),
+ SendMessageError::EnqueueError(_) | SendMessageError::MissingDraftId => (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(ErrorResponse {
+ message: "Internal server error",
+ }),
+ )
+ .into_response(),
+ }
}
}
@@ -107,204 +67,37 @@ pub struct SendMessageResponse {
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, user_context, gmail_token, request_body), fields(user_id=user_context.user_id, fusionauth_user_id=user_context.fusion_user_id), err)]
+#[tracing::instrument(skip(ctx, user_context, request_body), fields(user_id=user_context.user_id, fusionauth_user_id=user_context.fusion_user_id), err)]
pub async fn send_handler(
State(ctx): State<ApiContext>,
user_context: Extension<UserContext>,
- gmail_token: Extension<String>,
link: Extension<Link>,
Json(request_body): Json<SendMessageRequest>,
) -> Result<Response, SendMessageError> {
- let mut message_to_send = request_body.message;
- // TODO: Make api-layer struct that doesn't have this or provider ids
- message_to_send.link_id = link.id;
+ let undo_delay_secs = ctx.config.sent_undo_delay_secs;
+ let send_time = Utc::now() + Duration::seconds(undo_delay_secs as i64);
- validation::validate_existing_message(&ctx.db, &link.fusionauth_user_id, &mut message_to_send)
- .await?;
+ let draft =
+ process_message_to_send(&ctx.db, &link, request_body.message, Some(send_time), false)
+ .await?;
- validation::validate_replying_to_id(&ctx.db, &mut message_to_send, &link).await?;
+ let message_db_id = draft.db_id.ok_or(SendMessageError::MissingDraftId)?;
- let sender_contact = email_db_client::contacts::get::fetch_contact_by_email(
- &ctx.db,
- link.id,
- link.email_address.0.as_ref(),
- )
- .await?
- .ok_or(SendMessageError::SenderContactNotFound)?;
-
- let from_contact = ContactInfo {
- email: link.email_address.0.as_ref().to_string(),
- name: sender_contact.name,
- photo_url: sender_contact.photo_url,
+ let scheduled_message = ScheduledPubsubMessage {
+ link_id: link.id,
+ message_id: message_db_id,
};
- // Generate email headers that are used for threading
- let (parent_message_id, references) =
- send::generate_email_threading_headers(&ctx.db, message_to_send.replying_to_id, link.id)
- .await;
-
- // html comes in as a base64 encoded string, need to decode before inserting
- if let Some(html_body) = message_to_send.body_html {
- let decoded_html = URL_SAFE_NO_PAD.decode(html_body.as_bytes())?;
- let decoded_html_str = String::from_utf8(decoded_html)?;
-
- // Store the decoded HTML back into the message
- message_to_send.body_html = Some(decoded_html_str);
- }
-
- // if we are creating a new thread, we need to have a ts for the message in the db less than
- // the actual sent time. this is so the value gets updated in the inbox sync when gmail sends us the
- // processed message post-send
- let before_send_ts = Utc::now();
-
- // Include attachments for message
- let db_attachments = send::fetch_and_attach_draft_attachments(
- &ctx.db,
- &ctx.s3_client,
- ctx.config.attachment_bucket.as_str(),
- &link,
- &mut message_to_send,
- )
- .await
- .map_err(SendMessageError::AttachmentError)?;
+ // small delay to give user more time to undo send
+ let delay_seconds = undo_delay_secs as i32 + 2;
- ctx.gmail_client
- .send_message(
- gmail_token.as_str(),
- &mut message_to_send,
- &from_contact,
- parent_message_id,
- references,
- )
+ ctx.sqs_client
+ .enqueue_email_scheduled_message(scheduled_message, Some(delay_seconds))
.await?;
- // Parse and upsert contacts before starting the transaction to avoid deadlocks.
- // Contacts are shared across messages so they must be inserted outside the transaction.
- let addresses = addresses_from_message(&message_to_send);
- let recipients = parse_and_upsert_message_contacts(&ctx.db, link.id, addresses)
- .await
- .context("Failed to upsert message contacts")?;
-
- let mut tx = ctx.db.begin().await?;
-
- let result = insert_sent_message(
- &mut tx,
- &mut message_to_send,
- from_contact,
- before_send_ts,
- recipients,
+ Ok((
+ StatusCode::CREATED,
+ Json(SendMessageResponse { message: draft }),
)
- .await;
-
- match result {
- Ok(_) => {
- tx.commit().await?;
-
- // Cleanup attachments in the background
- if let (Some(draft_id), Some(attachments)) = (message_to_send.db_id, db_attachments) {
- let db = ctx.db.clone();
- let bucket = ctx.config.attachment_bucket.clone();
- let link_id = link.id;
- tokio::spawn(async move {
- send::cleanup_draft_attachments(
- db,
- &ctx.s3_client,
- bucket,
- link_id,
- draft_id,
- attachments,
- )
- .await;
- });
- }
-
- Ok((
- StatusCode::CREATED,
- Json(SendMessageResponse {
- message: message_to_send,
- }),
- )
- .into_response())
- }
- Err(e) => {
- if let Err(rollback_err) = tx.rollback().await {
- tracing::error!(error=?rollback_err, provider_id=?message_to_send.provider_id, "Failed to rollback transaction after sent message insert failure");
- }
- Err(SendMessageError::from(e))
- }
- }
-}
-
-async fn insert_sent_message(
- tx: &mut sqlx::PgConnection,
- message_to_send: &mut message::MessageToSend,
- from_contact: ContactInfo,
- before_send_ts: DateTime<Utc>,
- recipients: UpsertedRecipients,
-) -> anyhow::Result<()> {
- let mut thread_db_id = message_to_send.thread_db_id;
- let thread_provider_id = message_to_send.provider_thread_id.clone();
- let now: DateTime<Utc> = Utc::now();
- let link_id = message_to_send.link_id;
-
- // if there isn't already a thread associated with this message, create one
- match thread_db_id {
- None => {
- let thread = thread::Thread {
- db_id: None,
- provider_id: Some(thread_provider_id.clone().unwrap()), // safe bc it always gets populated in gmail_client
- link_id,
- // if we're creating a thread with a sent message, it's not visible in the inbox
- inbox_visible: true,
- is_read: true,
- latest_inbound_message_ts: None,
- latest_outbound_message_ts: Some(before_send_ts),
- latest_non_spam_message_ts: Some(before_send_ts),
- created_at: now,
- updated_at: now,
- messages: Vec::new(),
- };
-
- thread_db_id = Option::from(
- email_db_client::threads::insert::insert_thread(&mut *tx, &thread, link_id)
- .await
- .context("unable to insert thread")?,
- );
- message_to_send.thread_db_id = thread_db_id;
- }
- Some(thread_db_id) => {
- // need to upsert the thread's provider_id in case it doesn't exist already (e.g. if we are
- // sending a previously existing draft that is the first message in the thread)
- email_db_client::threads::update::update_thread_provider_id(
- tx,
- thread_db_id,
- link_id,
- &thread_provider_id.clone().unwrap(),
- )
- .await
- .context(format!(
- "Failed to update provider id to {} for thread {}",
- thread_provider_id.clone().unwrap(),
- thread_db_id
- ))?;
- }
- }
-
- let from_email_id =
- // safe because we always populate the from field before calling this function
- email_db_client::contacts::get::fetch_id_by_email(tx, link_id, from_contact.email.as_str())
- .await.context("unable to fetch from email id")?;
-
- insert_message_to_send(
- tx,
- message_to_send,
- thread_db_id.unwrap(),
- from_email_id,
- false,
- recipients,
- )
- .await
- .context("unable to insert message to send")?;
-
- Ok(())
+ .into_response())
}
diff --git a/rust/cloud-storage/email_service/src/config.rs b/rust/cloud-storage/email_service/src/config.rs
index 5da443db63..fc84d61dc8 100644
--- a/rust/cloud-storage/email_service/src/config.rs
+++ b/rust/cloud-storage/email_service/src/config.rs
@@ -50,6 +50,9 @@ pub struct Config {
/// The SQS queue name for contacts service
pub contacts_queue: String,
+ /// The amount of time to delay processing of a sent message (undo send window) - default 10s
+ pub sent_undo_delay_secs: u32,
+
/// The SQS bucket for storing attachments
pub attachment_bucket: String,
@@ -176,6 +179,11 @@ impl Config {
let attachment_bucket =
std::env::var("ATTACHMENT_BUCKET").context("ATTACHMENT_BUCKET must be provided")?;
+ let sent_undo_delay_secs: u32 = std::env::var("SENT_UNDO_DELAY_SECS")
+ .unwrap_or("10".to_string())
+ .parse::<u32>()
+ .unwrap();
+
let notifications_enabled = std::env::var("NOTIFICATIONS_ENABLED")
.context("NOTIFICATIONS_ENABLED must be provided")?
.parse::<bool>()
@@ -286,6 +294,7 @@ impl Config {
sfs_delete_queue,
contacts_queue,
attachment_bucket,
+ sent_undo_delay_secs,
notifications_enabled,
queue_max_messages,
queue_wait_time_seconds,
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 4d8758a80d..4212df93d7 100644
--- a/rust/cloud-storage/email_service/src/pubsub/scheduled/process.rs
+++ b/rust/cloud-storage/email_service/src/pubsub/scheduled/process.rs
@@ -4,12 +4,14 @@ 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::get_scheduled_message;
+use chrono::Utc;
+use email_db_client::messages::scheduled::get::get_and_start_processing_scheduled_message;
use models_email::service::message::MessageToSend;
use models_email::service::pubsub::ScheduledPubsubMessage;
use sqlx_core::any::AnyConnectionBackend;
use sqs_worker::cleanup_message;
+#[tracing::instrument(skip(ctx, message), err)]
pub async fn process_message(
ctx: ScheduledContext,
message: &aws_sdk_sqs::types::Message,
@@ -17,11 +19,47 @@ pub async fn process_message(
// Parse the incoming message
let data = extract_scheduled_message(message)?;
+ let result = process_scheduled_message_inner(&ctx, &data).await;
+
+ if let Err(ref e) = result {
+ tracing::error!(
+ error = ?e,
+ message_id = %data.message_id,
+ link_id = %data.link_id,
+ "Failed to process scheduled message - clearing processing flag"
+ );
+ if let Err(clear_err) =
+ email_db_client::messages::scheduled::upsert::clear_scheduled_message_processing(
+ &ctx.db,
+ data.link_id,
+ data.message_id,
+ )
+ .await
+ {
+ tracing::error!(
+ error = ?clear_err,
+ message_id = %data.message_id,
+ link_id = %data.link_id,
+ "Failed to clear processing flag"
+ );
+ }
+ return result;
+ }
+
+ cleanup_message(&ctx.sqs_worker, message).await?;
+
+ Ok(())
+}
+
+#[tracing::instrument(skip(ctx), err)]
+async fn process_scheduled_message_inner(
+ ctx: &ScheduledContext,
+ data: &ScheduledPubsubMessage,
+) -> anyhow::Result<()> {
let link = email_db_client::links::get::fetch_link_by_id(&ctx.db, data.link_id).await?;
let Some(link) = link else {
tracing::debug!(link_id=%data.link_id, "Link not found - skipping");
- cleanup_message(&ctx.sqs_worker, message).await?;
return Ok(());
};
@@ -31,15 +69,16 @@ pub async fn process_message(
// Get scheduled message from database
let scheduled_message =
- match get_scheduled_message(&ctx.db, data.link_id, data.message_id).await {
+ match get_and_start_processing_scheduled_message(&ctx.db, data.link_id, data.message_id)
+ .await
+ {
Ok(Some(msg)) => msg,
Ok(None) => {
- tracing::error!(
+ tracing::info!(
link_id = ?data.link_id,
message_id = ?data.message_id,
"Scheduled message not found"
);
- cleanup_message(&ctx.sqs_worker, message).await?;
return Ok(());
}
Err(e) => {
@@ -50,102 +89,116 @@ pub async fn process_message(
}
};
- if !scheduled_message.sent {
- // fetch message from db
- let (mut message_to_send, sender_contact) =
- email_db_client::messages::get::get_message_to_send(
- &ctx.db,
- data.message_id,
- data.link_id,
- )
+ if scheduled_message.sent {
+ tracing::warn!(
+ message_id=%data.message_id,
+ link_id=%data.link_id,
+ "Scheduled message already sent - skipping"
+ );
+ return Ok(());
+ } else if scheduled_message.processing {
+ tracing::warn!(
+ message_id=%data.message_id,
+ link_id=%data.link_id,
+ "Scheduled message already being processed - skipping"
+ );
+ return Ok(());
+ } else if scheduled_message.send_time > Utc::now() {
+ tracing::warn!(
+ message_id=%data.message_id,
+ link_id=%data.link_id,
+ send_time=scheduled_message.send_time.to_string(),
+ "Scheduled message send_time is in the future - skipping"
+ );
+ return Ok(());
+ }
+
+ // fetch message from db
+ let (mut message_to_send, sender_contact) =
+ email_db_client::messages::get::get_message_to_send(&ctx.db, data.message_id, data.link_id)
.await
.context(format!(
"Failed to fetch message to gmail api for message_id {}",
data.message_id
))?;
- // generate headers
- let (parent_message_id, references) =
- generate_email_threading_headers(&ctx.db, message_to_send.replying_to_id, data.link_id)
- .await;
-
- // Include attachments for message
- let db_attachments = fetch_and_attach_draft_attachments(
- &ctx.db,
- &ctx.s3_client,
- ctx.attachment_bucket.as_str(),
- &link,
+ // generate headers
+ let (parent_message_id, references) =
+ generate_email_threading_headers(&ctx.db, message_to_send.replying_to_id, data.link_id)
+ .await;
+
+ // Include attachments for message
+ let db_attachments = fetch_and_attach_draft_attachments(
+ &ctx.db,
+ &ctx.s3_client,
+ ctx.attachment_bucket.as_str(),
+ &link,
+ &mut message_to_send,
+ )
+ .await?;
+
+ // send message to gmail api
+ ctx.gmail_client
+ .send_message(
+ gmail_access_token.as_str(),
&mut message_to_send,
+ &sender_contact,
+ parent_message_id,
+ references,
)
- .await?;
-
- // send message to gmail api
- ctx.gmail_client
- .send_message(
- gmail_access_token.as_str(),
- &mut message_to_send,
- &sender_contact,
- parent_message_id,
- references,
- )
- .await
- .context(format!(
- "Failed to send message to gmail api for message_id {}",
- data.message_id
- ))?;
+ .await
+ .context(format!(
+ "Failed to send message to gmail api for message_id {}",
+ data.message_id
+ ))?;
- let mut tx = ctx
- .db
- .begin()
- .await
- .context("Failed to begin transaction")?;
-
- // mark scheduled_messages and messages db rows as sent in single txn
- let result = mark_messages_as_sent(tx.as_mut(), &message_to_send).await;
-
- match result {
- Ok(_) => {
- tx.as_mut()
- .commit()
- .await
- .context("Failed to commit transaction")?;
-
- // Cleanup attachments in the background after successful send
- if let (Some(draft_id), Some(attachments)) = (message_to_send.db_id, db_attachments)
- {
- let db = ctx.db.clone();
- let s3_client = ctx.s3_client.clone();
- let bucket = ctx.attachment_bucket.clone();
- let link_id = link.id;
- tokio::spawn(async move {
- cleanup_draft_attachments(
- db,
- &s3_client,
- bucket,
- link_id,
- draft_id,
- attachments,
- )
- .await;
- });
- }
+ let mut tx = ctx
+ .db
+ .begin()
+ .await
+ .context("Failed to begin transaction")?;
+
+ let result = process_sent_message(tx.as_mut(), &message_to_send).await;
+
+ match result {
+ Ok(_) => {
+ tx.as_mut()
+ .commit()
+ .await
+ .context("Failed to commit transaction")?;
+
+ // Cleanup attachments in the background after successful send
+ if let (Some(draft_id), Some(attachments)) = (message_to_send.db_id, db_attachments) {
+ let db = ctx.db.clone();
+ let s3_client = ctx.s3_client.clone();
+ let bucket = ctx.attachment_bucket.clone();
+ let link_id = link.id;
+ tokio::spawn(async move {
+ cleanup_draft_attachments(
+ db,
+ &s3_client,
+ bucket,
+ link_id,
+ draft_id,
+ attachments,
+ )
+ .await;
+ });
}
- Err(e) => {
- if let Err(rollback_err) = tx.as_mut().rollback().await {
- tracing::error!(
- error = ?rollback_err,
- link_id = ?data.link_id,
- message_id = ?data.message_id,
- "Failed to rollback transaction after marking messages as sent failure"
- );
- }
- return Err(e);
+ }
+ Err(e) => {
+ if let Err(rollback_err) = tx.as_mut().rollback().await {
+ tracing::error!(
+ error = ?rollback_err,
+ link_id = ?data.link_id,
+ message_id = ?data.message_id,
+ "Failed to rollback transaction after marking messages as sent failure"
+ );
}
+ return Err(e);
}
}
- cleanup_message(&ctx.sqs_worker, message).await?;
-
Ok(())
}
@@ -159,15 +212,22 @@ fn extract_scheduled_message(
.context("Failed to deserialize message body to ScheduledPubsubMessage")
}
-/// Mark both the scheduled message and the regular message as sent
+/// Mark both the scheduled message and the regular message as sent, and update thread metadata
///
-/// This function handles both database updates in a single transaction
+/// This function handles all database updates in a single transaction
#[expect(
clippy::useless_asref,
reason = "We actually need the as_mut so we don't transfer ownership of the transaction"
)]
-#[tracing::instrument(skip(tx), level = "info")]
-async fn mark_messages_as_sent(
+#[tracing::instrument(
+ skip(tx, message),
+ fields(
+ message_db_id = message.db_id.unwrap().to_string(),
+ link_id = message.link_id.to_string()
+ ),
+ err
+)]
+async fn process_sent_message(
tx: &mut sqlx::PgConnection,
message: &MessageToSend,
) -> anyhow::Result<()> {
@@ -177,11 +237,7 @@ async fn mark_messages_as_sent(
message.link_id,
message.db_id.unwrap(),
)
- .await
- .context(format!(
- "Failed to update scheduled message as sent for message_id {}",
- message.db_id.unwrap()
- ))?;
+ .await?;
// mark message as non-draft
email_db_client::messages::update::mark_message_as_sent(
@@ -191,26 +247,27 @@ async fn mark_messages_as_sent(
message.link_id,
message.db_id.unwrap(),
)
- .await
- .context(format!(
- "Failed to update message as sent for message_id {}",
- message.db_id.unwrap()
- ))?;
+ .await?;
+
+ // safe as it was fetched from the database - message is only inserted once thread is created
+ let thread_db_id = message.thread_db_id.unwrap();
// set provider id of thread - needed in case it's a thread with no other messages, as it wouldn't
// have a provider id yet
email_db_client::threads::update::update_thread_provider_id(
tx.as_mut(),
- message.thread_db_id.unwrap(),
+ thread_db_id,
message.link_id,
&message.provider_thread_id.clone().unwrap(),
)
- .await
- .context(format!(
- "Failed to update provider id to {} for thread {}",
- message.provider_thread_id.clone().unwrap(),
- message.thread_db_id.unwrap()
- ))?;
+ .await?;
+
+ email_db_client::threads::update::update_thread_metadata(
+ tx.as_mut(),
+ thread_db_id,
+ message.link_id,
+ )
+ .await?;
Ok(())
}
diff --git a/rust/cloud-storage/justfile b/rust/cloud-storage/justfile
index 62dd90a769..5e3ee7b1a6 100644
--- a/rust/cloud-storage/justfile
+++ b/rust/cloud-storage/justfile
@@ -72,6 +72,7 @@ setup_test_envs:
echo "DATABASE_URL={{ MACRODB }}" >> ./properties/.env
echo "DATABASE_URL={{ MACRODB }}" >> ./name_search/.env
echo "DATABASE_URL={{ MACRODB }}" >> ./email_contact_search/.env
+ echo "DATABASE_URL={{ MACRODB }}" >> ./email_scheduled_handler/.env
setup_macrodb:
just macro_db_client/create_db
diff --git a/rust/cloud-storage/macro_db_client/migrations/20260119190319_email_scheduled_processing.sql b/rust/cloud-storage/macro_db_client/migrations/20260119190319_email_scheduled_processing.sql
new file mode 100644
index 0000000000..20caf591a7
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/migrations/20260119190319_email_scheduled_processing.sql
@@ -0,0 +1,2 @@
+ALTER TABLE email_scheduled_messages
+ ADD COLUMN processing BOOLEAN NOT NULL DEFAULT false;
\ No newline at end of file
diff --git a/rust/cloud-storage/models_email/src/email/db/message.rs b/rust/cloud-storage/models_email/src/email/db/message.rs
index fb6d40d02d..df2f46fb18 100644
--- a/rust/cloud-storage/models_email/src/email/db/message.rs
+++ b/rust/cloud-storage/models_email/src/email/db/message.rs
@@ -62,12 +62,19 @@ pub struct MessageToSend {
pub headers_json: Option<JsonValue>,
}
+/// Represents a scheduled message that will be sent to the provider at a later time.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScheduledMessage {
+ /// the id of the link that the message is associated with.
pub link_id: Uuid,
+ /// the id of the message in our database.
pub message_id: Uuid,
+ /// the time the message is scheduled to be sent.
pub send_time: DateTime<Utc>,
+ /// whether the message has been sent to the provider yet.
pub sent: bool,
+ /// whether the message is currently being processed by the background job.
+ pub processing: bool,
}
impl From<service::message::ScheduledMessage> for ScheduledMessage {
@@ -77,6 +84,7 @@ impl From<service::message::ScheduledMessage> for ScheduledMessage {
message_id: other.message_id,
send_time: other.send_time,
sent: other.sent,
+ processing: other.processing,
}
}
}
diff --git a/rust/cloud-storage/models_email/src/email/service/message.rs b/rust/cloud-storage/models_email/src/email/service/message.rs
index e939a970ce..c6c5826eab 100644
--- a/rust/cloud-storage/models_email/src/email/service/message.rs
+++ b/rust/cloud-storage/models_email/src/email/service/message.rs
@@ -283,12 +283,19 @@ pub struct MessageToSend {
pub send_time: Option<DateTime<Utc>>,
}
+/// Represents a scheduled message that will be sent to the provider at a later time.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScheduledMessage {
+ /// the id of the link that the message is associated with.
pub link_id: Uuid,
+ /// the id of the message in our database.
pub message_id: Uuid,
+ /// the time the message is scheduled to be sent.
pub send_time: DateTime<Utc>,
+ /// whether the message has been sent to the provider yet.
pub sent: bool,
+ /// whether the message is currently being processed by the background job.
+ pub processing: bool,
}
impl From<db::message::ScheduledMessage> for ScheduledMessage {
@@ -298,6 +305,7 @@ impl From<db::message::ScheduledMessage> for ScheduledMessage {
message_id: other.message_id,
send_time: other.send_time,
sent: other.sent,
+ processing: other.processing,
}
}
}
diff --git a/rust/cloud-storage/sqs_client/src/email.rs b/rust/cloud-storage/sqs_client/src/email.rs
index ff0e44b601..4e17090dfc 100644
--- a/rust/cloud-storage/sqs_client/src/email.rs
+++ b/rust/cloud-storage/sqs_client/src/email.rs
@@ -63,9 +63,16 @@ impl SQS {
pub async fn enqueue_email_scheduled_message(
&self,
message: ScheduledPubsubMessage,
+ delay_seconds: Option<i32>,
) -> anyhow::Result<()> {
if let Some(email_scheduled_queue) = &self.email_scheduled_queue {
- return enqueue_scheduled_message(&self.inner, email_scheduled_queue, message).await;
+ return enqueue_scheduled_message(
+ &self.inner,
+ email_scheduled_queue,
+ message,
+ delay_seconds,
+ )
+ .await;
}
Err(anyhow::anyhow!("email_scheduled_queue is not configured"))
}
@@ -140,19 +147,20 @@ pub async fn enqueue_scheduled_message(
sqs_client: &aws_sdk_sqs::Client,
queue_url: &str,
message: ScheduledPubsubMessage,
+ delay_seconds: Option<i32>,
) -> anyhow::Result<()> {
let message_str = serde_json::to_string(&message)?;
- let message_db_id = message.message_id.to_string();
- // Send the message with the serialized body
- sqs_client
+ let mut request = sqs_client
.send_message()
.queue_url(queue_url)
- .message_body(message_str)
- .message_group_id(message_db_id.clone())
- .message_deduplication_id(message_db_id)
- .send()
- .await?;
+ .message_body(message_str);
+
+ if let Some(delay) = delay_seconds {
+ request = request.delay_seconds(delay);
+ }
+
+ request.send().await?;
Ok(())
}
diff --git a/rust/cloud-storage/target/lambda/email_scheduled_handler/bootstrap.zip b/rust/cloud-storage/target/lambda/email_scheduled_handler/bootstrap.zip
index 103b6d9219..060eb09729 100644
Binary files a/rust/cloud-storage/target/lambda/email_scheduled_handler/bootstrap.zip and b/rust/cloud-storage/target/lambda/email_scheduled_handler/bootstrap.zip differ