Skip to content

Commit 150ce45

Browse files
committed
Emails: the delivery job pushes a heartbeat that checks the work (VISUALCI_EMAILS_HEARTBEAT_URL/TOKEN; fails when the oldest unsent email has waited over 30 minutes or delivery errored), and failed_unresolved_count for /status (emails_failed_unresolved, as today)
1 parent 775644b commit 150ce45

5 files changed

Lines changed: 53 additions & 2 deletions

File tree

‎.gitignore‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
/target
1+
target/
22
**/node_modules
33
/tmp
44
.env

‎app/src/heartbeat.rs‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
//! Scheduled work pushes its result to a Gatus external endpoint when one is configured (`<PREFIX>_URL` and
2+
//! `<PREFIX>_TOKEN`, such as `VISUALCI_EMAILS_HEARTBEAT_URL`), so a run that failed, or no run at all, alerts. Ported
3+
//! from today's server.
4+
5+
use laravel::http::client;
6+
7+
/// Push a run's result. A failed push only logs: Gatus alerts on the missing heartbeat instead.
8+
pub async fn push(prefix: &str, result: Result<(), String>) {
9+
let Ok(url) = std::env::var(format!("{prefix}_URL")) else { return };
10+
if url.is_empty() {
11+
return;
12+
}
13+
let token = std::env::var(format!("{prefix}_TOKEN")).unwrap_or_default();
14+
let (success, error) = match result {
15+
Ok(()) => ("true", String::new()),
16+
Err(e) => ("false", e),
17+
};
18+
let sent = client::post(url).token(token).query([("success", success), ("error", error.as_str())]).await;
19+
match sent {
20+
Ok(response) if response.successful() => {}
21+
Ok(response) => tracing::warn!(prefix, status = %response.status(), "heartbeat refused"),
22+
Err(e) => tracing::warn!(prefix, error = %e, "heartbeat failed"),
23+
}
24+
}

‎app/src/lib.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
pub mod auth;
44
pub mod billing;
55
pub mod forge;
6+
pub mod heartbeat;
67
pub mod http;
78
pub mod listeners;
89
pub mod models;

‎app/src/notify/outbox.rs‎

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -110,11 +110,25 @@ impl DeliverEmails {
110110
postmark: laravel::config::Section<Postmark>,
111111
app: laravel::config::Section<AppUrl>,
112112
) -> laravel::Result<()> {
113-
deliver(&postmark, &app.url).await?;
113+
let delivered = deliver(&postmark, &app.url).await;
114+
// The heartbeat checks the work, not just the run: an email waiting more than half an hour fails it
115+
let health = match &delivered {
116+
Err(e) => Err(e.to_string()),
117+
Ok(_) => match oldest_unsent_seconds().await {
118+
Ok(waited) if waited > STALE_SECONDS => Err(format!("the oldest unsent email has waited {waited}s")),
119+
Ok(_) => Ok(()),
120+
Err(e) => Err(e.to_string()),
121+
},
122+
};
123+
crate::heartbeat::push("VISUALCI_EMAILS_HEARTBEAT", health).await;
124+
delivered?;
114125
Ok(())
115126
}
116127
}
117128

129+
/// How long an email may wait unsent before the heartbeat fails.
130+
pub const STALE_SECONDS: i64 = 30 * 60;
131+
118132
/// The web app's URL, for the links in emails.
119133
#[derive(Clone, laravel::config::Section)]
120134
pub struct AppUrl {
@@ -211,3 +225,14 @@ pub async fn oldest_unsent_seconds() -> laravel::Result<i64> {
211225
.await?
212226
.unwrap_or(0))
213227
}
228+
229+
/// Failed emails nobody has retried or dismissed yet, for `/status` (`emails_failed_unresolved`).
230+
///
231+
/// # Errors
232+
/// On a database error.
233+
pub async fn failed_unresolved_count() -> laravel::Result<i64> {
234+
Ok(db::query!("SELECT count(*) FROM emails WHERE state = 'failed' AND dismissed_at IS NULL")
235+
.scalar::<i64>()
236+
.await?
237+
.unwrap_or(0))
238+
}

‎app/tests/emails.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,5 +80,6 @@ async fn a_failed_send_stays_pending_for_the_next_run(_app: Application) -> lara
8080
assert!(r.try_get::<String>("last_error")?.contains("down"));
8181
}
8282
assert!(outbox::oldest_unsent_seconds().await? >= 0);
83+
assert_eq!(outbox::failed_unresolved_count().await?, 0, "pending, not failed, after one attempt");
8384
Ok(())
8485
}

0 commit comments

Comments
 (0)