Skip to content

Commit

Permalink
get pr compiling
Browse files Browse the repository at this point in the history
  • Loading branch information
jbr committed Jun 6, 2020
1 parent 980664b commit e2e2dab
Show file tree
Hide file tree
Showing 14 changed files with 67 additions and 78 deletions.
7 changes: 3 additions & 4 deletions examples/middleware.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ fn user_loader<'a>(
if let Some(user) = request.state().find_user().await {
tide::log::trace!("user loaded", {user: user.name});
request.set_ext(user);
next.run(request).await
Ok(next.run(request).await)
// this middleware only needs to run before the endpoint, so
// it just passes through the result of Next
} else {
Expand Down Expand Up @@ -71,7 +71,7 @@ impl<State: Send + Sync + 'static> Middleware<State> for RequestCounterMiddlewar
tide::log::trace!("request counter", { count: count });
req.set_ext(RequestCount(count));

let mut res = next.run(req).await?;
let mut res = next.run(req).await;

res.insert_header("request-number", count.to_string());
Ok(res)
Expand Down Expand Up @@ -99,8 +99,7 @@ async fn main() -> Result<()> {
tide::log::start();
let mut app = tide::with_state(UserDatabase::default());

app.middleware(After(|result: Result| async move {
let response = result.unwrap_or_else(|e| Response::new(e.status()));
app.middleware(After(|response: Response| async move {
match response.status() {
StatusCode::NotFound => {
let mut res = Response::new(404);
Expand Down
2 changes: 1 addition & 1 deletion src/cookies/middleware.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ impl<State: Send + Sync + 'static> Middleware<State> for CookiesMiddleware {
content
};

let mut res = next.run(ctx).await?;
let mut res = next.run(ctx).await;

// Don't do anything if there are no cookies.
if res.cookie_events.is_empty() {
Expand Down
12 changes: 7 additions & 5 deletions src/endpoint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,16 +44,17 @@ use crate::{Middleware, Request, Response};
/// ```
///
/// Tide routes will also accept endpoints with `Fn` signatures of this form, but using the `async` keyword has better ergonomics.
pub trait Endpoint<State>: Send + Sync + 'static {
pub trait Endpoint<State: Send + Sync + 'static>: Send + Sync + 'static {
/// Invoke the endpoint within the given context
fn call<'a>(&'a self, req: Request<State>) -> BoxFuture<'a, crate::Result>;
}

pub(crate) type DynEndpoint<State> = dyn Endpoint<State>;

impl<State, F: Send + Sync + 'static, Fut, Res> Endpoint<State> for F
impl<State, F, Fut, Res> Endpoint<State> for F
where
F: Fn(Request<State>) -> Fut,
State: Send + Sync + 'static,
F: Send + Sync + 'static + Fn(Request<State>) -> Fut,
Fut: Future<Output = Result<Res>> + Send + 'static,
Res: Into<Response>,
{
Expand Down Expand Up @@ -92,6 +93,7 @@ impl<E, State> std::fmt::Debug for MiddlewareEndpoint<E, State> {

impl<E, State> MiddlewareEndpoint<E, State>
where
State: Send + Sync + 'static,
E: Endpoint<State>,
{
pub fn wrap_with_middleware(ep: E, middleware: &[Arc<dyn Middleware<State>>]) -> Self {
Expand All @@ -102,7 +104,7 @@ where
}
}

impl<E, State: 'static> Endpoint<State> for MiddlewareEndpoint<E, State>
impl<E, State: 'static + Send + Sync> Endpoint<State> for MiddlewareEndpoint<E, State>
where
E: Endpoint<State>,
{
Expand All @@ -111,6 +113,6 @@ where
endpoint: &self.endpoint,
next_middleware: &self.middleware,
};
next.run(req)
Box::pin(async move { Ok(next.run(req).await) })
}
}
5 changes: 4 additions & 1 deletion src/fs/serve_dir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,10 @@ impl ServeDir {
}
}

impl<State> Endpoint<State> for ServeDir {
impl<State> Endpoint<State> for ServeDir
where
State: Send + Sync + 'static,
{
fn call<'a>(&'a self, req: Request<State>) -> BoxFuture<'a, Result> {
let path = req.url().path();
let path = path.trim_start_matches(&self.prefix);
Expand Down
60 changes: 24 additions & 36 deletions src/log/middleware.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,43 +37,31 @@ impl LogMiddleware {
path: path,
});
let start = std::time::Instant::now();
match next.run(ctx).await {
Ok(res) => {
let status = res.status();
if status.is_server_error() {
log::error!("--> Response sent", {
method: method,
path: path,
status: status as u16,
duration: format!("{:?}", start.elapsed()),
});
} else if status.is_client_error() {
log::warn!("--> Response sent", {
method: method,
path: path,
status: status as u16,
duration: format!("{:?}", start.elapsed()),
});
} else {
log::info!("--> Response sent", {
method: method,
path: path,
status: status as u16,
duration: format!("{:?}", start.elapsed()),
});
}
Ok(res)
}
Err(err) => {
log::error!("{}", err.to_string(), {
method: method,
path: path,
status: err.status() as u16,
duration: format!("{:?}", start.elapsed()),
});
Err(err)
}
let response = next.run(ctx).await;
let status = response.status();
if status.is_server_error() {
log::error!("--> Response sent", {
method: method,
path: path,
status: status as u16,
duration: format!("{:?}", start.elapsed()),
});
} else if status.is_client_error() {
log::warn!("--> Response sent", {
method: method,
path: path,
status: status as u16,
duration: format!("{:?}", start.elapsed()),
});
} else {
log::info!("--> Response sent", {
method: method,
path: path,
status: status as u16,
duration: format!("{:?}", start.elapsed()),
});
}
Ok(response)
}
}

Expand Down
13 changes: 6 additions & 7 deletions src/middleware.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,7 @@ where
/// use tide::{After, Response, http};
///
/// let mut app = tide::new();
/// app.middleware(After(|res: tide::Result| async move {
/// let res = res.unwrap_or_else(|e| Response::new(e.status()));
/// app.middleware(After(|res: Response| async move {
/// match res.status() {
/// http::StatusCode::NotFound => Ok("Page not found".into()),
/// http::StatusCode::InternalServerError => Ok("Something went wrong".into()),
Expand All @@ -98,8 +97,8 @@ where
next: Next<'a, State>,
) -> BoxFuture<'a, crate::Result> {
Box::pin(async move {
let result = next.run(request).await;
(self.0)(result).await
let response = next.run(request).await;
(self.0)(response).await
})
}
}
Expand Down Expand Up @@ -127,17 +126,17 @@ pub struct Next<'a, State> {
pub(crate) next_middleware: &'a [Arc<dyn Middleware<State>>],
}

impl<'a, State: 'static> Next<'a, State> {
impl<'a, State: 'static + Send + Sync> Next<'a, State> {
/// Asynchronously execute the remaining middleware chain.
#[must_use]
pub async fn run(mut self, req: Request<State>) -> BoxFuture<'a, Response> {
pub fn run(mut self, req: Request<State>) -> BoxFuture<'a, Response> {
Box::pin(async move {
if let Some((current, next)) = self.next_middleware.split_first() {
self.next_middleware = next;
current.handle(req, self).await.into()
} else {
self.endpoint.call(req).await.into()
}
}
})
}
}
1 change: 1 addition & 0 deletions src/redirect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ impl<T: AsRef<str>> Redirect<T> {

impl<State, T> Endpoint<State> for Redirect<T>
where
State: Send + Sync + 'static,
T: AsRef<str> + Send + Sync + 'static,
{
fn call<'a>(&'a self, _req: Request<State>) -> BoxFuture<'a, crate::Result<Response>> {
Expand Down
16 changes: 3 additions & 13 deletions src/response.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use std::convert::TryInto;
use std::fmt::Debug;
use std::ops::Index;
use std::sync::Arc;

use crate::http::cookies::Cookie;
use crate::http::headers::{self, HeaderName, HeaderValues, ToHeaderValues};
Expand Down Expand Up @@ -36,16 +35,6 @@ impl Response {
}
}

