Skip to content

Commit

Permalink
Add middleware Result type
Browse files Browse the repository at this point in the history
  • Loading branch information
jtgeibel committed Jan 4, 2020
1 parent 4ec4d10 commit 6f33bbe
Show file tree
Hide file tree
Showing 14 changed files with 35 additions and 53 deletions.
21 changes: 13 additions & 8 deletions src/middleware.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,22 @@
mod prelude {
pub use conduit::{Handler, Request, Response};
pub use conduit_middleware::{AroundMiddleware, Middleware};
pub use std::error::Error;

use std::error::Error;
pub type BoxError = Box<dyn Error + Send>;
pub type Result<T> = std::result::Result<T, BoxError>;
}

pub use self::app::AppMiddleware;
pub use self::current_user::CurrentUser;
pub use self::debug::*;
pub use self::ember_index_rewrite::EmberIndexRewrite;
pub use self::head::Head;
pub use prelude::Result;

use self::app::AppMiddleware;
use self::current_user::CurrentUser;
use self::debug::*;
use self::ember_index_rewrite::EmberIndexRewrite;
use self::head::Head;
use self::log_connection_pool_status::LogConnectionPoolStatus;
pub use self::security_headers::SecurityHeaders;
pub use self::static_or_continue::StaticOrContinue;
use self::security_headers::SecurityHeaders;
use self::static_or_continue::StaticOrContinue;

pub mod app;
mod block_traffic;
Expand Down
8 changes: 2 additions & 6 deletions src/middleware/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,12 @@ impl AppMiddleware {
}

