server-mark2-dev/src/websocket/tasks/watchdog.rs

50 lines
1.5 KiB
Rust
Raw Normal View History

use crate::{app::Hub, websocket::core::*};
use log::{debug, info, warn};
use std::{sync::Arc, time::Duration};
use tokio::{
sync::{Mutex, mpsc::Sender},
task::JoinHandle,
time::Instant,
};
pub async fn get_watchdog_task(
tx: Sender<TxControlMessage>,
watchdog_last_seen: Arc<Mutex<Instant>>,
user: Arc<Mutex<String>>,
hub: Arc<Mutex<Hub>>,
) -> JoinHandle<()> {
tokio::spawn(async move {
loop {
tokio::time::sleep(Duration::from_secs(5)).await;
{
let h = hub.try_lock().unwrap();
let curr_user = user.try_lock().unwrap().to_string();
info!("{}: checking invalid ...", curr_user);
if h.clients.contains_key(&curr_user) && curr_user.starts_with("temp") {
warn!("detect unauthorized -- {}", curr_user);
let _ = tx
.send(TxControlMessage::Payload(serde_json::json!({
"timeout": "watchdog"
})))
.await;
break;
}
}
let last = *watchdog_last_seen.lock().await;
if last.elapsed() > TIMEOUT {
warn!("Timeout close connection");
let _ = tx
.send(TxControlMessage::Payload(serde_json::json!({
"timeout": "watchdog"
})))
.await;
break;
}
}
})
}