Skip to content

Commit c6e172c

Browse files
committed
Merge remote-tracking branch 'sam/refactor-sentry-process' into issue-151-migrations
2 parents 536fd56 + 4b0ed1a commit c6e172c

File tree

3 files changed

+68
-63
lines changed

3 files changed

+68
-63
lines changed

sentry/src/chain.rs

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,22 @@ pub async fn chain<M, MF>(
1212
middlewares: Vec<M>,
1313
) -> Result<Request<Body>, ResponseError>
1414
where
15-
MF: Future<Output = Result<Request<Body>, ResponseError>>,
15+
MF: Future<Output = Result<Request<Body>, ResponseError>> + Send,
1616
M: FnMut(Request<Body>) -> MF,
1717
{
18-
middlewares
19-
.into_iter()
20-
.try_fold(req, |req, mut mw| futures::executor::block_on(mw(req)))
18+
let mut req = Ok(req);
19+
20+
for mut mw in middlewares.into_iter() {
21+
match mw(req.unwrap()).await {
22+
Ok(r) => {
23+
req = Ok(r);
24+
}
25+
Err(e) => {
26+
req = Err(e);
27+
break;
28+
}
29+
}
30+
}
31+
32+
req
2133
}

sentry/src/lib.rs

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ use primitives::Config;
1212
use redis::aio::MultiplexedConnection;
1313
use regex::Regex;
1414
use routes::cfg::config;
15-
use routes::channel::ChannelController;
15+
use routes::channel::{create_channel, last_approved};
1616
use slog::{error, Logger};
1717

1818
pub mod middleware {
@@ -91,8 +91,6 @@ impl<A: Adapter + 'static> Application<A> {
9191
}
9292

9393
pub async fn handle_routing(&self, req: Request<Body>) -> Response<Body> {
94-
let channel_controller = ChannelController::new(&self);
95-
9694
let headers = match cors(&req) {
9795
Some(Cors::Simple(headers)) => headers,
9896
// if we have a Preflight, just return the response directly
@@ -104,7 +102,7 @@ impl<A: Adapter + 'static> Application<A> {
104102
Ok(req) => req,
105103
Err(error) => {
106104
error!(&self.logger, "{}", &error; "module" => "middleware-auth");
107-
return map_response_error(ResponseError::BadRequest(error));
105+
return map_response_error(ResponseError::BadRequest);
108106
}
109107
};
110108

@@ -119,8 +117,7 @@ impl<A: Adapter + 'static> Application<A> {
119117
return map_response_error(error);
120118
}
121119
};
122-
123-
channel_controller.channel(req).await
120+
create_channel(req, &self).await
124121
}
125122
("/channel/list", &Method::GET) => Err(ResponseError::NotFound),
126123
// This is important becuase it prevents us from doing
@@ -136,7 +133,8 @@ impl<A: Adapter + 'static> Application<A> {
136133
.get(1)
137134
.map_or("".to_string(), |m| m.as_str().to_string())]);
138135
req.extensions_mut().insert(param);
139-
channel_controller.last_approved(req).await
136+
137+
last_approved(req, &self).await
140138
} else {
141139
Err(ResponseError::NotFound)
142140
}
@@ -154,22 +152,24 @@ impl<A: Adapter + 'static> Application<A> {
154152
#[derive(Debug)]
155153
pub enum ResponseError {
156154
NotFound,
157-
BadRequest(Box<dyn std::error::Error>),
155+
BadRequest,
158156
}
159157

160158
impl<T> From<T> for ResponseError
161159
where
162160
T: std::error::Error + 'static,
163161
{
164162
fn from(error: T) -> Self {
165-
ResponseError::BadRequest(error.into())
163+
// @TODO use a error proper logger?
164+
println!("{:#?}", error);
165+
ResponseError::BadRequest
166166
}
167167
}
168168