impl Middleware for AppMiddleware {
fn before(&self, req: &mut dyn Request) -> Result<(), Box<dyn Error + Send>> {
fn before(&self, req: &mut dyn Request) -> Result<()> {
req.mut_extensions().insert(Arc::clone(&self.app));
Ok(())
}

fn after(
&self,
req: &mut dyn Request,
res: Result<Response, Box<dyn Error + Send>>,
) -> Result<Response, Box<dyn Error + Send>> {
fn after(&self, req: &mut dyn Request, res: Result<Response>) -> Result<Response> {
req.mut_extensions().pop::<Arc<App>>().unwrap();
res
}
Expand Down
2 changes: 1 addition & 1 deletion src/middleware/block_traffic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ impl AroundMiddleware for BlockTraffic {
}

impl Handler for BlockTraffic {
fn call(&self, req: &mut dyn Request) -> Result<Response, Box<dyn Error + Send>> {
fn call(&self, req: &mut dyn Request) -> Result<Response> {
let has_blocked_value = req
.headers()
.find(&self.header_name)
Expand Down
8 changes: 3 additions & 5 deletions src/middleware/current_user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,17 +20,15 @@ pub enum AuthenticationSource {
}

impl Middleware for CurrentUser {
fn before(&self, req: &mut dyn Request) -> Result<(), Box<dyn Error + Send>> {
fn before(&self, req: &mut dyn Request) -> Result<()> {
// Check if the request has a session cookie with a `user_id` property inside
let id = {
req.session()
.get("user_id")
.and_then(|s| s.parse::<i32>().ok())
};

let conn = req
.db_conn()
.map_err(|e| Box::new(e) as Box<dyn Error + Send>)?;
let conn = req.db_conn().map_err(|e| Box::new(e) as BoxError)?;

if let Some(id) = id {
// If it did, look for a user in the database with the given `user_id`
Expand Down Expand Up @@ -58,7 +56,7 @@ impl Middleware for CurrentUser {
})
})
.optional()
.map_err(|e| Box::new(e) as Box<dyn Error + Send>)?
.map_err(|e| Box::new(e) as BoxError)?
} else {
None
};
Expand Down
10 changes: 3 additions & 7 deletions src/middleware/debug.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,11 @@ use super::prelude::*;
pub struct Debug;

impl Middleware for Debug {
fn before(&self, req: &mut dyn Request) -> Result<(), Box<dyn Error + Send>> {
fn before(&self, req: &mut dyn Request) -> Result<()> {
DebugRequest.before(req)
}

fn after(
&self,
_req: &mut dyn Request,
res: Result<Response, Box<dyn Error + Send>>,
) -> Result<Response, Box<dyn Error + Send>> {
fn after(&self, _req: &mut dyn Request, res: Result<Response>) -> Result<Response> {
res.map(|res| {
println!(" <- {:?}", res.status);
for (k, v) in &res.headers {
Expand All @@ -29,7 +25,7 @@ impl Middleware for Debug {
pub struct DebugRequest;

impl Middleware for DebugRequest {
fn before(&self, req: &mut dyn Request) -> Result<(), Box<dyn Error + Send>> {
fn before(&self, req: &mut dyn Request) -> Result<()> {
println!(" version: {}", req.http_version());
println!(" method: {:?}", req.method());
println!(" scheme: {:?}", req.scheme());
Expand Down
2 changes: 1 addition & 1 deletion src/middleware/ember_index_rewrite.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ impl AroundMiddleware for EmberIndexRewrite {
}

impl Handler for EmberIndexRewrite {
fn call(&self, req: &mut dyn Request) -> Result<Response, Box<dyn Error + Send>> {
fn call(&self, req: &mut dyn Request) -> Result<Response> {
// If the client is requesting html, then we've only got one page so
// rewrite the request.
let wants_html = req
Expand Down
6 changes: 1 addition & 5 deletions src/middleware/ensure_well_formed_500.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,7 @@ use std::collections::HashMap;
pub struct EnsureWellFormed500;

impl Middleware for EnsureWellFormed500 {
fn after(
&self,
_: &mut dyn Request,
res: Result<Response, Box<dyn Error + Send>>,
) -> Result<Response, Box<dyn Error + Send>> {
fn after(&self, _: &mut dyn Request, res: Result<Response>) -> Result<Response> {
res.or_else(|_| {
let body = "Internal Server Error";
let mut headers = HashMap::new();
Expand Down
2 changes: 1 addition & 1 deletion src/middleware/head.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ impl AroundMiddleware for Head {
}

impl Handler for Head {
fn call(&self, req: &mut dyn Request) -> Result<Response, Box<dyn Error + Send>> {
fn call(&self, req: &mut dyn Request) -> Result<Response> {
if req.method() == Method::Head {
let mut req = RequestProxy::rewrite_method(req, Method::Get);
self.handler
Expand Down
8 changes: 2 additions & 6 deletions src/middleware/log_connection_pool_status.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ impl LogConnectionPoolStatus {
}

impl Middleware for LogConnectionPoolStatus {
fn before(&self, _: &mut dyn Request) -> Result<(), Box<dyn Error + Send>> {
fn before(&self, _: &mut dyn Request) -> Result<()> {
let mut last_log_time = self
.last_log_time
.lock()
Expand All @@ -45,11 +45,7 @@ impl Middleware for LogConnectionPoolStatus {
Ok(())
}

fn after(
&self,
_: &mut dyn Request,
res: Result<Response, Box<dyn Error + Send>>,
) -> Result<Response, Box<dyn Error + Send>> {
fn after(&self, _: &mut dyn Request, res: Result<Response>) -> Result<Response> {
self.in_flight_requests.fetch_sub(1, Ordering::SeqCst);
res
}
Expand Down
2 changes: 1 addition & 1 deletion src/middleware/log_request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ impl AroundMiddleware for LogRequests {
}

impl Handler for LogRequests {
fn call(&self, req: &mut dyn Request) -> Result<Response, Box<dyn Error + Send>> {
fn call(&self, req: &mut dyn Request) -> Result<Response> {
let request_start = Instant::now();
let res = self.handler.as_ref().unwrap().call(req);
let (level, response_code) = match res {
Expand Down
2 changes: 1 addition & 1 deletion src/middleware/require_user_agent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ impl AroundMiddleware for RequireUserAgent {
}

impl Handler for RequireUserAgent {
fn call(&self, req: &mut dyn Request) -> Result<Response, Box<dyn Error + Send>> {
fn call(&self, req: &mut dyn Request) -> Result<Response> {
let has_user_agent = request_header(req, "User-Agent") != "";
let is_download = req.path().ends_with("download");
if !has_user_agent && !is_download {
Expand Down
6 changes: 1 addition & 5 deletions src/middleware/security_headers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,11 +57,7 @@ impl SecurityHeaders {
}

impl Middleware for SecurityHeaders {
fn after(
&self,
_: &mut dyn Request,
mut res: Result<Response, Box<dyn Error + Send>>,
) -> Result<Response, Box<dyn Error + Send>> {
fn after(&self, _: &mut dyn Request, mut res: Result<Response>) -> Result<Response> {
if let Ok(ref mut response) = res {
response.headers.extend(self.headers.clone());
}
Expand Down
2 changes: 1 addition & 1 deletion src/middleware/static_or_continue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ impl AroundMiddleware for StaticOrContinue {
}

impl Handler for StaticOrContinue {
fn call(&self, req: &mut dyn Request) -> Result<Response, Box<dyn Error + Send>> {
fn call(&self, req: &mut dyn Request) -> Result<Response> {
match self.static_handler.call(req) {
Ok(ref resp) if resp.status.0 == 404 => {}
ret => return ret,
Expand Down
9 changes: 4 additions & 5 deletions src/router.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use std::error::Error;
use std::sync::Arc;

use conduit::{Handler, Request, Response};
Expand All @@ -7,7 +6,7 @@ use conduit_router::{RequestParams, RouteBuilder};
use crate::controllers::*;
use crate::util::errors::{std_error, AppError, AppResult, NotFound};
use crate::util::RequestProxy;
use crate::{App, Env};
use crate::{middleware, App, Env};

pub fn build_router(app: &App) -> R404 {
let mut api_router = RouteBuilder::new();
Expand Down Expand Up @@ -136,7 +135,7 @@ pub fn build_router(app: &App) -> R404 {
struct C(pub fn(&mut dyn Request) -> AppResult<Response>);

impl Handler for C {
fn call(&self, req: &mut dyn Request) -> Result<Response, Box<dyn Error + Send>> {
fn call(&self, req: &mut dyn Request) -> middleware::Result<Response> {
let C(f) = *self;
match f(req) {
Ok(resp) => Ok(resp),
Expand All @@ -151,7 +150,7 @@ impl Handler for C {
struct R<H>(pub Arc<H>);

impl<H: Handler> Handler for R<H> {
fn call(&self, req: &mut dyn Request) -> Result<Response, Box<dyn Error + Send>> {
fn call(&self, req: &mut dyn Request) -> middleware::Result<Response> {
let path = req.params()["path"].to_string();
let R(ref sub_router) = *self;
sub_router.call(&mut RequestProxy::rewrite_path(req, &path))
Expand All @@ -163,7 +162,7 @@ impl<H: Handler> Handler for R<H> {
pub struct R404(pub RouteBuilder);

impl Handler for R404 {
fn call(&self, req: &mut dyn Request) -> Result<Response, Box<dyn Error + Send>> {
fn call(&self, req: &mut dyn Request) -> middleware::Result<Response> {
let R404(ref router) = *self;
match router.recognize(&req.method(), req.path()) {
Ok(m) => {
Expand Down

0 comments on commit 6f33bbe

Please sign in to comment.