Skip to main content

rustio_admin/
background.rs

1//! Background tasks. A tiny runner that spawns one tokio task per
2//! recurring job. Kept simple on purpose — we don't ship a cron DSL,
3//! just "run this every N seconds".
4
5use std::time::Duration;
6
7use tokio::time::{interval, MissedTickBehavior};
8
9use crate::auth::purge_expired_sessions;
10use crate::orm::Db;
11
12/// Spin up the standard housekeeping tasks. Call this once during
13/// app startup. Returns immediately — the tasks run forever.
14pub fn spawn_housekeeping(db: Db) {
15    spawn_session_sweeper(db.clone());
16}
17
18/// Delete expired sessions every 10 minutes.
19pub fn spawn_session_sweeper(db: Db) {
20    log::info!("background session sweeper spawned (10 min interval)");
21    tokio::spawn(async move {
22        let mut tick = interval(Duration::from_secs(600));
23        tick.set_missed_tick_behavior(MissedTickBehavior::Delay);
24        // Skip the first tick (it fires immediately) — no need to
25        // sweep the second the server boots.
26        tick.tick().await;
27        loop {
28            tick.tick().await;
29            match purge_expired_sessions(&db).await {
30                Ok(0) => {}
31                Ok(n) => log::info!("swept {n} expired sessions"),
32                Err(e) => log::warn!("session sweep failed: {e}"),
33            }
34        }
35    });
36}