2026-11-15 11:49:29 +00:00
|
|
|
//! Hourly removal of data that is no longer needed.
|
|
|
|
|
|
|
|
|
|
use std::time::Duration;
|
|
|
|
|
|
|
|
|
|
use sqlx::PgPool;
|
|
|
|
|
use tokio::sync::watch;
|
|
|
|
|
|
|
|
|
|
const INTERVAL: Duration = Duration::from_secs(3600);
|
|
|
|
|
|
|
|
|
|
/// (what, statement) pairs; each returns the number of deleted rows.
|
2026-11-17 14:41:12 +00:00
|
|
|
const STATEMENTS: [(&str, &str); 5] = [
|
2026-11-15 11:49:29 +00:00
|
|
|
("sessions", "DELETE FROM sessions WHERE expires_at < now()"),
|
|
|
|
|
("auth_tokens", "DELETE FROM auth_tokens WHERE expires_at < now()"),
|
|
|
|
|
// Sent e-mails contain links with tokens; keep them a week for support.
|
|
|
|
|
(
|
|
|
|
|
"emails",
|
|
|
|
|
"DELETE FROM email_outbox WHERE sent_at < now() - interval '7 days' \
|
|
|
|
|
OR failed_at < now() - interval '30 days'",
|
|
|
|
|
),
|
|
|
|
|
("invites", "DELETE FROM synastry_invites WHERE accepted_at IS NULL AND expires_at < now() - interval '30 days'"),
|
2026-11-17 14:41:12 +00:00
|
|
|
("prompt_previews", "DELETE FROM prompt_previews WHERE created_at < now() - interval '30 days'"),
|
2026-11-15 11:49:29 +00:00
|
|
|
];
|
|
|
|
|
|
|
|
|
|
pub async fn run_once(db: &PgPool) -> Result<Vec<(&'static str, u64)>, sqlx::Error> {
|
|
|
|
|
let mut deleted = Vec::new();
|
|
|
|
|
for (what, sql) in STATEMENTS {
|
|
|
|
|
deleted.push((what, sqlx::query(sql).execute(db).await?.rows_affected()));
|
|
|
|
|
}
|
|
|
|
|
Ok(deleted)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub async fn run(db: PgPool, stop: watch::Receiver<bool>) {
|
|
|
|
|
loop {
|
|
|
|
|
match run_once(&db).await {
|
|
|
|
|
Ok(deleted) => {
|
|
|
|
|
let total: u64 = deleted.iter().map(|(_, n)| n).sum();
|
|
|
|
|
if total > 0 {
|
|
|
|
|
tracing::info!(?deleted, "cleanup");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
Err(e) => tracing::error!(error = %e, "cleanup"),
|
|
|
|
|
}
|
|
|
|
|
tokio::select! {
|
|
|
|
|
() = tokio::time::sleep(INTERVAL) => {}
|
|
|
|
|
() = crate::stopped(stop.clone()) => break,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|