107 lines
2.3 KiB
Rust
107 lines
2.3 KiB
Rust
use std::{
|
|
error::Error,
|
|
path::PathBuf,
|
|
sync::Arc,
|
|
time::Duration,
|
|
};
|
|
|
|
use handlebars::Handlebars;
|
|
use hyper::{
|
|
StatusCode,
|
|
};
|
|
use reqwest::Client;
|
|
use tokio::{
|
|
time::delay_for,
|
|
};
|
|
|
|
use crate::http_serde;
|
|
|
|
pub mod file_server;
|
|
|
|
const SERVER_NAME: &str = "alien_wildlands";
|
|
|
|
async fn handle_req_resp <'a> (
|
|
opt: &'a Opt,
|
|
handlebars: Arc <Handlebars <'static>>,
|
|
client: &'a Client,
|
|
req_resp: reqwest::Response
|
|
) {
|
|
//println! ("Step 1");
|
|
|
|
if req_resp.status () != StatusCode::OK {
|
|
// TODO: Error handling
|
|
return;
|
|
}
|
|
|
|
let body = req_resp.bytes ().await.unwrap ();
|
|
let wrapped_req: http_serde::WrappedRequest = match rmp_serde::from_read_ref (&body)
|
|
{
|
|
Ok (x) => x,
|
|
_ => return,
|
|
};
|
|
|
|
let (req_id, parts) = (wrapped_req.id, wrapped_req.req);
|
|
|
|
let response = file_server::serve_all (handlebars, &opt.file_server_root, parts).await;
|
|
|
|
let mut resp_req = client
|
|
.post (&format! ("{}/7ZSFUKGV_http_response/{}", opt.relay_url, req_id))
|
|
.header (crate::PTTH_MAGIC_HEADER, base64::encode (rmp_serde::to_vec (&response.parts).unwrap ()));
|
|
|
|
if let Some (body) = response.body {
|
|
resp_req = resp_req.body (reqwest::Body::wrap_stream (body));
|
|
}
|
|
|
|
//println! ("Step 6");
|
|
if let Err (e) = resp_req.send ().await {
|
|
println! ("Err: {:?}", e);
|
|
}
|
|
}
|
|
|
|
pub struct Opt {
|
|
pub relay_url: String,
|
|
pub file_server_root: PathBuf,
|
|
}
|
|
|
|
pub async fn main (opt: Opt) -> Result <(), Box <dyn Error>> {
|
|
let client = Arc::new (Client::new ());
|
|
let opt = Arc::new (opt);
|
|
|
|
let handlebars = Arc::new (file_server::load_templates ()?);
|
|
|
|
let mut backoff_delay = 0;
|
|
|
|
loop {
|
|
if backoff_delay > 0 {
|
|
delay_for (Duration::from_millis (backoff_delay)).await;
|
|
}
|
|
|
|
let req_req = client.get (&format! ("{}/7ZSFUKGV_http_listen/{}", opt.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 ();
|
|
let opt = opt.clone ();
|
|
|
|
let handlebars = handlebars.clone ();
|
|
tokio::spawn (async move {
|
|
match handle_req_resp (&opt, handlebars, &client, req_resp).await {
|
|
_ => (),
|
|
}
|
|
});
|
|
}
|
|
}
|