169-
fn map_response_error(error: ResponseError) -> Response<Body> {
169+
pub fn map_response_error(error: ResponseError) -> Response<Body> {
170170
match error {
171171
ResponseError::NotFound => not_found(),
172-
ResponseError::BadRequest(error) => bad_request(error),
172+
ResponseError::BadRequest => bad_request(),
173173
}
174174
}
175175

@@ -180,8 +180,7 @@ pub fn not_found() -> Response<Body> {
180180
response
181181
}
182182

183-
pub fn bad_request(err: Box<dyn std::error::Error>) -> Response<Body> {
184-
println!("{:#?}", err);
183+
pub fn bad_request() -> Response<Body> {
185184
let body = Body::from("Bad Request: try again later");
186185
let mut response = Response::new(body);
187186
let status = response.status_mut();

sentry/src/routes/channel.rs

Lines changed: 40 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -9,66 +9,60 @@ use hyper::{Body, Request, Response};
99
use primitives::adapter::Adapter;
1010
use primitives::{Channel, ChannelId};
1111

12-
pub struct ChannelController<'a, A: Adapter> {
13-
pub app: &'a Application<A>,
14-
}
1512

16-
impl<'a, A: Adapter> ChannelController<'a, A> {
17-
pub fn new(app: &'a Application<A>) -> Self {
18-
Self { app }
13+
mod channel_create {
14+
use serde::Serialize;
15+
16+
#[derive(Serialize)]
17+
pub(crate) struct ChannelCreateResponse {
18+
pub success: bool,
1919
}
20+
}
2021

21-
pub async fn channel(&self, req: Request<Body>) -> Result<Response<Body>, ResponseError> {
22-
let body = req.into_body().try_concat().await?;
23-
let channel = serde_json::from_slice::<Channel>(&body)?;
22+
pub async fn create_channel<A: Adapter>(req: Request<Body>, app: &Application<A>) -> Result<Response<Body>, ResponseError> {
23+
let body = req.into_body().try_concat().await?;
24+
let channel = serde_json::from_slice::<Channel>(&body)?;
25+
// insert into database
2426

25-
let create_response = channel_create::ChannelCreateResponse {
26-
// @TODO get validate_channel response error
27-
success: self.app.adapter.validate_channel(&channel).unwrap_or(false),
28-
};
29-
let body = serde_json::to_string(&create_response)?.into();
3027

31-
Ok(Response::builder().status(200).body(body).unwrap())
32-
}
28+
let create_response = channel_create::ChannelCreateResponse {
29+
// @TODO get validate_channel response error
30+
success: app.adapter.validate_channel(&channel).unwrap_or(false),
31+
};
32+
let body = serde_json::to_string(&create_response)?.into();
3333

34-
pub async fn channel_list(&self, req: Request<Body>) -> Result<Response<Body>, ResponseError> {
35-
// @TODO: Get from Config
36-
let _channel_find_limit = 5;
34+
Ok(Response::builder().status(200).body(body).unwrap())
35+
}
3736

38-
let query =
39-
serde_urlencoded::from_str::<ChannelListQuery>(&req.uri().query().unwrap_or(""))?;
37+
pub async fn channel_list(req: Request<Body>) -> Result<Response<Body>, ResponseError> {
38+
// @TODO: Get from Config
39+
let _channel_find_limit = 5;
4040

41-
// @TODO: List all channels returned from the DB
42-
println!("{:?}", query);
41+
let query =
42+
serde_urlencoded::from_str::<ChannelListQuery>(&req.uri().query().unwrap_or(""))?;
4343

44-
Err(ResponseError::NotFound)
45-
}
44+
// @TODO: List all channels returned from the DB
45+
println!("{:?}", query);
4646

47-
pub async fn last_approved(&self, req: Request<Body>) -> Result<Response<Body>, ResponseError> {
48-
// get request params
49-
let route_params = req
50-
.extensions()
51-
.get::<RouteParams>()
52-
.expect("request should have route params");
53-
let channel_id = ChannelId::from_hex(route_params.index(0))?;
54-
let channel = get_channel(&self.app.pool, &channel_id).await?.unwrap();
55-
56-
Ok(Response::builder()
57-
.header("Content-type", "application/json")
58-
.body(serde_json::to_string(&channel)?.into())
59-
.unwrap())
60-
}
47+
Err(ResponseError::NotFound)
6148
}
6249

63-
mod channel_create {
64-
use serde::Serialize;
65-
66-
#[derive(Serialize)]
67-
pub(crate) struct ChannelCreateResponse {
68-
pub success: bool,
69-
}
50+
pub async fn last_approved<A: Adapter>(req: Request<Body>, app: &Application<A>) -> Result<Response<Body>, ResponseError> {
51+
// get request params
52+
let route_params = req
53+
.extensions()
54+
.get::<RouteParams>()
55+
.expect("request should have route params");
56+
let channel_id = ChannelId::from_hex(route_params.index(0))?;
57+
let channel = get_channel(&app.pool, &channel_id).await?.unwrap();
58+
59+
Ok(Response::builder()
60+
.header("Content-type", "application/json")
61+
.body(serde_json::to_string(&channel)?.into())
62+
.unwrap())
7063
}
7164

65+
7266
mod channel_list {
7367
use chrono::{DateTime, Utc};
7468
use serde::{Deserialize, Deserializer};

0 commit comments

Comments
 (0)