use std::time::Instant; use tokio::sync::{Mutex, MutexGuard}; use crate::{status::Status, template::Template}; pub struct Data { pub int_html: String, pub globals: Vec, pub index: Template, pub status: Mutex, pub status_updated: Mutex<(Instant, bool)>, } #[allow(dead_code)] impl Data { pub fn new_sync(int_html: String, index: Template, globals: Vec) -> Self { Self { int_html, index, globals, status: Mutex::new(Status::query_sync(false)), status_updated: Mutex::new((Instant::now(), false)), } } pub async fn new_async(int_html: String, index: Template, globals: Vec) -> Self { Self { int_html, index, globals, status: Mutex::new(Status::query_async(false).await), status_updated: Mutex::new((Instant::now(), false)), } } pub fn status_sync(&self, dbg: bool) -> MutexGuard { let mut updated = self.status_updated.blocking_lock(); let now = Instant::now(); if (now - updated.0).as_secs_f32() > 3.0 || (dbg && !updated.1) { updated.0 = now; updated.1 = dbg; drop(updated); let mut lock = self.status.blocking_lock(); *lock = Status::query_sync(dbg); lock } else { drop(updated); self.status.blocking_lock() } } pub async fn status_async(&self, dbg: bool) -> MutexGuard { let mut updated = self.status_updated.lock().await; let now = Instant::now(); if (now - updated.0).as_secs_f32() > 3.0 || (dbg && !updated.1) { updated.0 = now; updated.1 = dbg; drop(updated); let mut lock = self.status.lock().await; *lock = Status::query_async(dbg).await; lock } else { drop(updated); self.status.lock().await } } }