Skip to content

Commit

Permalink
Clean up, preparing to merge in other changes.
Browse files Browse the repository at this point in the history
  • Loading branch information
jebrosen committed Jul 10, 2019
1 parent db6b1bb commit 937fb46
Show file tree
Hide file tree
Showing 5 changed files with 39 additions and 108 deletions.
54 changes: 15 additions & 39 deletions core/http/src/hyper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,52 +18,28 @@
#[doc(hidden)] pub use http::status::StatusCode;
#[doc(hidden)] pub use http::uri::Uri;

/// Type alias to `hyper::Response<'a, hyper::net::Fresh>`.
// TODO #[doc(hidden)] pub type FreshResponse<'a> = self::Response<'a, self::net::Fresh>;

/// Reexported Hyper header types.
/// Reexported http header types.
pub mod header {
use crate::Header;

macro_rules! import_hyper_items {
($($item:ident),*) => ($(pub use hyper::header::$item;)*)
}

macro_rules! import_hyper_headers {
macro_rules! import_http_headers {
($($name:ident),*) => ($(
pub use http::header::$name as $name;
)*)
}

// import_hyper_items! {
// Accept, AcceptCharset, AcceptEncoding, AcceptLanguage, AcceptRanges,
// AccessControlAllowCredentials, AccessControlAllowHeaders,
// AccessControlAllowMethods, AccessControlExposeHeaders,
// AccessControlMaxAge, AccessControlRequestHeaders,
// AccessControlRequestMethod, Allow, Authorization, Basic, Bearer,
// CacheControl, Connection, ContentDisposition, ContentEncoding,
// ContentLanguage, ContentLength, ContentRange, ContentType, Date, ETag,
// EntityTag, Expires, From, Headers, Host, HttpDate, IfModifiedSince,
// IfUnmodifiedSince, LastModified, Location, Origin, Prefer,
// PreferenceApplied, Protocol, Quality, QualityItem, Referer,
// StrictTransportSecurity, TransferEncoding, Upgrade, UserAgent,
// AccessControlAllowOrigin, ByteRangeSpec, CacheDirective, Charset,
// ConnectionOption, ContentRangeSpec, DispositionParam, DispositionType,
// Encoding, Expect, IfMatch, IfNoneMatch, IfRange, Pragma, Preference,
// ProtocolName, Range, RangeUnit, ReferrerPolicy, Vary, Scheme, q, qitem
// }
//
import_hyper_headers! {
ACCEPT, ACCESS_CONTROL_ALLOW_CREDENTIALS, ACCESS_CONTROL_ALLOW_HEADERS,
import_http_headers! {
ACCEPT, ACCEPT_CHARSET, ACCEPT_ENCODING, ACCEPT_LANGUAGE, ACCEPT_RANGES,
ACCESS_CONTROL_ALLOW_CREDENTIALS, ACCESS_CONTROL_ALLOW_HEADERS,
ACCESS_CONTROL_ALLOW_METHODS, ACCESS_CONTROL_ALLOW_ORIGIN,
ACCESS_CONTROL_EXPOSE_HEADERS, ACCESS_CONTROL_MAX_AGE,
ACCESS_CONTROL_REQUEST_HEADERS, ACCESS_CONTROL_REQUEST_METHOD, ACCEPT_CHARSET,
ACCEPT_ENCODING, ACCEPT_LANGUAGE, ACCEPT_RANGES, ALLOW, CACHE_CONTROL,
CONNECTION, CONTENT_DISPOSITION, CONTENT_ENCODING, CONTENT_LANGUAGE,
CONTENT_LENGTH, CONTENT_RANGE, DATE, ETAG, EXPECT, EXPIRES, HOST, IF_MATCH,
IF_MODIFIED_SINCE, IF_NONE_MATCH, IF_RANGE, IF_UNMODIFIED_SINCE, LAST_MODIFIED,
LOCATION, ORIGIN, PRAGMA, RANGE, REFERER,
REFERRER_POLICY, STRICT_TRANSPORT_SECURITY, TRANSFER_ENCODING, UPGRADE,
USER_AGENT, VARY
ACCESS_CONTROL_REQUEST_HEADERS, ACCESS_CONTROL_REQUEST_METHOD, ALLOW,
AUTHORIZATION, CACHE_CONTROL, CONNECTION, CONTENT_DISPOSITION,
CONTENT_ENCODING, CONTENT_LANGUAGE, CONTENT_LENGTH, CONTENT_LOCATION,
CONTENT_RANGE, CONTENT_SECURITY_POLICY,
CONTENT_SECURITY_POLICY_REPORT_ONLY, CONTENT_TYPE, DATE, ETAG, EXPECT,
EXPIRES, FORWARDED, FROM, HOST, IF_MATCH, IF_MODIFIED_SINCE,
IF_NONE_MATCH, IF_RANGE, IF_UNMODIFIED_SINCE, LAST_MODIFIED, LINK,
LOCATION, ORIGIN, PRAGMA, RANGE, REFERER, REFERRER_POLICY, REFRESH,
STRICT_TRANSPORT_SECURITY, TE, TRANSFER_ENCODING, UPGRADE, USER_AGENT,
VARY
}
}
4 changes: 1 addition & 3 deletions core/http/src/method.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
extern crate http;

use std::fmt;
use std::str::FromStr;

use crate::{hyper, uncased::uncased_eq};
use crate::uncased::uncased_eq;

use self::Method::*;

Expand Down
1 change: 0 additions & 1 deletion core/lib/src/catcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,6 @@ use yansi::Color::*;
///
/// A function decorated with `catch` must take exactly zero or one arguments.
/// If the catcher takes an argument, it must be of type [`&Request`](Request).
#[derive(Clone)]
pub struct Catcher {
/// The HTTP status code to match against.
pub code: u16,
Expand Down
6 changes: 2 additions & 4 deletions core/lib/src/request/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ use std::cell::{Cell, RefCell};
use std::net::{IpAddr, SocketAddr};
use std::fmt;
use std::str;
use std::str::FromStr;
use std::sync::Arc;

use yansi::Paint;
use state::{Container, Storage};
Expand All @@ -15,7 +13,7 @@ use crate::request::{FromFormValue, FormItems, FormItem};
use crate::rocket::Rocket;
use crate::router::Route;
use crate::config::{Config, Limits};
use crate::http::{hyper, uri::{Origin, Segments, Uri}};
use crate::http::{hyper, uri::{Origin, Segments}};
use crate::http::{Method, Header, HeaderMap, Cookies};
use crate::http::{RawStr, ContentType, Accept, MediaType};
use crate::http::private::{Indexed, SmallVec, CookieJar};
Expand Down Expand Up @@ -820,7 +818,7 @@ impl<'r> Request<'r> {
// TODO if cookie_headers.peek().is_some() {
let mut cookie_jar = CookieJar::new();
for header in cookie_headers {
let raw_str = match ::std::str::from_utf8(header.as_bytes()) {
let raw_str = match std::str::from_utf8(header.as_bytes()) {
Ok(string) => string,
Err(_) => continue
};
Expand Down
82 changes: 21 additions & 61 deletions core/lib/src/rocket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,8 @@ use std::collections::HashMap;
use std::convert::From;
use std::str::{from_utf8, FromStr};
use std::cmp::min;
use std::io::{self, Write};
use std::time::Duration;
use std::mem;
use std::net::{IpAddr, SocketAddr, ToSocketAddrs};
use std::net::ToSocketAddrs;
use std::sync::Arc;

use futures::{Future, Stream};
Expand All @@ -19,7 +17,6 @@ use tokio::prelude::{Future as _, Stream as _};
#[cfg(feature = "tls")] use crate::http::tls::TlsAcceptor;

use crate::{logger, handler};
use crate::ext::ReadExt;
use crate::config::{self, Config, LoggedValue};
use crate::request::{Request, FormItems};
use crate::data::Data;
Expand All @@ -45,16 +42,20 @@ pub struct Rocket {
fairings: Fairings,
}

struct RocketArcs {
config: Arc<Config>,
router: Arc<Router>,
default_catchers: Arc<HashMap<u16, Catcher>>,
catchers: Arc<HashMap<u16, Catcher>>,
state: Arc<Container>,
fairings: Arc<Fairings>,
#[derive(Clone)]
struct RocketHyperService {
rocket: Arc<Rocket>,
}

impl std::ops::Deref for RocketHyperService {
type Target = Rocket;

fn deref(&self) -> &Self::Target {
&*self.rocket
}
}

impl<Ctx> hyper::MakeService<Ctx> for RocketArcs {
impl<Ctx> hyper::MakeService<Ctx> for RocketHyperService {
type ReqBody = hyper::Body;
type ResBody = hyper::Body;
type Error = hyper::Error;
Expand All @@ -63,27 +64,16 @@ impl<Ctx> hyper::MakeService<Ctx> for RocketArcs {
type MakeError = Self::Error;

fn make_service(&mut self, _: Ctx) -> Self::Future {
future::ok(RocketHyperService::new(self))
future::ok(RocketHyperService { rocket: self.rocket.clone() })
}
}

#[derive(Clone)]
pub struct RocketHyperService {
config: Arc<Config>,
router: Arc<Router>,
default_catchers: Arc<HashMap<u16, Catcher>>,
catchers: Arc<HashMap<u16, Catcher>>,
state: Arc<Container>,
fairings: Arc<Fairings>,
}

#[doc(hidden)]
impl hyper::Service for RocketHyperService {
type ReqBody = hyper::Body;
type ResBody = hyper::Body;
type Error = hyper::Error;
//type Future = FutureResult<hyper::Response<Self::ResBody>, Self::Error>;
type Future = Box<future::Future<Item = hyper::Response<Self::ResBody>, Error = Self::Error> + Send>;
type Future = Box<dyn future::Future<Item = hyper::Response<Self::ResBody>, Error = Self::Error> + Send>;

// This function tries to hide all of the Hyper-ness from Rocket. It
// essentially converts Hyper types into Rocket types, then calls the
Expand Down Expand Up @@ -132,19 +122,6 @@ impl hyper::Service for RocketHyperService {
}

impl RocketHyperService {

#[inline]
fn new(rocket: &RocketArcs) -> RocketHyperService {
RocketHyperService {
config: rocket.config.clone(),
router: rocket.router.clone(),
default_catchers: rocket.default_catchers.clone(),
catchers: rocket.catchers.clone(),
state: rocket.state.clone(),
fairings: rocket.fairings.clone(),
}
}

/// Preprocess the request for Rocket things. Currently, this means:
///
/// * Rewriting the method in the request if _method form field exists.
Expand Down Expand Up @@ -322,7 +299,7 @@ impl Rocket {
crate fn handle_error<'r>(
&self,
status: Status,
req: &'r Request
req: &'r Request<'_>
) -> Response<'r> {
unimplemented!("TODO")
}
Expand Down Expand Up @@ -553,20 +530,16 @@ impl Rocket {
pub fn register(mut self, catchers: Vec<Catcher>) -> Self {
info!("{}{}", Paint::masked("👾 "), Paint::magenta("Catchers:"));

let mut current_catchers = self.catchers.clone();

for c in catchers {
if self.catchers.get(&c.code).map_or(false, |e| !e.is_default) {
info_!("{} {}", c, Paint::yellow("(warning: duplicate catcher!)"));
} else {
info_!("{}", c);
}

current_catchers.insert(c.code, c);
self.catchers.insert(c.code, c);
}

self.catchers = current_catchers;

self
}

Expand Down Expand Up @@ -763,12 +736,12 @@ impl Rocket {
// Restore the log level back to what it originally was.
logger::pop_max_level();

let arcs = RocketArcs::from(self);
let service = RocketHyperService { rocket: Arc::new(self) };

// NB: executor must be passed manually here, see hyperium/hyper#1537
let server = hyper::Server::builder(incoming)
.executor(runtime.executor())
.serve(arcs);
.serve(service);

// TODO.async: Use with_graceful_shutdown, and let launch() return a Result<(), Error>
runtime.block_on(server).expect("TODO.async handle error");
Expand Down Expand Up @@ -859,22 +832,9 @@ impl Rocket {
}
}

impl From<Rocket> for RocketArcs {
fn from(mut rocket: Rocket) -> Self {
RocketArcs {
config: Arc::new(rocket.config),
router: Arc::new(rocket.router),
default_catchers: Arc::new(rocket.default_catchers),
catchers: Arc::new(rocket.catchers),
state: Arc::new(rocket.state),
fairings: Arc::new(rocket.fairings),
}
}
}

// TODO: consider try_from here?
impl<'a> From<Response<'a>> for hyper::Response<hyper::Body> {
fn from(mut response: Response) -> Self {
fn from(mut response: Response<'_>) -> Self {

let mut builder = hyper::Response::builder();
builder.status(hyper::StatusCode::from_u16(response.status().code).expect(""));
Expand All @@ -901,4 +861,4 @@ impl<'a> From<Response<'a>> for hyper::Response<hyper::Body> {
}
}.unwrap()
}
}
}

0 comments on commit 937fb46

Please sign in to comment.