Skip to content

Commit 1bfecb7

Browse files
committed
Emails, review fixes: each email is claimed just before it's sent (a claim lapses after 30 minutes, far longer than a 10-second send), so a slow run's batch is never sent twice; a crashed run's fifth attempt ends failed, never a sixth; a failed send waits five minutes for the next run; the membership notice's dedupe key is the change's time, fixed at dispatch, so a retried listener doesn't send it again
1 parent dfc0ed4 commit 1bfecb7

5 files changed

Lines changed: 79 additions & 19 deletions

File tree

‎app/src/auth/memberships.rs‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,16 @@ pub struct MembershipChanged {
2121
pub organization_id: i64,
2222
pub user_id: i64,
2323
pub role: Option<Role>,
24+
/// When the membership changed (milliseconds), fixed at dispatch: the notice's dedupe key, so a retried listener
25+
/// doesn't send it twice.
26+
pub changed_at: i64,
27+
}
28+
29+
impl MembershipChanged {
30+
#[must_use]
31+
pub fn now(organization_id: i64, user_id: i64, role: Option<Role>) -> Self {
32+
Self { organization_id, user_id, role, changed_at: laravel::now().timestamp().as_millisecond() }
33+
}
2434
}
2535

2636
#[derive(Debug)]
@@ -151,7 +161,7 @@ pub async fn apply(
151161
})
152162
.await?;
153163
for (org, role) in &notices {
154-
MembershipChanged { organization_id: *org, user_id, role: *role }.dispatch().await?;
164+
MembershipChanged::now(*org, user_id, *role).dispatch().await?;
155165
}
156166
Ok(notices.len())
157167
}

‎app/src/notify/mod.rs‎

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -24,13 +24,7 @@ pub async fn membership_changed(event: Event<MembershipChanged>) -> laravel::Res
2424
Some(role) => Kind::AddedToOrg { role: role.as_str().to_string() },
2525
None => Kind::RemovedFromOrg,
2626
};
27-
let key = format!(
28-
"{}:{}:{}:{}",
29-
kind.name(),
30-
event.organization_id,
31-
event.user_id,
32-
laravel::now().timestamp().as_millisecond()
33-
);
27+
let key = format!("{}:{}:{}:{}", kind.name(), event.organization_id, event.user_id, event.changed_at);
3428
queue(&kind, To::User(event.user_id), Some(event.organization_id), &key).await?;
3529
Ok(())
3630
}

‎app/src/notify/outbox.rs‎

Lines changed: 34 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -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)]
104104
pub 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.
149154
pub 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?;

‎app/src/notify/postmark.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ pub async fn send(
3838
let response = client::post("https://api.postmarkapp.com/email")
3939
.header("X-Postmark-Server-Token", token)
4040
.accept_json()
41+
.timeout(std::time::Duration::from_secs(10))
4142
.json(&body)
4243
.await?;
4344
if !response.successful() {

‎app/tests/emails.rs‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,3 +83,35 @@ async fn a_failed_send_stays_pending_for_the_next_run(_app: Application) -> lara
8383
assert_eq!(outbox::failed_unresolved_count().await?, 0, "pending, not failed, after one attempt");
8484
Ok(())
8585
}
86+
87+
#[laravel::test(app = postmark)]
88+
async fn claims_are_per_email_and_attempts_end_at_five(_app: Application) -> laravel::Result<()> {
89+
let postmark = client::fake().with("api.postmarkapp.com/*", json!({ "MessageID": "x" }));
90+
// A run that crashed during its fifth attempt, half an hour ago: failed, not sent a sixth time.
91+
db::query!(
92+
"INSERT INTO emails (kind, dedupe_key, recipient, data, attempts, claimed_at) \
93+
VALUES ('removed_from_org', 'crashed', 'ada@example.com', '\"RemovedFromOrg\"', 5, now() - interval '31 minutes')"
94+
)
95+
.insert()
96+
.await?;
97+
// Another run is sending this one right now: left alone.
98+
db::query!(
99+
"INSERT INTO emails (kind, dedupe_key, recipient, data, attempts, claimed_at) \
100+
VALUES ('removed_from_org', 'in-flight', 'bea@example.com', '\"RemovedFromOrg\"', 1, now() - interval '6 minutes')"
101+
)
102+
.insert()
103+
.await?;
104+
let config = app::notify::postmark::Postmark {
105+
token: Some("test-token".into()),
106+
from: "VisualCI <support@visualci.com>".into(),
107+
reply_to: "support@visualci.com".into(),
108+
};
109+
assert_eq!(outbox::deliver(&config, "https://app.visualci.com").await?, 0);
110+
postmark.assert_nothing_sent();
111+
let state = |key: &'static str| async move {
112+
db::query!("SELECT state FROM emails WHERE dedupe_key = {key}").scalar::<String>().await
113+
};
114+
assert_eq!(state("crashed").await?.as_deref(), Some("failed"));
115+
assert_eq!(state("in-flight").await?.as_deref(), Some("pending"));
116+
Ok(())
117+
}

0 commit comments

Comments
 (0)