extern crate log;
use std::path::PathBuf;
use std::time::Instant;
use log::debug;
use structopt::StructOpt;
use actix_web::{web, App, http, HttpResponse, HttpServer, Responder, middleware::Logger};
use actix_cors::Cors;
use solvastro::process_query::process_query;
use solvastro::query::Query;
use solvastro::settings::Settings;
use solvastro::star_index::StarIndex;
#[derive(Debug, StructOpt)]
struct CliArgs {
#[structopt(parse(from_os_str))]
star_index: PathBuf,
}
pub struct AppState {
pub config: Settings,
pub star_index: StarIndex,
}
#[cfg(not(tarpaulin_include))]
#[actix_web::main]
async fn main() -> std::io::Result<()> {
let start = Instant::now();
pretty_env_logger::init();
let cli_args = CliArgs::from_args();
let config = Settings::new().expect("could not load settings");
let cors_origin: String = config.cors_origin.clone();
println!("Settings: {:?}", &config);
let star_index: StarIndex =
StarIndex::read_from_file(&cli_args.star_index).expect("Could not load StarIndex");
let app_state: web::Data<AppState> = web::Data::new(AppState { config, star_index });
let server = HttpServer::new(move || {
App::new()
.wrap(
Cors::default()
.allowed_origin(&cors_origin.clone())
.allowed_methods(vec!["GET", "POST"])
.allowed_headers(vec![http::header::AUTHORIZATION, http::header::ACCEPT, http::header::COOKIE, http::header::CONTENT_TYPE])
.max_age(3600)
)
.wrap(Logger::default())
.app_data(app_state.clone())
.service(
web::scope("/")
.route("/health", web::get().to(health_check_handler))
.route("/vip/query", web::post().to(image_query_handler))
)
})
.bind("0.0.0.0:5000")?
.run();
let duration_startup = start.elapsed();
println!("Startup time: {:?}", duration_startup);
server.await
}
async fn health_check_handler() -> impl Responder {
"Hello world!"
}
async fn image_query_handler(state: web::Data<AppState>, item: web::Json<Query>) -> HttpResponse {
debug!("Query request received: {:?}", &item);
let body = process_query(&state.star_index, &item.0, &state.config).unwrap();
debug!("Query Result: {:?}", &body);
HttpResponse::Ok().json(body)
}