66 lines
2.0 KiB
Rust
66 lines
2.0 KiB
Rust
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<String>,
|
|
pub index: Template,
|
|
pub status: Mutex<Status>,
|
|
pub status_updated: Mutex<(Instant, bool)>,
|
|
}
|
|
|
|
#[allow(dead_code)]
|
|
impl Data {
|
|
pub fn new_sync(int_html: String, index: Template, globals: Vec<String>) -> 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<String>) -> 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<Status> {
|
|
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<Status> {
|
|
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
|
|
}
|
|
}
|
|
}
|