gitea_pages/backend/src/worker/mod.rs

90 lines
2.2 KiB
Rust

use anyhow::Result;
use async_once::AsyncOnce;
use async_trait::async_trait;
use celery::beat::{Beat, DeltaSchedule, LocalSchedulerBackend};
use celery::prelude::*;
use celery::Celery;
use lazy_static::lazy_static;
use std::sync::Arc;
use std::time::Duration;
use stdext::duration::DurationExt;
pub mod delete_repo;
pub mod get_repo;
pub mod update_repos;
use crate::CONFIG;
pub const QUEUE_NAME: &str = "gitea_pages";
pub async fn app() -> Result<Arc<Celery>, CeleryError> {
celery::app!(
broker = AMQPBroker { &CONFIG.amqp_url },
tasks = [
get_repo::get_repo,
delete_repo::delete_repo,
update_repos::update_repos,
],
task_routes = [
"*" => QUEUE_NAME,
],
prefetch_count = 2,
heartbeat = Some(10)
)
.await
}
pub async fn beat() -> Result<Beat<LocalSchedulerBackend>, BeatError> {
celery::beat!(
broker = AMQPBroker { &CONFIG.amqp_url },
tasks = [
// "cleanup_tokens" => {
// cleanup_tokens::cleanup_tokens,
// schedule = DeltaSchedule::new(Duration::from_hours(1)),
// args = (),
// }
"update_repos" => {
update_repos::update_repos,
schedule = DeltaSchedule::new(Duration::from_days(1)),
args = (),
},
],
task_routes = [
"*" => QUEUE_NAME,
]
)
.await
}
pub type Connection = Arc<Celery>;
pub struct ConnectionManager;
#[async_trait]
impl bb8::ManageConnection for ConnectionManager {
type Connection = Connection;
type Error = CeleryError;
async fn connect(&self) -> Result<Self::Connection, Self::Error> {
app().await
}
async fn is_valid(&self, _conn: &mut Self::Connection) -> Result<(), Self::Error> {
Ok(())
}
fn has_broken(&self, _: &mut Self::Connection) -> bool {
false
}
}
pub type Pool = bb8::Pool<ConnectionManager>;
pub async fn pool() -> Result<Pool> {
Ok(bb8::Pool::builder().build(ConnectionManager).await?)
}
lazy_static! {
pub static ref POOL: AsyncOnce<Pool> = AsyncOnce::new(async { pool().await.unwrap() });
}