Started removing unwrap calls

proxy
Jef Roosens 2021-11-26 21:49:19 +01:00
parent 84b9afbd1b
commit d78e35a2f5
Signed by: Jef Roosens
GPG Key ID: B580B976584B5F30
3 changed files with 34 additions and 23 deletions

View File

@ -40,7 +40,7 @@ base64 = "0.13.0"
figment = { version = "*", features = [ "yaml" ] } figment = { version = "*", features = [ "yaml" ] }
mimalloc = { version = "0.1.26", default_features = false } mimalloc = { version = "0.1.26", default_features = false }
reqwest = { version = "0.11.6", features = [ "stream" ] } reqwest = { version = "0.11.6", features = [ "stream" ] }
tokio-util = {version="*", features=["compat"]} tokio-util = {version="*", features=[ "compat" ] }
bytes = "*" bytes = "*"
futures = "0.3.18" futures = "0.3.18"

View File

@ -129,11 +129,15 @@ fn rocket() -> _
.expect("services config"); .expect("services config");
rocket rocket
.mount("/api/v1/posts", ProxyServer::from(&services_conf.blog, "/v1/posts")) .mount(
"/api/v1/posts",
ProxyServer::from(&services_conf.blog, "/v1/posts"),
)
.mount( .mount(
"/api/v1/sections", "/api/v1/sections",
ProxyServer::from(&services_conf.blog, "/v1/sections"), ProxyServer::from(&services_conf.blog, "/v1/sections"),
) )
.mount("/yeet", ProxyServer::from("http://localhost:5000", "/"))
.manage(jwt_conf) .manage(jwt_conf)
.manage(admin_conf) .manage(admin_conf)
.attach(AdHoc::try_on_ignite("Create admin user", create_admin_user)) .attach(AdHoc::try_on_ignite("Create admin user", create_admin_user))

View File

@ -1,7 +1,4 @@
use std::{ use std::path::{Path, PathBuf};
io::Cursor,
path::{Path, PathBuf},
};
use futures::stream::TryStreamExt; use futures::stream::TryStreamExt;
use reqwest::{ use reqwest::{
@ -10,8 +7,7 @@ use reqwest::{
}; };
use rocket::{ use rocket::{
data::ToByteUnit, data::ToByteUnit,
http::{Header, Method}, http::{Method, Status},
response::{stream::ByteStream, Redirect},
route::{Handler, Outcome}, route::{Handler, Outcome},
Data, Request, Route, Data, Request, Route,
}; };
@ -82,21 +78,25 @@ impl Handler for ProxyServer
{ {
async fn handle<'r>(&self, req: &'r Request<'_>, data: Data<'r>) -> Outcome<'r> async fn handle<'r>(&self, req: &'r Request<'_>, data: Data<'r>) -> Outcome<'r>
{ {
println!("{:?}", req); // ROCKET REQUEST -> REQWEST REQUEST
// The goals here is to convert a Rocket request into a reqwest one
// First, we convert the headers // Headers
let mut headers = HeaderMap::new(); let mut headers = HeaderMap::new();
for header in req.headers().iter() { for header in req.headers().iter() {
// TODO remove unwrap let name = match HeaderName::from_lowercase(header.name.into_string().as_bytes()) {
headers.insert( Ok(val) => val,
HeaderName::from_lowercase(header.name.into_string().as_bytes()).unwrap(), Err(_) => return Outcome::Failure(Status::BadRequest),
HeaderValue::from_str(&header.value.into_owned()).unwrap(), };
); let value = match HeaderValue::from_str(&header.value.into_owned()) {
Ok(val) => val,
Err(_) => return Outcome::Failure(Status::BadRequest),
};
headers.insert(name, value);
} }
// Then the method // Method
let method = match req.method() { let method = match req.method() {
Method::Delete => ReqMethod::DELETE, Method::Delete => ReqMethod::DELETE,
Method::Get => ReqMethod::GET, Method::Get => ReqMethod::GET,
@ -106,9 +106,12 @@ impl Handler for ProxyServer
_ => todo!(), _ => todo!(),
}; };
// Then the URL // URL
// We first extract all URL segments starting from the mountpoint // We first extract all URL segments starting from the mountpoint
let segments: PathBuf = req.segments(0..).unwrap(); let segments: PathBuf = match req.segments(0..) {
Ok(val) => val,
Err(_) => return Outcome::Failure(Status::InternalServerError),
};
let query_part = req let query_part = req
.uri() .uri()
@ -118,8 +121,8 @@ impl Handler for ProxyServer
let url = format!( let url = format!(
"{}{}/{}{}", "{}{}/{}{}",
self.root, self.root,
self.prefix.to_str().unwrap(), self.prefix.to_str().unwrap_or(""),
segments.to_str().unwrap(), segments.to_str().unwrap_or(""),
query_part query_part
); );
@ -127,7 +130,7 @@ impl Handler for ProxyServer
// TODO don't hard-code max request size here // TODO don't hard-code max request size here
static BODY_SIZE: i64 = 2; static BODY_SIZE: i64 = 2;
// TODO remove unwrap // TODO remove unwrap
let data: Vec<u8> = data let body: Vec<u8> = data
.open(BODY_SIZE.mebibytes()) .open(BODY_SIZE.mebibytes())
.into_bytes() .into_bytes()
.await .await
@ -135,16 +138,20 @@ impl Handler for ProxyServer
.to_vec(); .to_vec();
// TODO remove unwrap // TODO remove unwrap
// let body = reqwest::Body::wrap_stream(data);
let new_res = reqwest::Client::new() let new_res = reqwest::Client::new()
.request(method, url) .request(method, url)
.headers(headers) .headers(headers)
.body(data) .body(body)
.send() .send()
.await .await
.unwrap(); .unwrap();
let mut res_headers = new_res.headers().clone(); let mut res_headers = new_res.headers().clone();
let mut res_builder = rocket::Response::build(); let mut res_builder = rocket::Response::build();
// Let us thank this Git repo for showing me how to do this
// https://github.com/benkay86/async-applied/blob/master/reqwest-tokio-compat/src/main.rs
let mut res_builder = res_builder let mut res_builder = res_builder
.status(rocket::http::Status::new(new_res.status().as_u16())) .status(rocket::http::Status::new(new_res.status().as_u16()))
.streamed_body( .streamed_body(