/// Create a new instance from an `http_types::Error`.
#[must_use]
pub fn from_error(err: Error) -> Self {
let res = http::Response::from_error(err);
Self {
res,
cookie_events: vec![],
}
}

/// Returns the statuscode.
#[must_use]
pub fn status(&self) -> crate::StatusCode {
Expand Down Expand Up @@ -220,7 +209,7 @@ impl Response {
}

/// Takes the `Error` from the response if one exists, replacing it with `None`.
pub fn take_error(&mut self) -> Option<Arc<Error>> {
pub fn take_error(&mut self) -> Option<Error> {
self.res.take_error()
}

Expand Down Expand Up @@ -293,7 +282,8 @@ impl From<serde_json::Value> for Response {

impl From<Error> for Response {
fn from(err: Error) -> Self {
Self::from_error(err)
let res: http::Response = err.into();
res.into()
}
}

Expand Down
8 changes: 6 additions & 2 deletions src/route.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ pub struct Route<'a, State> {
prefix: bool,
}

impl<'a, State: 'static> Route<'a, State> {
impl<'a, State: 'static + Send + Sync> Route<'a, State> {
pub(crate) fn new(router: &'a mut Router<State>, path: String) -> Route<'a, State> {
Route {
router,
Expand Down Expand Up @@ -274,7 +274,11 @@ impl<E> Clone for StripPrefixEndpoint<E> {
}
}

impl<State, E: Endpoint<State>> Endpoint<State> for StripPrefixEndpoint<E> {
impl<State, E> Endpoint<State> for StripPrefixEndpoint<E>
where
State: 'static + Send + Sync,
E: Endpoint<State>,
{
fn call<'a>(&'a self, req: crate::Request<State>) -> BoxFuture<'a, crate::Result> {
let crate::Request {
state,
Expand Down
10 changes: 7 additions & 3 deletions src/router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ pub struct Selection<'a, State> {
pub(crate) params: Params,
}

impl<State: 'static> Router<State> {
impl<State: 'static + Send + Sync> Router<State> {
pub fn new() -> Self {
Router {
method_map: HashMap::default(),
Expand Down Expand Up @@ -82,10 +82,14 @@ impl<State: 'static> Router<State> {
}
}

fn not_found_endpoint<State>(_cx: Request<State>) -> BoxFuture<'static, crate::Result> {
fn not_found_endpoint<State: Send + Sync + 'static>(
_cx: Request<State>,
) -> BoxFuture<'static, crate::Result> {
Box::pin(async move { Ok(Response::new(StatusCode::NotFound)) })
}

fn method_not_allowed<State>(_cx: Request<State>) -> BoxFuture<'static, crate::Result> {
fn method_not_allowed<State: Send + Sync + 'static>(
_cx: Request<State>,
) -> BoxFuture<'static, crate::Result> {
Box::pin(async move { Ok(Response::new(StatusCode::MethodNotAllowed)) })
}
4 changes: 2 additions & 2 deletions src/security/cors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ impl<State: Send + Sync + 'static> Middleware<State> for CorsMiddleware {

if origins.is_none() {
// This is not a CORS request if there is no Origin header
return next.run(req).await;
return Ok(next.run(req).await);
}

let origins = origins.unwrap();
Expand All @@ -156,7 +156,7 @@ impl<State: Send + Sync + 'static> Middleware<State> for CorsMiddleware {
return Ok(self.build_preflight_response(&origins).into());
}

