Add a timer to revoke all expired tokens( Fix #279

This commit is contained in:
2022-09-29 01:30:03 +00:00
committed by GitHub
parent 677cc576cf
commit fcff540220
8 changed files with 80 additions and 5 deletions

View File

@@ -5,7 +5,7 @@ pub mod user;
pub use pubkey::{AuthPubkeyContext, AuthPubkeyRoute, RSAKey};
pub use status::{AuthStatusContext, AuthStatusRoute};
pub use token::{AuthTokenContext, AuthTokenRoute};
pub use token::{revoke_expired_tokens, AuthTokenContext, AuthTokenRoute};
pub use user::{AuthUserContext, AuthUserRoute};
const PASSWORD_SALT: [u8; 64] = [

View File

@@ -194,3 +194,8 @@ impl MatchRoute<Body, Body> for AuthTokenRoute {
}
}
}
pub async fn revoke_expired_tokens(ctx: Arc<ServerContext>) -> Result<(), PixivDownloaderError> {
ctx.db.revoke_expired_tokens().await?;
Ok(())
}

View File

@@ -13,6 +13,8 @@ pub mod result;
pub mod route;
/// Services
pub mod service;
/// Tasks invoked by timer
pub mod timer;
/// Traits
pub mod traits;
#[cfg(all(test, feature = "db_sqlite"))]

View File

@@ -64,9 +64,9 @@ pub struct PixivDownloaderMakeSvc {
}
impl PixivDownloaderMakeSvc {
pub async fn new() -> Self {
pub fn new(ctx: &Arc<ServerContext>) -> Self {
Self {
context: Arc::new(ServerContext::default().await),
context: Arc::clone(ctx),
routes: Arc::new(ServerRoutes::new()),
}
}
@@ -93,5 +93,8 @@ impl<T> Service<T> for PixivDownloaderMakeSvc {
pub async fn start_server(
addr: &SocketAddr,
) -> Result<Server<AddrIncoming, PixivDownloaderMakeSvc>, hyper::Error> {
Ok(Server::try_bind(addr)?.serve(PixivDownloaderMakeSvc::new().await))
let ctx = Arc::new(ServerContext::default().await);
let ser = Server::try_bind(addr)?.serve(PixivDownloaderMakeSvc::new(&ctx));
tokio::spawn(super::timer::start_timer(ctx));
Ok(ser)
}

23
src/server/timer.rs Normal file
View File

@@ -0,0 +1,23 @@
use super::auth::*;
use super::context::ServerContext;
use crate::task_manager::{MaxCount, TaskManager};
use std::sync::Arc;
use tokio::time::{interval_at, Duration, Instant};
pub async fn start_timer(ctx: Arc<ServerContext>) {
let mut interval = interval_at(Instant::now(), Duration::from_secs(60));
let task_count = Arc::new(futures_util::lock::Mutex::new(0usize));
let max_count = MaxCount::new(8);
let tasks = TaskManager::new(task_count, max_count);
loop {
interval.tick().await;
tasks.add_task(revoke_expired_tokens(ctx.clone())).await;
tasks.join().await;
for task in tasks.take_finished_tasks() {
let re = task.await;
if let Ok(Err(e)) = re {
println!("Timer task error: {}", e);
}
}
}
}