|
| 1 | +use std::str::FromStr; |
| 2 | + |
| 3 | +use apalis::{ |
| 4 | + layers::{WorkerBuilderExt, prometheus::PrometheusLayer}, |
| 5 | + prelude::{Data, WorkerBuilder}, |
| 6 | +}; |
| 7 | +use apalis_cron::{CronStream, Tick}; |
| 8 | +use cron::Schedule; |
| 9 | +use tokio::signal::ctrl_c; |
| 10 | + |
| 11 | +use diesel::Connection; |
| 12 | + |
| 13 | +use crate::db::connection::DbPool; |
| 14 | +use crate::models::session::Session; |
| 15 | + |
| 16 | +fn cleanup_expired_sessions(pool: &DbPool) -> Result<(), diesel::result::Error> { |
| 17 | + let mut conn = pool.get().map_err(|e| { |
| 18 | + tracing::error!(error = ?e, "Failed to get connection for session cleanup"); |
| 19 | + diesel::result::Error::DatabaseError( |
| 20 | + diesel::result::DatabaseErrorKind::Unknown, |
| 21 | + Box::new(e.to_string()), |
| 22 | + ) |
| 23 | + })?; |
| 24 | + |
| 25 | + conn.transaction(|conn| { |
| 26 | + let deleted = Session::delete_expired(conn)?; |
| 27 | + |
| 28 | + tracing::debug!(deleted, "Cleaned up old leaderboard entries"); |
| 29 | + |
| 30 | + Ok(()) |
| 31 | + }) |
| 32 | +} |
| 33 | + |
| 34 | +async fn run_cleanup(_tick: Tick, pool: Data<DbPool>) { |
| 35 | + if let Err(e) = cleanup_expired_sessions(&pool) { |
| 36 | + tracing::error!(error = ?e, "Failed to cleanup old leaderboard entries"); |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +pub async fn setup(diesel_pool: DbPool) -> impl std::future::Future<Output = ()> { |
| 41 | + let cleanup_schedule = |
| 42 | + Schedule::from_str("0 0 0 * * *").expect("valid cron: daily at midnight"); |
| 43 | + |
| 44 | + let cleanup_pool = diesel_pool; |
| 45 | + |
| 46 | + let cleanup_worker = WorkerBuilder::new("sessions-cleanup") |
| 47 | + .backend(CronStream::new(cleanup_schedule)) |
| 48 | + .enable_tracing() |
| 49 | + .layer(PrometheusLayer::default()) |
| 50 | + .catch_panic() |
| 51 | + .data(cleanup_pool) |
| 52 | + .build(run_cleanup); |
| 53 | + |
| 54 | + async move { |
| 55 | + tokio::select! { |
| 56 | + _ = cleanup_worker.run() => {} |
| 57 | + _ = ctrl_c() => { |
| 58 | + tracing::info!("Shutting down session workers"); |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | +} |
0 commit comments