let mut response: http_types::Response = next.run(req).await?.into();
let mut response: http_types::Response = next.run(req).await.into();

response.insert_header(
headers::ACCESS_CONTROL_ALLOW_ORIGIN,
Expand Down
3 changes: 1 addition & 2 deletions src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -454,8 +454,7 @@ impl<State: Sync + Send + 'static, InnerState: Sync + Send + 'static> Endpoint<S
next_middleware: &middleware,
};

let res = next.run(req).await?;
Ok(res)
Ok(next.run(req).await)
})
}
}
Expand Down
2 changes: 1 addition & 1 deletion tests/nested.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ async fn nested_middleware() {
next: Next<'a, State>,
) -> BoxFuture<'a, tide::Result<tide::Response>> {
Box::pin(async move {
let mut res = next.run(req).await?;
let mut res = next.run(req).await;
res.insert_header("X-Tide-Test", "1");
Ok(res)
})
Expand Down
2 changes: 1 addition & 1 deletion tests/route_middleware.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ impl<State: Send + Sync + 'static> Middleware<State> for TestMiddleware {
next: tide::Next<'a, State>,
) -> BoxFuture<'a, tide::Result<tide::Response>> {
Box::pin(async move {
let mut res = next.run(req).await?;
let mut res = next.run(req).await;
res.insert_header(self.0.clone(), self.1);
Ok(res)
})
Expand Down

0 comments on commit e2e2dab

Please sign in to comment.