@@ -98,8 +98,8 @@ pub async fn queue(kind: &Kind, to: To, org_id: Option<i64>, dedupe_key: &str) -
9898 Ok ( queued)
9999}
100100
101- /// Send pending emails, up to 50 a run. Each is claimed first , so two runs never send one twice; a failure leaves it
102- /// pending for the next run, and after five attempts it's marked failed. Without a Postmark token nothing is sent.
101+ /// Send pending emails, up to 50 a run. Each is claimed just before it's sent , so two runs never send one twice; a
102+ /// failure leaves it pending for the next run, and after five attempts it's marked failed. Without a Postmark token nothing is sent.
103103#[ derive( Queueable , Clone , Debug , serde:: Serialize , serde:: Deserialize ) ]
104104pub struct DeliverEmails ;
105105
@@ -142,23 +142,42 @@ fn schedule(schedule: &mut Schedule) {
142142 schedule. job ( DeliverEmails ) . every_five_minutes ( ) . without_overlapping ( ) ;
143143}
144144
145+ /// How long a claimed email waits before another run may take it: far longer than one send can take.
146+ pub const RECLAIM_MINUTES : i64 = 30 ;
147+ /// How long a failed send waits before it's tried again.
148+ pub const RETRY_MINUTES : i64 = 5 ;
149+
145150/// Send what's pending. Returns how many were sent.
146151///
147152/// # Errors
148153/// On a database error.
149154pub async fn deliver ( config : & Postmark , app_url : & str ) -> laravel:: Result < usize > {
150155 let Some ( token) = config. token . as_deref ( ) . filter ( |t| !t. is_empty ( ) ) else { return Ok ( 0 ) } ;
151- let rows = db :: query! (
152- "UPDATE emails SET claimed_at = now(), attempts = attempts + 1 WHERE id IN ( \
153- SELECT id FROM emails WHERE state = 'pending' \
154- AND ( claimed_at IS NULL OR claimed_at < now() - interval '5 minutes') \
155- ORDER BY id LIMIT 50 FOR UPDATE SKIP LOCKED ) \
156- RETURNING id, recipient, data, organization_id, attempts"
156+ // Anything a crashed run left claimed after its fifth attempt has had its tries.
157+ let window = RECLAIM_MINUTES ;
158+ db :: query! (
159+ "UPDATE emails SET state = 'failed', claimed_at = NULL, \
160+ last_error = COALESCE(last_error, 'no result after five attempts'), updated_at = now( ) \
161+ WHERE state = 'pending' AND attempts >= 5 AND claimed_at < now() - make_interval(mins => {window}::int) "
157162 )
158- . select ( )
163+ . update ( )
159164 . await ?;
160165 let mut sent = 0 ;
161- for r in rows {
166+ // One at a time, each claimed just before it's sent: a claim only lapses after RECLAIM_MINUTES, far longer than one
167+ // send can take, so a slow run's later emails are never taken by the next run while it's still sending.
168+ for _ in 0 ..50 {
169+ let Some ( r) = db:: query!(
170+ "UPDATE emails SET claimed_at = now(), attempts = attempts + 1 WHERE id = ( \
171+ SELECT id FROM emails WHERE state = 'pending' AND attempts < 5 \
172+ AND (claimed_at IS NULL OR claimed_at < now() - make_interval(mins => {window}::int)) \
173+ ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED) \
174+ RETURNING id, recipient, data, organization_id, attempts"
175+ )
176+ . select_one ( )
177+ . await ?
178+ else {
179+ break ;
180+ } ;
162181 let id: i64 = r. try_get ( "id" ) ?;
163182 let to: String = r. try_get ( "recipient" ) ?;
164183 let attempts: i32 = r. try_get ( "attempts" ) ?;
@@ -201,8 +220,12 @@ pub async fn deliver(config: &Postmark, app_url: &str) -> laravel::Result<usize>
201220 Err ( e) => {
202221 let state = if attempts >= 5 { "failed" } else { "pending" } ;
203222 let error = e. to_string ( ) ;
223+ // Its claim lapses in RETRY_MINUTES, so the next run tries again, never this one.
224+ let hold = RECLAIM_MINUTES - RETRY_MINUTES ;
204225 db:: query!(
205- "UPDATE emails SET state = {state}, claimed_at = NULL, last_error = {error}, updated_at = now() WHERE id = {id}"
226+ "UPDATE emails SET state = {state}, last_error = {error}, updated_at = now(), \
227+ claimed_at = CASE WHEN {state} = 'failed' THEN NULL \
228+ ELSE now() - make_interval(mins => {hold}::int) END WHERE id = {id}"
206229 )
207230 . update ( )
208231 . await ?;
0 commit comments