|
| 1 | +use crate::domain::SubscriberEmail; |
| 2 | +use crate::email_client::EmailClient; |
| 3 | +use crate::{configuration::Settings, startup::get_connection_pool}; |
| 4 | +use sqlx::{PgPool, Postgres, Transaction}; |
| 5 | +use std::time::Duration; |
| 6 | +use tracing::{field::display, Span}; |
| 7 | +use uuid::Uuid; |
| 8 | + |
| 9 | +pub enum ExecutionOutcome { |
| 10 | + TaskCompleted, |
| 11 | + EmptyQueue, |
| 12 | +} |
| 13 | + |
| 14 | +#[tracing::instrument( |
| 15 | + skip_all, |
| 16 | + fields( |
| 17 | + newsletter_issue_id = tracing::field::Empty, |
| 18 | + subscriber_email = tracing::field::Empty, |
| 19 | + ), |
| 20 | + err |
| 21 | +)] |
| 22 | +pub async fn try_execute_task( |
| 23 | + pool: &PgPool, |
| 24 | + email_client: &EmailClient, |
| 25 | +) -> Result<ExecutionOutcome, anyhow::Error> { |
| 26 | + let task = dequeue_task(pool).await?; |
| 27 | + if task.is_none() { |
| 28 | + return Ok(ExecutionOutcome::EmptyQueue); |
| 29 | + } |
| 30 | + |
| 31 | + let (transaction, issue_id, email) = task.unwrap(); |
| 32 | + Span::current() |
| 33 | + .record("newsletter_issue_id", &display(issue_id)) |
| 34 | + .record("subscriber_email", &display(&email)); |
| 35 | + |
| 36 | + match SubscriberEmail::parse(email.clone()) { |
| 37 | + Ok(email) => { |
| 38 | + let issue = get_issue(pool, issue_id).await?; |
| 39 | + if let Err(e) = email_client |
| 40 | + .send_email( |
| 41 | + &email, |
| 42 | + &issue.title, |
| 43 | + &issue.html_content, |
| 44 | + &issue.text_content, |
| 45 | + ) |
| 46 | + .await |
| 47 | + { |
| 48 | + tracing::error!( |
| 49 | + error.cause_chain = ?e, |
| 50 | + error.message = %e, |
| 51 | + "Failed to deliver issue to a confirmed subscriber. \ |
| 52 | + Skipping.", |
| 53 | + ); |
| 54 | + } |
| 55 | + } |
| 56 | + Err(e) => { |
| 57 | + tracing::error!( |
| 58 | + error.cause_chain = ?e, |
| 59 | + error.message = %e, |
| 60 | + "Skipping a confirmed subscriber. \ |
| 61 | + Their stored contact details are invalid", |
| 62 | + ); |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + delete_task(transaction, issue_id, &email).await?; |
| 67 | + Ok(ExecutionOutcome::TaskCompleted) |
| 68 | +} |
| 69 | + |
| 70 | +type PgTransaction = Transaction<'static, Postgres>; |
| 71 | + |
| 72 | +#[tracing::instrument(skip_all)] |
| 73 | +async fn dequeue_task( |
| 74 | + pool: &PgPool, |
| 75 | +) -> Result<Option<(PgTransaction, Uuid, String)>, anyhow::Error> { |
| 76 | + let mut transaction = pool.begin().await?; |
| 77 | + let r = sqlx::query!( |
| 78 | + r#" |
| 79 | + SELECT newsletter_issue_id, subscriber_email |
| 80 | + FROM issue_delivery_queue |
| 81 | + FOR UPDATE |
| 82 | + SKIP LOCKED |
| 83 | + LIMIT 1 |
| 84 | + "#, |
| 85 | + ) |
| 86 | + .fetch_optional(&mut transaction) |
| 87 | + .await?; |
| 88 | + if let Some(r) = r { |
| 89 | + Ok(Some(( |
| 90 | + transaction, |
| 91 | + r.newsletter_issue_id, |
| 92 | + r.subscriber_email, |
| 93 | + ))) |
| 94 | + } else { |
| 95 | + Ok(None) |
| 96 | + } |
| 97 | +} |
| 98 | + |
| 99 | +#[tracing::instrument(skip_all)] |
| 100 | +async fn delete_task( |
| 101 | + mut transaction: PgTransaction, |
| 102 | + issue_id: Uuid, |
| 103 | + email: &str, |
| 104 | +) -> Result<(), anyhow::Error> { |
| 105 | + sqlx::query!( |
| 106 | + r#" |
| 107 | + DELETE FROM issue_delivery_queue |
| 108 | + WHERE |
| 109 | + newsletter_issue_id = $1 AND |
| 110 | + subscriber_email = $2 |
| 111 | + "#, |
| 112 | + issue_id, |
| 113 | + email |
| 114 | + ) |
| 115 | + .execute(&mut transaction) |
| 116 | + .await?; |
| 117 | + transaction.commit().await?; |
| 118 | + Ok(()) |
| 119 | +} |
| 120 | + |
| 121 | +struct NewsletterIssue { |
| 122 | + title: String, |
| 123 | + text_content: String, |
| 124 | + html_content: String, |
| 125 | +} |
| 126 | + |
| 127 | +#[tracing::instrument(skip_all)] |
| 128 | +async fn get_issue(pool: &PgPool, issue_id: Uuid) -> Result<NewsletterIssue, anyhow::Error> { |
| 129 | + let issue = sqlx::query_as!( |
| 130 | + NewsletterIssue, |
| 131 | + r#" |
| 132 | + SELECT title, text_content, html_content |
| 133 | + FROM newsletter_issues |
| 134 | + WHERE |
| 135 | + newsletter_issue_id = $1 |
| 136 | + "#, |
| 137 | + issue_id |
| 138 | + ) |
| 139 | + .fetch_one(pool) |
| 140 | + .await?; |
| 141 | + Ok(issue) |
| 142 | +} |
| 143 | + |
| 144 | +async fn worker_loop(pool: PgPool, email_client: EmailClient) -> Result<(), anyhow::Error> { |
| 145 | + loop { |
| 146 | + match try_execute_task(&pool, &email_client).await { |
| 147 | + Ok(ExecutionOutcome::EmptyQueue) => { |
| 148 | + tokio::time::sleep(Duration::from_secs(10)).await; |
| 149 | + } |
| 150 | + Err(_) => { |
| 151 | + tokio::time::sleep(Duration::from_secs(1)).await; |
| 152 | + } |
| 153 | + Ok(ExecutionOutcome::TaskCompleted) => {} |
| 154 | + } |
| 155 | + } |
| 156 | +} |
| 157 | + |
| 158 | +pub async fn run_worker_until_stopped(configuration: Settings) -> Result<(), anyhow::Error> { |
| 159 | + let connection_pool = get_connection_pool(&configuration.database); |
| 160 | + let email_client = configuration.email_client.client(); |
| 161 | + worker_loop(connection_pool, email_client).await |
| 162 | +} |
0 commit comments