use std::{ error::Error, sync::Arc, time::Duration, }; use hyper::{ StatusCode, }; use reqwest::Client; use tokio::{ time::delay_for, }; use ptth::http_serde; const RELAY_URL: &str = "http://127.0.0.1:4000"; const SERVER_NAME: &str = "alien_wildlands"; async fn handle_req_resp ( client: &Client, req_resp: reqwest::Response ) -> Result <(), Box > { //println! ("Step 1"); if req_resp.status () != StatusCode::OK { // TODO: Error handling return Ok (()); } let body = req_resp.bytes ().await?; let wrapped_req: http_serde::WrappedRequest = match rmp_serde::from_read_ref (&body) { Ok (x) => x, _ => return Ok (()), }; let (req_id, parts) = (wrapped_req.id, wrapped_req.req); let response = ptth::file_server::serve_all (parts).await; let mut resp_req = client .post (&format! ("{}/http_response/{}", RELAY_URL, req_id)) .header (ptth::PTTH_MAGIC_HEADER, base64::encode (rmp_serde::to_vec (&response.parts).unwrap ())); if let Some (body) = response.body { resp_req = resp_req.body (body); } //println! ("Step 6"); if let Err (e) = resp_req.send ().await { println! ("Err: {:?}", e); } Ok (()) } async fn server_main () -> Result <(), Box > { let client = Arc::new (Client::new ()); let mut backoff_delay = 0; loop { if backoff_delay > 0 { delay_for (Duration::from_millis (backoff_delay)).await; } let req_req = client.get (&format! ("{}/http_listen/{}", RELAY_URL, SERVER_NAME)); let req_resp = match req_req.send ().await { Err (e) => { println! ("Err: {:?}", e); backoff_delay = backoff_delay * 2 + 500; continue; }, Ok (r) => { backoff_delay = 0; r }, }; // Spawn another task for each request so we can // immediately listen for the next connection let client = client.clone (); tokio::spawn (async move { match handle_req_resp (&client, req_resp).await { _ => (), } }); } } #[tokio::main] async fn main () -> Result <(), Box > { server_main ().await }