Compare commits

..

No commits in common. "af79f6d2a35a1b03898f80e4b11253db60f9ea00" and "d92a5b7004b62cd999f35ce94c7e86f10b1d7213" have entirely different histories.

3 changed files with 38 additions and 35 deletions

View file

@ -7,10 +7,10 @@ use actix_web::{
use reqwest::{Client, Url, UrlError};
use serde::Serialize;
use std::sync::{Arc, RwLock};
use std::sync::{Arc, Mutex, MutexGuard};
use tera::{Context, Tera};
#[derive(Clone, Serialize, Default, Debug)]
#[derive(Clone, Serialize, Default)]
pub struct Status {
status: u8,
location: String,
@ -19,7 +19,7 @@ pub struct Status {
error: Option<String>,
}
#[derive(Serialize, Debug)]
#[derive(Serialize)]
pub struct QueryResults {
pub last_update: EpochTimestamp,
pub refresh_time: u64,
@ -27,10 +27,25 @@ pub struct QueryResults {
pub statuses: Vec<Status>,
}
type State = Arc<RwLock<QueryResults>>;
type State = Arc<Mutex<QueryResults>>;
// impl State {
// pub fn new(config: &Config) -> Self {
// State(Arc::from(Mutex::from(QueryResults {
// last_update: EpochTimestamp::now(),
// refresh_time: config.refresh_time.clone(),
// config: config.clone(),
// statuses: vec![],
// })))
// }
// fn lock(&self) -> MutexGuard<QueryResults> {
// self.0.lock().unwrap()
// }
// }
pub fn index(tmpl: Data<Tera>, state: Data<State>) -> WebResult<HttpResponse, WebError> {
let state = state.read().unwrap();
let state = update_state(state.lock().unwrap());
let mut ctx = Context::new();
ctx.insert("results", &*state);
let s = tmpl.render("index.html", &ctx).map_err(|e| {
@ -41,25 +56,17 @@ pub fn index(tmpl: Data<Tera>, state: Data<State>) -> WebResult<HttpResponse, We
}
pub fn json_endpoint(state: Data<State>) -> HttpResponse {
let state = state.read().unwrap();
let state = update_state(state.lock().unwrap());
HttpResponse::Ok().json(&state.statuses)
}
pub fn update_state(state: State) {
let mut new_timestamp = None;
let mut new_statuses = None;
{
let read_state = state.read().unwrap();
if EpochTimestamp::now() - read_state.last_update >= read_state.refresh_time {
new_timestamp = Some(EpochTimestamp::now());
new_statuses = Some(update_status(&read_state.config));
}
}
if new_timestamp.is_some() {
let mut write_state = state.try_write().expect("Could not unlock");
write_state.last_update = new_timestamp.unwrap();
write_state.statuses = new_statuses.unwrap();
fn update_state(mut state: MutexGuard<QueryResults>) -> MutexGuard<QueryResults> {
if EpochTimestamp::now() - state.last_update >= state.refresh_time {
state.last_update = EpochTimestamp::now();
state.statuses = update_status(&state.config);
}
state
}
fn update_status(config: &Config) -> Vec<Status> {

View file

@ -19,8 +19,9 @@ use actix::System;
use actix_web::{middleware::Logger, web::resource, App, HttpServer};
use ron::de::from_str;
use std::{
error::Error,
fs::read_to_string,
sync::{Arc, RwLock},
sync::{Arc, Mutex},
time::Duration,
};
use tokio::prelude::{Future, Stream};
@ -28,28 +29,25 @@ use tokio::timer::Interval;
fn main() {
System::run(move || {
let config = from_str::<Config>(
&read_to_string("./endstat_conf.ron").expect("Could not find config file"),
)
.unwrap();
let config = from_str::<Config>(&read_to_string("./endstat_conf.ron").expect("Could not find config file")).unwrap();
let bind_addr = config.bind_address.clone();
std::env::set_var("RUST_LOG", "actix_web=info");
env_logger::init();
let state = Arc::new(RwLock::new(QueryResults {
let state = Arc::from(Mutex::from(QueryResults {
last_update: EpochTimestamp::now(),
refresh_time: config.refresh_time.clone(),
config: config.clone(),
statuses: vec![],
}));
let clone_state = Arc::clone(&state);
let state1 = state.clone();
let state2 = state.clone();
HttpServer::new(move || {
let tera = compile_templates!(concat!(env!("CARGO_MANIFEST_DIR"), "/templates/**/*"));
let state = Arc::clone(&state);
App::new()
.data(state)
.data(state1)
.data(tera)
.wrap(Logger::default())
.service(resource("/").to(index))
@ -61,13 +59,11 @@ fn main() {
tokio::spawn(
Interval::new_interval(Duration::from_millis(5000))
.for_each(move |_| {
let state = Arc::clone(&clone_state);
update_state(state);
.for_each(|_| {
println!("Every 5 seconds");
Ok(())
})
.map_err(|_| ()),
);
})
.expect("Could not run system!");
}).expect("Could not run system!");
}

View file

@ -5,7 +5,7 @@ use std::{
time::{SystemTime, UNIX_EPOCH},
};
#[derive(PartialEq, PartialOrd, Copy, Clone, Debug)]
#[derive(PartialEq, PartialOrd, Copy, Clone)]
pub struct EpochTimestamp(SystemTime);
impl EpochTimestamp {