use chrono::{Days, Utc};
use diesel::{debug_query, pg::Pg, BoolExpressionMethods, ExpressionMethods, QueryDsl};
use diesel_async::RunQueryDsl;
use log::debug;
use std::sync::Arc;
use super::connection::Pool;
use crate::schema::{layers, maps};
const CLEANUP_INTERVAL: u64 = 60 * 60 * 24;
pub async fn cleanup_maps(pool: Arc<Pool>) -> ! {
loop {
tokio::time::sleep(std::time::Duration::from_secs(CLEANUP_INTERVAL)).await;
log::info!("Running maps cleanup...");
let Some(one_month_ago) = Utc::now().date_naive().checked_sub_days(Days::new(30)) else {
log::error!("Failed to calculate date one month ago");
continue;
};
let query = diesel::delete(
maps::table.filter(
maps::deletion_date
.is_not_null()
.and(maps::deletion_date.lt(one_month_ago)),
),
);
debug!("{}", debug_query::<Pg, _>(&query));
match pool.get().await {
Ok(mut conn) => match query.execute(&mut conn).await {
Ok(delete_rows) => log::info!("Removed {delete_rows} maps"),
Err(e) => log::error!("Failed to execute query: {}", e),
},
Err(e) => {
log::error!("Failed to get connection from pool: {}", e);
}
}
}
}
pub async fn cleanup_layers(pool: Arc<Pool>) -> ! {
loop {
tokio::time::sleep(std::time::Duration::from_secs(CLEANUP_INTERVAL)).await;
log::info!("Running layers cleanup...");
let one_day_ago = Utc::now().naive_utc() - chrono::Duration::days(1);
let query = diesel::delete(
layers::table.filter(
layers::marked_deleted
.is_not_null()
.and(layers::marked_deleted.lt(one_day_ago)),
),
);
debug!("{}", debug_query::<Pg, _>(&query));
match pool.get().await {
Ok(mut conn) => match query.execute(&mut conn).await {
Ok(delete_rows) => log::info!("Removed {delete_rows} layers"),
Err(e) => log::error!("Failed to execute query: {}", e),
},
Err(e) => {
log::error!("Failed to get connection from pool: {}", e);
}
}
}
}