endstat/src/main.rs

79 lines
2.0 KiB
Rust

#![forbid(unsafe_code)]
extern crate actix;
extern crate actix_web;
extern crate chrono;
extern crate env_logger;
extern crate reqwest;
extern crate ron;
extern crate serde;
extern crate tokio;
#[macro_use]
extern crate tera;
extern crate ring;
mod config;
mod handlers;
mod results;
mod updater;
use self::{config::*, handlers::*, results::QueryResults, updater::*};
use actix::System;
use actix_web::{middleware::Logger, web::resource, App, HttpServer};
use ron::de::from_str;
use std::{
env::var,
fs::read_to_string,
sync::{Arc, RwLock},
time::Duration,
};
use tokio::{
prelude::{Future, Stream},
timer::Interval,
};
pub type State = Arc<RwLock<QueryResults>>;
fn main() {
System::run(|| {
let conf_file_loc =
var("ENDSTAT_CONF").unwrap_or_else(|_| String::from("./config/endstat_conf.ron"));
let config = from_str::<Config>(
&read_to_string(&conf_file_loc).expect(&format!("finding {}", conf_file_loc)),
)
.unwrap();
let bind_addr = &config.bind_address;
std::env::set_var("RUST_LOG", "actix_web=info");
env_logger::init();
let state = Arc::new(RwLock::new(QueryResults::new(config.clone())));
let clone_state = Arc::clone(&state);
HttpServer::new(move || {
let tera = compile_templates!("./templates/**/*");
let state = Arc::clone(&state);
App::new()
.data(state)
.data(tera)
.wrap(Logger::default())
.service(resource("/").to(index))
.service(resource("/api").to(json_endpoint))
})
.bind(&bind_addr)
.expect("Could not bind to address!")
.start();
tokio::spawn(
Interval::new_interval(Duration::from_secs(config.refresh_time))
.for_each(move |_| {
update_state(Arc::clone(&clone_state));
Ok(())
})
.map_err(|_| ()),
);
})
.expect("Could not run system!");
}