diff --git a/Cargo.toml b/Cargo.toml index fa243bc9e..13dbb76d2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -50,7 +50,7 @@ flate2-c = ["flate2/miniz-sys"] flate2-rust = ["flate2/rust_backend"] [dependencies] -# actix = "0.6.1" +# actix = "0.7.0" actix = { git="https://github.com/actix/actix.git" } base64 = "0.9" diff --git a/src/application.rs b/src/application.rs index 2cf7a4fab..aa9a74d1f 100644 --- a/src/application.rs +++ b/src/application.rs @@ -7,13 +7,12 @@ use http::{Method, StatusCode}; use httprequest::HttpRequest; use httpresponse::HttpResponse; use middleware::Middleware; -use param::Params; use pipeline::{HandlerType, Pipeline, PipelineHandler}; use pred::Predicate; use resource::ResourceHandler; use router::{Resource, RouteInfo, Router}; use scope::Scope; -use server::{HttpHandler, HttpHandlerTask, IntoHttpHandler, Request, ServerSettings}; +use server::{HttpHandler, HttpHandlerTask, IntoHttpHandler, Request}; /// Application pub struct HttpApplication { @@ -102,23 +101,20 @@ impl HttpApplication { continue 'outer; } } - let info = self - .router - .route_info_params(params, self.inner.prefix as u16); - return (info, HandlerType::Handler(idx)); + return ( + self.router.route_info_params(params), + HandlerType::Handler(idx), + ); } } } } - ( - self.router.default_route_info(self.inner.prefix as u16), - HandlerType::Default, - ) + (self.router.default_route_info(), HandlerType::Default) } } #[cfg(test)] - pub(crate) fn run(&self, mut req: Request) -> AsyncResult { + pub(crate) fn run(&self, req: Request) -> AsyncResult { let (info, tp) = self.get_handler(&req); let req = HttpRequest::new(req, Rc::clone(&self.state), info); @@ -129,7 +125,7 @@ impl HttpApplication { impl HttpHandler for HttpApplication { type Task = Pipeline>; - fn handle(&self, mut msg: Request) -> Result>, Request> { + fn handle(&self, msg: Request) -> Result>, Request> { let m = { let path = msg.path(); path.starts_with(&self.prefix) diff --git a/src/client/connector.rs b/src/client/connector.rs index 6c32d898e..3bcc57c72 100644 --- a/src/client/connector.rs +++ b/src/client/connector.rs @@ -5,8 +5,8 @@ use std::{fmt, io, mem, time}; use actix::resolver::{Connect as ResolveConnect, Resolver, ResolverError}; use actix::{ - fut, Actor, ActorContext, ActorFuture, ActorResponse, Addr, AsyncContext, Context, - ContextFutureSpawner, Handler, Message, Recipient, StreamHandler2, Supervised, + fut, Actor, ActorFuture, ActorResponse, Addr, AsyncContext, Context, + ContextFutureSpawner, Handler, Message, Recipient, StreamHandler, Supervised, SystemService, WrapFuture, }; @@ -220,7 +220,7 @@ impl Actor for ClientConnector { self.resolver = Some(Resolver::from_registry()) } self.collect_periodic(ctx); - ctx.add_stream2(self.acq_rx.take().unwrap()); + ctx.add_stream(self.acq_rx.take().unwrap()); ctx.spawn(Maintenance); } } @@ -769,20 +769,17 @@ impl Handler for ClientConnector { } } -impl StreamHandler2 for ClientConnector { - fn handle( - &mut self, msg: Result, ()>, - ctx: &mut Context, - ) { +impl StreamHandler for ClientConnector { + fn handle(&mut self, msg: AcquiredConnOperation, _: &mut Context) { let now = Instant::now(); match msg { - Ok(Some(AcquiredConnOperation::Close(conn))) => { + AcquiredConnOperation::Close(conn) => { self.release_key(&conn.key); self.to_close.push(conn); self.stats.closed += 1; } - Ok(Some(AcquiredConnOperation::Release(conn))) => { + AcquiredConnOperation::Release(conn) => { self.release_key(&conn.key); // check connection lifetime and the return to available pool @@ -793,10 +790,9 @@ impl StreamHandler2 for ClientConnector { .push_back(Conn(Instant::now(), conn)); } } - Ok(Some(AcquiredConnOperation::ReleaseKey(key))) => { + AcquiredConnOperation::ReleaseKey(key) => { self.release_key(&key); } - _ => ctx.stop(), } // check keep-alive diff --git a/src/client/response.rs b/src/client/response.rs index a5c23014e..0c094a2aa 100644 --- a/src/client/response.rs +++ b/src/client/response.rs @@ -1,13 +1,11 @@ use std::cell::RefCell; use std::{fmt, str}; -use bytes::Bytes; use cookie::Cookie; -use futures::{Async, Poll, Stream}; use http::header::{self, HeaderValue}; use http::{HeaderMap, StatusCode, Version}; -use error::{CookieParseError, PayloadError}; +use error::CookieParseError; use httpmessage::HttpMessage; use super::pipeline::Pipeline; diff --git a/src/context.rs b/src/context.rs index d13cd4175..71a5af2d8 100644 --- a/src/context.rs +++ b/src/context.rs @@ -105,7 +105,7 @@ where { #[inline] /// Create a new HTTP Context from a request and an actor - pub fn new(req: HttpRequest, actor: A) -> Body { + pub fn create(req: HttpRequest, actor: A) -> Body { let mb = Mailbox::default(); let ctx = HttpContext { inner: ContextParts::new(mb.sender_producer()), diff --git a/src/extractor.rs b/src/extractor.rs index 1b75f9f14..8e0a96594 100644 --- a/src/extractor.rs +++ b/src/extractor.rs @@ -768,7 +768,7 @@ mod tests { routes.push((Resource::new("index", "/{key}/{value}/"), Some(resource))); let (router, _) = Router::new("", routes); - let mut req = TestRequest::with_uri("/name/user1/?id=test") + let req = TestRequest::with_uri("/name/user1/?id=test") .finish_with_router(router.clone()); let info = router.recognize(&req).unwrap().1; let req = req.with_route_info(info); diff --git a/src/fs.rs b/src/fs.rs index 663788234..b6ba47062 100644 --- a/src/fs.rs +++ b/src/fs.rs @@ -2,7 +2,6 @@ use std::fmt::Write; use std::fs::{DirEntry, File, Metadata}; use std::io::{Read, Seek}; -use std::marker::PhantomData; use std::ops::{Deref, DerefMut}; use std::path::{Path, PathBuf}; use std::time::{SystemTime, UNIX_EPOCH}; @@ -20,9 +19,7 @@ use mime_guess::{get_mime_type, guess_mime_type}; use percent_encoding::{utf8_percent_encode, DEFAULT_ENCODE_SET}; use error::Error; -use handler::{ - AsyncResult, AsyncResultItem, Handler, Responder, RouteHandler, WrapHandler, -}; +use handler::{AsyncResult, Handler, Responder, RouteHandler, WrapHandler}; use header; use http::{ContentEncoding, Method, StatusCode}; use httpmessage::HttpMessage; diff --git a/src/handler.rs b/src/handler.rs index c7fd63982..690d71664 100644 --- a/src/handler.rs +++ b/src/handler.rs @@ -10,7 +10,6 @@ use http::StatusCode; use httprequest::HttpRequest; use httpresponse::HttpResponse; use resource::ResourceHandler; -use server::Request; /// Trait defines object that could be registered as route handler #[allow(unused_variables)] diff --git a/src/httpmessage.rs b/src/httpmessage.rs index 8ed48de2c..4da0163e5 100644 --- a/src/httpmessage.rs +++ b/src/httpmessage.rs @@ -16,7 +16,6 @@ use error::{ use header::Header; use json::JsonBody; use multipart::Multipart; -use payload::Payload; /// Trait that implements general purpose operations on http messages pub trait HttpMessage: Sized { @@ -613,10 +612,7 @@ mod tests { use encoding::all::ISO_8859_2; use encoding::Encoding; use futures::Async; - use http::{Method, Uri, Version}; - use httprequest::HttpRequest; use mime; - use std::str::FromStr; use test::TestRequest; #[test] @@ -765,7 +761,7 @@ mod tests { #[test] fn test_urlencoded() { - let mut req = TestRequest::with_header( + let req = TestRequest::with_header( header::CONTENT_TYPE, "application/x-www-form-urlencoded", ).header(header::CONTENT_LENGTH, "11") @@ -780,7 +776,7 @@ mod tests { }) ); - let mut req = TestRequest::with_header( + let req = TestRequest::with_header( header::CONTENT_TYPE, "application/x-www-form-urlencoded; charset=utf-8", ).header(header::CONTENT_LENGTH, "11") @@ -818,7 +814,7 @@ mod tests { _ => unreachable!("error"), } - let mut req = TestRequest::default() + let req = TestRequest::default() .set_payload(Bytes::from_static(b"11111111111111")) .finish(); match req.body().limit(5).poll().err().unwrap() { diff --git a/src/httprequest.rs b/src/httprequest.rs index 3cfcb68aa..186568550 100644 --- a/src/httprequest.rs +++ b/src/httprequest.rs @@ -1,22 +1,18 @@ //! HTTP Request message related code. -use std::cell::{Cell, Ref, RefCell, RefMut}; +use std::cell::{Ref, RefMut}; use std::collections::HashMap; use std::net::SocketAddr; use std::ops::Deref; use std::rc::Rc; -use std::{cmp, fmt, io, str}; +use std::{fmt, str}; -use bytes::Bytes; use cookie::Cookie; -use failure; -use futures::{Async, Poll, Stream}; use futures_cpupool::CpuPool; use http::{header, HeaderMap, Method, StatusCode, Uri, Version}; -use tokio_io::AsyncRead; use url::{form_urlencoded, Url}; use body::Body; -use error::{CookieParseError, PayloadError, UrlGenerationError}; +use error::{CookieParseError, UrlGenerationError}; use extensions::Extensions; use handler::FromRequest; use httpmessage::HttpMessage; @@ -24,19 +20,12 @@ use httpresponse::{HttpResponse, HttpResponseBuilder}; use info::ConnectionInfo; use param::Params; use payload::Payload; -use router::{Resource, RouteInfo, Router}; -use server::message::{MessageFlags, Request}; -use uri::Url as InnerUrl; +use router::{Resource, RouteInfo}; +use server::Request; struct Query(HashMap); struct Cookies(Vec>); -#[derive(Debug, Copy, Clone, PartialEq)] -pub(crate) enum RouterResource { - Notset, - Normal(u16), -} - /// An HTTP Request pub struct HttpRequest { req: Rc, @@ -167,11 +156,6 @@ impl HttpRequest { self.request().inner.url.path() } - #[inline] - pub(crate) fn url(&self) -> &InnerUrl { - &self.request().inner.url - } - /// Get *ConnectionInfo* for the correct request. #[inline] pub fn connection_info(&self) -> Ref { @@ -248,7 +232,6 @@ impl HttpRequest { for (key, val) in form_urlencoded::parse(self.query_string().as_ref()) { query.insert(key.as_ref().to_string(), val.to_string()); } - let mut req = self.clone(); self.extensions_mut().insert(Query(query)); } Ref::map(self.extensions(), |ext| &ext.get::().unwrap().0) @@ -270,7 +253,6 @@ impl HttpRequest { #[inline] pub fn cookies(&self) -> Result>>, CookieParseError> { if self.extensions().get::().is_none() { - let mut req = self.clone(); let mut cookies = Vec::new(); for hdr in self.request().inner.headers.get_all(header::COOKIE) { let s = str::from_utf8(hdr.as_bytes()).map_err(CookieParseError::from)?; @@ -379,7 +361,7 @@ impl fmt::Debug for HttpRequest { mod tests { use super::*; use resource::ResourceHandler; - use router::Resource; + use router::{Resource, Router}; use test::TestRequest; #[test] @@ -448,7 +430,7 @@ mod tests { let routes = vec![(Resource::new("index", "/user/{name}.{ext}"), Some(resource))]; let (router, _) = Router::new("/", routes); - let info = router.default_route_info(0); + let info = router.default_route_info(); assert!(info.has_route("/user/test.html")); assert!(!info.has_route("/test/unknown")); @@ -476,7 +458,7 @@ mod tests { resource.name("index"); let routes = vec![(Resource::new("index", "/user/{name}.html"), Some(resource))]; let (router, _) = Router::new("/prefix/", routes); - let info = router.default_route_info(0); + let info = router.default_route_info(); assert!(info.has_route("/user/test.html")); assert!(!info.has_route("/prefix/user/test.html")); @@ -495,7 +477,7 @@ mod tests { resource.name("index"); let routes = vec![(Resource::new("index", "/index.html"), Some(resource))]; let (router, _) = Router::new("/prefix/", routes); - let info = router.default_route_info(0); + let info = router.default_route_info(); assert!(info.has_route("/index.html")); assert!(!info.has_route("/prefix/index.html")); @@ -518,7 +500,7 @@ mod tests { None, )]; let router = Router::new::<()>("", routes).0; - let info = router.default_route_info(0); + let info = router.default_route_info(); assert!(!info.has_route("https://youtube.com/watch/unknown")); let req = TestRequest::default().finish_with_router(router); diff --git a/src/httpresponse.rs b/src/httpresponse.rs index 71db87678..83c128d70 100644 --- a/src/httpresponse.rs +++ b/src/httpresponse.rs @@ -1042,8 +1042,6 @@ mod tests { use body::Binary; use http; use http::header::{HeaderValue, CONTENT_TYPE, COOKIE}; - use http::{Method, Uri}; - use std::str::FromStr; use time::Duration; use test::TestRequest; diff --git a/src/info.rs b/src/info.rs index 5d43b8e97..b15ba9886 100644 --- a/src/info.rs +++ b/src/info.rs @@ -1,9 +1,4 @@ -use std::rc::Rc; -use std::str::FromStr; - use http::header::{self, HeaderName}; -use httpmessage::HttpMessage; -use httprequest::HttpRequest; use server::Request; const X_FORWARDED_FOR: &[u8] = b"x-forwarded-for"; @@ -165,7 +160,6 @@ impl ConnectionInfo { #[cfg(test)] mod tests { use super::*; - use http::header::HeaderValue; use test::TestRequest; #[test] @@ -214,7 +208,7 @@ mod tests { assert_eq!(info.host(), "192.0.2.60"); assert_eq!(info.remote(), None); - let mut req = TestRequest::default() + let req = TestRequest::default() .header(X_FORWARDED_PROTO, "https") .request(); let mut info = ConnectionInfo::default(); diff --git a/src/json.rs b/src/json.rs index e9083cdd1..485d0b3e4 100644 --- a/src/json.rs +++ b/src/json.rs @@ -1,4 +1,4 @@ -use bytes::{Bytes, BytesMut}; +use bytes::BytesMut; use futures::{Future, Poll, Stream}; use http::header::CONTENT_LENGTH; use std::fmt; @@ -10,7 +10,7 @@ use serde::de::DeserializeOwned; use serde::Serialize; use serde_json; -use error::{Error, JsonPayloadError, PayloadError}; +use error::{Error, JsonPayloadError}; use handler::{FromRequest, Responder}; use http::StatusCode; use httpmessage::HttpMessage; diff --git a/src/middleware/csrf.rs b/src/middleware/csrf.rs index 0062bd02f..cda1d324c 100644 --- a/src/middleware/csrf.rs +++ b/src/middleware/csrf.rs @@ -50,7 +50,6 @@ use std::collections::HashSet; use bytes::Bytes; use error::{ResponseError, Result}; use http::{header, HeaderMap, HttpTryFrom, Uri}; -use httpmessage::HttpMessage; use httprequest::HttpRequest; use httpresponse::HttpResponse; use middleware::{Middleware, Started}; diff --git a/src/middleware/errhandlers.rs b/src/middleware/errhandlers.rs index a9ebe21ca..83c66aae1 100644 --- a/src/middleware/errhandlers.rs +++ b/src/middleware/errhandlers.rs @@ -87,10 +87,7 @@ mod tests { use http::StatusCode; use httpmessage::HttpMessage; use middleware::Started; - use test; - - use server::Request; - use test::TestRequest; + use test::{self, TestRequest}; fn render_500(_: &HttpRequest, resp: HttpResponse) -> Result { let mut builder = resp.into_builder(); diff --git a/src/middleware/identity.rs b/src/middleware/identity.rs index c85542441..d890bebef 100644 --- a/src/middleware/identity.rs +++ b/src/middleware/identity.rs @@ -46,7 +46,6 @@ //! )); //! } //! ``` -use std::cell::RefCell; use std::rc::Rc; use cookie::{Cookie, CookieJar, Key}; @@ -59,7 +58,6 @@ use http::header::{self, HeaderValue}; use httprequest::HttpRequest; use httpresponse::HttpResponse; use middleware::{Middleware, Response, Started}; -use server::Request; /// The helper trait to obtain your identity from a request. /// @@ -109,13 +107,13 @@ impl RequestIdentity for HttpRequest { } fn remember(&self, identity: String) { - if let Some(mut id) = self.extensions_mut().get_mut::() { + if let Some(id) = self.extensions_mut().get_mut::() { return id.0.as_mut().remember(identity); } } fn forget(&self) { - if let Some(mut id) = self.extensions_mut().get_mut::() { + if let Some(id) = self.extensions_mut().get_mut::() { return id.0.forget(); } } diff --git a/src/middleware/logger.rs b/src/middleware/logger.rs index dbad60a19..103cbf373 100644 --- a/src/middleware/logger.rs +++ b/src/middleware/logger.rs @@ -11,7 +11,6 @@ use httpmessage::HttpMessage; use httprequest::HttpRequest; use httpresponse::HttpResponse; use middleware::{Finished, Middleware, Started}; -use server::Request; /// `Middleware` for logging request and response info to the terminal. /// @@ -309,13 +308,12 @@ impl<'a> fmt::Display for FormatDisplay<'a> { #[cfg(test)] mod tests { - use super::*; - use http::header::{self, HeaderMap}; - use http::{Method, StatusCode, Uri, Version}; - use std::str::FromStr; - use test::TestRequest; use time; + use super::*; + use http::{header, StatusCode}; + use test::TestRequest; + #[test] fn test_logger() { let logger = Logger::new("%% %{User-Agent}i %{X-Test}o %{HOME}e %D test"); diff --git a/src/middleware/mod.rs b/src/middleware/mod.rs index 237a0eb3c..c69dbb3e0 100644 --- a/src/middleware/mod.rs +++ b/src/middleware/mod.rs @@ -4,7 +4,6 @@ use futures::Future; use error::{Error, Result}; use httprequest::HttpRequest; use httpresponse::HttpResponse; -use server::Request; mod logger; diff --git a/src/middleware/session.rs b/src/middleware/session.rs index af3d03cce..9661c2bff 100644 --- a/src/middleware/session.rs +++ b/src/middleware/session.rs @@ -83,7 +83,6 @@ use handler::FromRequest; use httprequest::HttpRequest; use httpresponse::HttpResponse; use middleware::{Middleware, Response, Started}; -use server::Request; /// The helper trait to obtain your session data from a request. /// diff --git a/src/param.rs b/src/param.rs index 649345ee0..c58d9e78f 100644 --- a/src/param.rs +++ b/src/param.rs @@ -57,10 +57,6 @@ impl Params { self.segments.clear(); } - pub(crate) fn set_url(&mut self, url: Url) { - self.url = url; - } - pub(crate) fn set_tail(&mut self, tail: u16) { self.tail = tail; } diff --git a/src/pipeline.rs b/src/pipeline.rs index 0ba258066..528680f53 100644 --- a/src/pipeline.rs +++ b/src/pipeline.rs @@ -6,7 +6,6 @@ use futures::sync::oneshot; use futures::{Async, Future, Poll, Stream}; use log::Level::Debug; -use application::Inner; use body::{Body, BodyStream}; use context::{ActorHttpContext, Frame}; use error::Error; @@ -15,7 +14,7 @@ use header::ContentEncoding; use httprequest::HttpRequest; use httpresponse::HttpResponse; use middleware::{Finished, Middleware, Response, Started}; -use server::{HttpHandlerTask, Request, Writer, WriterState}; +use server::{HttpHandlerTask, Writer, WriterState}; #[doc(hidden)] #[derive(Debug, Clone, Copy)] @@ -84,17 +83,6 @@ struct PipelineInfo { } impl PipelineInfo { - fn new(req: HttpRequest) -> PipelineInfo { - PipelineInfo { - req, - count: 0, - error: None, - context: None, - disconnected: None, - encoding: ContentEncoding::Auto, - } - } - fn poll_context(&mut self) -> Poll<(), Error> { if let Some(ref mut context) = self.context { match context.poll() { diff --git a/src/pred.rs b/src/pred.rs index 5d47922fa..ebc48c348 100644 --- a/src/pred.rs +++ b/src/pred.rs @@ -4,8 +4,6 @@ use std::marker::PhantomData; use http; use http::{header, HttpTryFrom}; -use httpmessage::HttpMessage; -use httprequest::HttpRequest; use server::message::Request; /// Trait defines resource route predicate. @@ -239,11 +237,8 @@ impl Predicate for HostPredicate { #[cfg(test)] mod tests { - use std::str::FromStr; - use super::*; - use http::header::{self, HeaderMap}; - use http::{Method, Uri, Version}; + use http::{header, Method}; use test::TestRequest; #[test] diff --git a/src/resource.rs b/src/resource.rs index 4e8ecf55f..cbf3d9858 100644 --- a/src/resource.rs +++ b/src/resource.rs @@ -12,7 +12,6 @@ use httpresponse::HttpResponse; use middleware::Middleware; use pred; use route::Route; -use server::Request; #[derive(Copy, Clone)] pub(crate) struct RouteId(usize); diff --git a/src/route.rs b/src/route.rs index bf880a3ca..d383d90be 100644 --- a/src/route.rs +++ b/src/route.rs @@ -16,7 +16,6 @@ use middleware::{ Started as MiddlewareStarted, }; use pred::Predicate; -use server::Request; use with::{With, WithAsync}; /// Resource route definition diff --git a/src/router.rs b/src/router.rs index f4da7da02..0edf51844 100644 --- a/src/router.rs +++ b/src/router.rs @@ -3,11 +3,9 @@ use std::hash::{Hash, Hasher}; use std::rc::Rc; use regex::{escape, Regex}; -use smallvec::SmallVec; use url::Url; use error::UrlGenerationError; -use httprequest::HttpRequest; use param::{ParamItem, Params}; use resource::ResourceHandler; use server::Request; @@ -25,7 +23,6 @@ pub struct Router(Rc); pub struct RouteInfo { router: Rc, resource: RouterResource, - prefix: u16, params: Params, } @@ -51,14 +48,8 @@ impl RouteInfo { &self.params } - #[doc(hidden)] #[inline] - pub fn prefix_len(&self) -> u16 { - self.prefix - } - - #[inline] - pub(crate) fn merge(&self, mut params: Params) -> RouteInfo { + pub(crate) fn merge(&self, params: &Params) -> RouteInfo { let mut p = self.params.clone(); p.set_tail(params.tail); for item in ¶ms.segments { @@ -69,7 +60,6 @@ impl RouteInfo { params: p, router: self.router.clone(), resource: self.resource, - prefix: self.prefix, } } @@ -167,10 +157,6 @@ impl Router { &self.0.prefix } - pub(crate) fn get_resource(&self, idx: usize) -> &Resource { - &self.0.patterns[idx] - } - pub(crate) fn route_info(&self, req: &Request, prefix: u16) -> RouteInfo { let mut params = Params::with_url(req.url()); params.set_tail(prefix); @@ -179,22 +165,19 @@ impl Router { params, router: self.0.clone(), resource: RouterResource::Notset, - prefix: 0, } } - pub(crate) fn route_info_params(&self, params: Params, prefix: u16) -> RouteInfo { + pub(crate) fn route_info_params(&self, params: Params) -> RouteInfo { RouteInfo { params, - prefix, router: self.0.clone(), resource: RouterResource::Notset, } } - pub(crate) fn default_route_info(&self, prefix: u16) -> RouteInfo { + pub(crate) fn default_route_info(&self) -> RouteInfo { RouteInfo { - prefix, router: self.0.clone(), resource: RouterResource::Notset, params: Params::new(), @@ -215,7 +198,6 @@ impl Router { params, router: self.0.clone(), resource: RouterResource::Normal(idx as u16), - prefix: self.0.prefix_len as u16, }, )); } diff --git a/src/scope.rs b/src/scope.rs index 5db1562b1..ffa581578 100644 --- a/src/scope.rs +++ b/src/scope.rs @@ -341,7 +341,7 @@ impl RouteHandler for Scope { // recognize resources for &(ref pattern, ref resource) in self.resources.iter() { if let Some(params) = pattern.match_with_params(req, tail, false) { - let req2 = req.with_route_info(req.route().merge(params)); + let req2 = req.with_route_info(req.route().merge(¶ms)); if let Some(id) = resource.get_route_id(&req2) { if self.middlewares.is_empty() { return resource.handle(id, &req2); @@ -358,10 +358,9 @@ impl RouteHandler for Scope { } // nested scopes - let len = req.route().prefix_len() as usize; 'outer: for &(ref prefix, ref handler, ref filters) in &self.nested { if let Some(params) = prefix.match_prefix_with_params(req, tail) { - let req2 = req.with_route_info(req.route().merge(params)); + let req2 = req.with_route_info(req.route().merge(¶ms)); let state = req.state(); for filter in filters { diff --git a/src/server/error.rs b/src/server/error.rs index 79b3e4f0b..b3c79a066 100644 --- a/src/server/error.rs +++ b/src/server/error.rs @@ -2,7 +2,6 @@ use futures::{Async, Poll}; use super::{helpers, HttpHandlerTask, Writer}; use http::{StatusCode, Version}; -use httpresponse::HttpResponse; use Error; pub(crate) struct ServerError(Version, StatusCode); @@ -16,7 +15,7 @@ impl ServerError { impl HttpHandlerTask for ServerError { fn poll_io(&mut self, io: &mut Writer) -> Poll { { - let mut bytes = io.buffer(); + let bytes = io.buffer(); helpers::write_status_line(self.0, self.1.as_u16(), bytes); } io.set_date(); diff --git a/src/server/h1.rs b/src/server/h1.rs index a9b3100fd..c3d44c30e 100644 --- a/src/server/h1.rs +++ b/src/server/h1.rs @@ -9,10 +9,7 @@ use tokio_timer::Delay; use error::{Error, PayloadError}; use http::{StatusCode, Version}; -use httprequest::HttpRequest; -use httpresponse::HttpResponse; use payload::{Payload, PayloadStatus, PayloadWriter}; -use pipeline::Pipeline; use super::error::ServerError; use super::h1decoder::{DecoderError, H1Decoder, Message}; diff --git a/src/server/h1writer.rs b/src/server/h1writer.rs index 70797804f..d25f236d6 100644 --- a/src/server/h1writer.rs +++ b/src/server/h1writer.rs @@ -149,20 +149,18 @@ impl Writer for H1Writer { let mut buffer = self.buffer.as_mut(); let reason = msg.reason().as_bytes(); - let mut is_bin = if let Body::Binary(ref bytes) = body { + if let Body::Binary(ref bytes) = body { buffer.reserve( 256 + msg.headers().len() * AVERAGE_HEADER_SIZE + bytes.len() + reason.len(), ); - true } else { buffer.reserve( 256 + msg.headers().len() * AVERAGE_HEADER_SIZE + reason.len(), ); - false - }; + } // status line helpers::write_status_line(version, msg.status().as_u16(), &mut buffer); diff --git a/src/server/h2.rs b/src/server/h2.rs index a8f28fbfe..001a46b7c 100644 --- a/src/server/h2.rs +++ b/src/server/h2.rs @@ -15,11 +15,7 @@ use tokio_timer::Delay; use error::{Error, PayloadError}; use http::{StatusCode, Version}; -use httpmessage::HttpMessage; -use httprequest::HttpRequest; -use httpresponse::HttpResponse; use payload::{Payload, PayloadStatus, PayloadWriter}; -use pipeline::Pipeline; use uri::Url; use super::error::ServerError; diff --git a/src/server/message.rs b/src/server/message.rs index 73b238730..61f418939 100644 --- a/src/server/message.rs +++ b/src/server/message.rs @@ -172,7 +172,8 @@ impl Request { } #[inline] - pub(crate) fn reset(&mut self) { + /// Reset request instance + pub fn reset(&mut self) { self.inner.headers.clear(); self.inner.extensions.borrow_mut().clear(); self.inner.flags.set(MessageFlags::empty()); @@ -210,6 +211,7 @@ impl RequestPool { } #[inline] + /// Release request instance pub fn release(&self, mut msg: Request) { let v = &mut self.0.borrow_mut(); if v.len() < 128 { diff --git a/src/server/mod.rs b/src/server/mod.rs index 4f95ffb7f..a302f5e73 100644 --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -33,7 +33,6 @@ use actix::Message; use body::Binary; use error::Error; use header::ContentEncoding; -use httprequest::HttpRequest; use httpresponse::HttpResponse; /// max buffer size 64k diff --git a/src/server/output.rs b/src/server/output.rs index 1d9ee92a4..597faf342 100644 --- a/src/server/output.rs +++ b/src/server/output.rs @@ -10,12 +10,10 @@ use bytes::BytesMut; use flate2::write::{DeflateEncoder, GzEncoder}; #[cfg(feature = "flate2")] use flate2::Compression; -use http::header::{ - HeaderValue, ACCEPT_ENCODING, CONTENT_ENCODING, CONTENT_LENGTH, TRANSFER_ENCODING, -}; -use http::{HttpTryFrom, Method, Version}; +use http::header::{ACCEPT_ENCODING, CONTENT_LENGTH}; +use http::Version; -use super::message::{InnerRequest, Request}; +use super::message::InnerRequest; use body::{Binary, Body}; use header::ContentEncoding; use httpresponse::HttpResponse; diff --git a/src/server/settings.rs b/src/server/settings.rs index 7f38088c8..ceb362ac2 100644 --- a/src/server/settings.rs +++ b/src/server/settings.rs @@ -11,7 +11,6 @@ use parking_lot::Mutex; use time; use super::channel::Node; -use super::helpers; use super::message::{Request, RequestPool}; use super::KeepAlive; use body::Body; @@ -161,7 +160,6 @@ pub(crate) struct WorkerSettings { channels: Cell, node: Box>, date: UnsafeCell, - settings: ServerSettings, } impl WorkerSettings { @@ -177,13 +175,12 @@ impl WorkerSettings { WorkerSettings { h: RefCell::new(h), bytes: Rc::new(SharedBytesPool::new()), - messages: RequestPool::pool(settings.clone()), + messages: RequestPool::pool(settings), channels: Cell::new(0), node: Box::new(Node::head()), date: UnsafeCell::new(Date::new()), keep_alive, ka_enabled, - settings, } } diff --git a/src/server/srv.rs b/src/server/srv.rs index 772238927..dc7321213 100644 --- a/src/server/srv.rs +++ b/src/server/srv.rs @@ -5,7 +5,7 @@ use std::{io, net, thread}; use actix::{ fut, signal, Actor, ActorFuture, Addr, Arbiter, AsyncContext, Context, Handler, - Response, StreamHandler2, System, WrapFuture, + Response, StreamHandler, System, WrapFuture, }; use futures::sync::mpsc; @@ -447,7 +447,7 @@ impl HttpServer { // start http server actor let signals = self.subscribe_to_signals(); let addr = Actor::create(move |ctx| { - ctx.add_stream2(rx); + ctx.add_stream(rx); self }); if let Some(signals) = signals { @@ -613,51 +613,55 @@ impl Handler for HttpServer { } /// Commands from accept threads -impl StreamHandler2 for HttpServer { - fn handle(&mut self, msg: Result, ()>, _: &mut Context) { - if let Ok(Some(ServerCommand::WorkerDied(idx, socks))) = msg { - let mut found = false; - for i in 0..self.workers.len() { - if self.workers[i].0 == idx { - self.workers.swap_remove(i); - found = true; - break; - } - } +impl StreamHandler for HttpServer { + fn finished(&mut self, _: &mut Context) {} - if found { - error!("Worker has died {:?}, restarting", idx); - let (tx, rx) = mpsc::unbounded::>(); - - let mut new_idx = self.workers.len(); - 'found: loop { - for i in 0..self.workers.len() { - if self.workers[i].0 == new_idx { - new_idx += 1; - continue 'found; - } + fn handle(&mut self, msg: ServerCommand, _: &mut Context) { + match msg { + ServerCommand::WorkerDied(idx, socks) => { + let mut found = false; + for i in 0..self.workers.len() { + if self.workers[i].0 == idx { + self.workers.swap_remove(i); + found = true; + break; } - break; } - let ka = self.keep_alive; - let factory = Arc::clone(&self.factory); - let host = self.host.clone(); - let addr = socks[0].addr; + if found { + error!("Worker has died {:?}, restarting", idx); + let (tx, rx) = mpsc::unbounded::>(); - let addr = Arbiter::start(move |ctx: &mut Context<_>| { - let settings = ServerSettings::new(Some(addr), &host, false); - let apps: Vec<_> = - (*factory)().into_iter().map(|h| h.into_handler()).collect(); - ctx.add_message_stream(rx); - Worker::new(apps, socks, ka, settings) - }); - for item in &self.accept { - let _ = item.1.send(Command::Worker(new_idx, tx.clone())); - let _ = item.0.set_readiness(mio::Ready::readable()); + let mut new_idx = self.workers.len(); + 'found: loop { + for i in 0..self.workers.len() { + if self.workers[i].0 == new_idx { + new_idx += 1; + continue 'found; + } + } + break; + } + + let ka = self.keep_alive; + let factory = Arc::clone(&self.factory); + let host = self.host.clone(); + let addr = socks[0].addr; + + let addr = Arbiter::start(move |ctx: &mut Context<_>| { + let settings = ServerSettings::new(Some(addr), &host, false); + let apps: Vec<_> = + (*factory)().into_iter().map(|h| h.into_handler()).collect(); + ctx.add_message_stream(rx); + Worker::new(apps, socks, ka, settings) + }); + for item in &self.accept { + let _ = item.1.send(Command::Worker(new_idx, tx.clone())); + let _ = item.0.set_readiness(mio::Ready::readable()); + } + + self.workers.push((new_idx, addr)); } - - self.workers.push((new_idx, addr)); } } } diff --git a/src/test.rs b/src/test.rs index 5fc06f65c..bc34472e4 100644 --- a/src/test.rs +++ b/src/test.rs @@ -22,7 +22,7 @@ use client::{ClientConnector, ClientRequest, ClientRequestBuilder}; use error::Error; use handler::{AsyncResultItem, Handler, Responder}; use header::{Header, IntoHeaderValue}; -use httprequest::{HttpRequest, RouterResource}; +use httprequest::HttpRequest; use httpresponse::HttpResponse; use middleware::Middleware; use param::Params; @@ -548,7 +548,7 @@ impl TestRequest { *req.inner.payload.borrow_mut() = payload; let mut req = - HttpRequest::new(req, Rc::new(state), router.route_info_params(params, 0)); + HttpRequest::new(req, Rc::new(state), router.route_info_params(params)); req.set_cookies(cookies); req } @@ -574,7 +574,7 @@ impl TestRequest { req.inner.headers = headers; *req.inner.payload.borrow_mut() = payload; let mut req = - HttpRequest::new(req, Rc::new(state), router.route_info_params(params, 0)); + HttpRequest::new(req, Rc::new(state), router.route_info_params(params)); req.set_cookies(cookies); req } @@ -582,14 +582,12 @@ impl TestRequest { /// Complete request creation and generate server `Request` instance pub fn request(self) -> Request { let TestRequest { - state, method, uri, version, headers, - params, - cookies, payload, + .. } = self; let mut req = Request::new(ServerSettings::default()); req.inner.method = method; diff --git a/src/ws/client.rs b/src/ws/client.rs index 251b0edd6..4295905ab 100644 --- a/src/ws/client.rs +++ b/src/ws/client.rs @@ -23,8 +23,8 @@ use httpmessage::HttpMessage; use payload::PayloadHelper; use client::{ - ClientConnector, ClientRequest, ClientRequestBuilder, ClientResponse, - HttpResponseParserError, Pipeline, SendRequest, SendRequestError, + ClientConnector, ClientRequest, ClientRequestBuilder, HttpResponseParserError, + Pipeline, SendRequest, SendRequestError, }; use super::frame::Frame; diff --git a/src/ws/context.rs b/src/ws/context.rs index 91a23e0fd..0444db997 100644 --- a/src/ws/context.rs +++ b/src/ws/context.rs @@ -92,7 +92,7 @@ where { #[inline] /// Create a new Websocket context from a request and an actor - pub fn new

(req: HttpRequest, actor: A, stream: WsStream

) -> Body + pub fn create

(req: HttpRequest, actor: A, stream: WsStream

) -> Body where A: StreamHandler, P: Stream + 'static, diff --git a/src/ws/mod.rs b/src/ws/mod.rs index 63b7ab0a1..05099971e 100644 --- a/src/ws/mod.rs +++ b/src/ws/mod.rs @@ -45,7 +45,7 @@ use bytes::Bytes; use futures::{Async, Poll, Stream}; use http::{header, Method, StatusCode}; -use super::actix::{Actor, AsyncContext, StreamHandler}; +use super::actix::{Actor, StreamHandler}; use body::Binary; use error::{Error, PayloadError, ResponseError}; @@ -179,7 +179,7 @@ where let mut resp = handshake(req)?; let stream = WsStream::new(req.payload()); - let body = WebsocketContext::new(req.clone(), actor, stream); + let body = WebsocketContext::create(req.clone(), actor, stream); Ok(resp.body(body)) } @@ -357,10 +357,8 @@ pub trait WsWriter { #[cfg(test)] mod tests { - use std::str::FromStr; - use super::*; - use http::{header, HeaderMap, Method, Uri, Version}; + use http::{header, Method}; use test::TestRequest; #[test]