use actix_web::{ get, http::header::ContentType, middleware::Logger, post, web, App, HttpResponse, HttpServer, Responder, }; use clap::Parser; use futures::try_join; use futures::{future::join_all, lock::Mutex}; use log::info; use serde::{Deserialize, Serialize}; use std::{ collections::HashMap, env::args, io::{stdin, stdout, IsTerminal}, sync::Arc, }; use tokio; use tokio::task; use uuid::Uuid; use lambda::lambda::{eval_whnf, generate_expr, Environment}; use lambda::parser::parse; #[derive(Debug, PartialEq, Serialize, Deserialize, Clone)] struct Registration { url: String, } trait AppState: Send + Sync { fn register(&mut self, registration: &Registration) -> RegistrationResult; } #[derive(Debug, PartialEq, Serialize, Deserialize, Clone)] enum RegistrationResult { RegistrationSuccess { id: String, url: String }, UrlAlreadyRegistered { url: String }, } #[derive(Debug, PartialEq, Serialize, Deserialize, Clone)] struct Client { id: Uuid, url: String, grade: u8, } #[derive(Debug)] struct State { clients: HashMap>>, } impl State { fn new() -> Self { Self { clients: HashMap::new(), } } } impl AppState for State { fn register(&mut self, registration: &Registration) -> RegistrationResult { if self.clients.contains_key(®istration.url) { RegistrationResult::UrlAlreadyRegistered { url: registration.url.clone(), } } else { let id = Uuid::new_v4(); let client = Arc::new(Mutex::new(Client { id, url: registration.url.clone(), grade: 1, })); let client_s = client.clone(); self.clients.insert(registration.url.clone(), client); // let it run in the background // FIXME: should find a way to handle graceful termination task::spawn(async move { send_tests(client_s).await }); RegistrationResult::RegistrationSuccess { id: id.to_string(), url: registration.url.clone(), } } } } #[post("/register")] async fn register( app_state: web::Data>>, registration: web::Json, ) -> impl Responder { let result = app_state.lock().await.register(®istration); match result { RegistrationResult::RegistrationSuccess { .. } => HttpResponse::Ok().json(result), RegistrationResult::UrlAlreadyRegistered { .. } => HttpResponse::BadRequest().json(result), } } #[post("/eval")] async fn eval(input: String) -> impl Responder { let mut env = Environment::new(); match parse(&input).first() { Some(expr) => { let output = eval_whnf(expr, &mut env); HttpResponse::Ok().body(format!("{}", output)) } None => HttpResponse::BadRequest().finish(), } } #[derive(Parser, Debug)] struct Options { /// The port to listen on /// Defaults to 8080 #[arg(short, long, default_value_t = 8080)] port: u16, /// The host to bind the server to /// Defaults to 127.0.0.1 #[arg(long, default_value = "127.0.0.1")] host: String, } #[tokio::main] async fn main() -> std::io::Result<()> { let options = Options::parse(); let app_state = Arc::new(Mutex::new(State::new())); let http_state: Arc> = app_state; env_logger::init(); HttpServer::new(move || { App::new() .wrap(Logger::default()) .app_data(web::Data::new(http_state.clone())) .service(register) .service(eval) }) .bind((options.host, options.port))? .run() .await } async fn send_tests(client_m: Arc>) { loop { tokio::time::sleep(std::time::Duration::from_secs(1)).await; let mut client = client_m.lock().await; let result = send_test(client.grade, &client.url).await; match result { Ok(_) => { client.grade += 1; } Err(_) => { // FIXME } } } } async fn send_test(grade: u8, url: &String) -> Result<(), String> { let input = generate_expr(grade.into()); let mut env = Environment::new(); let output = eval_whnf(&input, &mut env); info!("Sending {} to {}", input, url); let response = reqwest::Client::new() .post(url) .header("content-type", "text/plain") .body(format!("{}", input)) .send() .await; match response { Ok(response) => { let body = response.text().await.unwrap(); let vals = parse(&body); // FIXME: should be able to handle multiple values let result = eval_whnf(vals.first().unwrap(), &mut env); info!("Received {} from {}", body, url); if result == output { info!("Test passed {}", url); Ok(()) } else { info!("Test failed {}", url); Err("Test failed".to_string()) } } Err(e) => { info!("Error sending test: {}", e); Err("Error sending test".to_string()) } } } #[cfg(test)] mod app_tests { use std::sync::Arc; use actix_web::http::header::TryIntoHeaderValue; use actix_web::{body, http::header::ContentType, middleware::Logger, test, App}; use super::*; struct DummyAppState { id: String, } impl DummyAppState { fn new(id: String) -> Self { Self { id } } } impl AppState for DummyAppState { fn register(&mut self, registration: &Registration) -> RegistrationResult { if self.id.is_empty() { RegistrationResult::UrlAlreadyRegistered { url: registration.url.clone(), } } else { RegistrationResult::RegistrationSuccess { id: self.id.clone(), url: registration.url.clone(), } } } } #[actix_web::test] async fn post_registration_returns_success_with_unique_id() { let id = "0123456789abcdef0123456789abcdef".to_string(); let dummy_state: Arc> = Arc::new(Mutex::new(DummyAppState::new(id.clone()))); // FIXME should only be called once, move to setup env_logger::init(); let app = test::init_service( App::new() .wrap(Logger::default()) .app_data(web::Data::new(dummy_state)) .service(register), ) .await; let url = "http://192.168.1.1".to_string(); let req = test::TestRequest::post() .uri("/register") .set_json(Registration { url: url.clone() }) .insert_header(ContentType::json()) .to_request(); let resp = test::call_service(&app, req).await; assert!(resp.status().is_success()); let body = resp.into_body(); let bytes = body::to_bytes(body).await; assert_eq!( RegistrationResult::RegistrationSuccess { id, url }, serde_json::from_slice(&bytes.unwrap()).unwrap() ); } #[actix_web::test] async fn post_registration_returns_400_when_register_fails() { let dummy_state: Arc> = Arc::new(Mutex::new(DummyAppState::new("".to_string()))); let app = test::init_service( App::new() .wrap(Logger::default()) .app_data(web::Data::new(dummy_state)) .service(register), ) .await; let url = "http://192.168.1.1".to_string(); let req = test::TestRequest::post() .uri("/register") .set_json(Registration { url: url.clone() }) .insert_header(ContentType::json()) .to_request(); let resp = test::call_service(&app, req).await; assert!(resp.status().is_client_error()); assert_eq!( ContentType::json().try_into_value().unwrap(), resp.headers().get("content-type").unwrap() ); } #[actix_web::test] async fn post_expression_returns_evaluation() { let app = test::init_service(App::new().wrap(Logger::default()).service(eval)).await; let req = test::TestRequest::post() .uri("/eval") .set_payload("((lam (x y) x) 1 2)") .insert_header(ContentType::plaintext()) .to_request(); let resp = test::call_service(&app, req).await; assert!(resp.status().is_success()); let body = resp.into_body(); let bytes = body::to_bytes(body).await.unwrap(); assert_eq!(bytes, "1".to_string().into_bytes()); } #[test] async fn app_does_not_register_same_url_twice() { let mut app_state = State::new(); let registration = Registration { url: "http://1.2.3.4".to_string(), }; app_state.register(®istration); let result = app_state.register(®istration); assert_eq!( RegistrationResult::UrlAlreadyRegistered { url: "http://1.2.3.4".to_string() }, result ); } // #[test] // async fn tester_repeatedly_callback_registered_client() { // let app_state = Arc::new(Mutex::new(State::new())); // let send_state = app_state.clone(); // let client = Client { // id: Uuid::new_v4(), // url: "http:// // } }