Skip to content

Commit 0d048da

Browse files
committed
Merge remote-tracking branch 'sam/refactor-sentry-process' into issue-151-migrations
2 parents 6013ba0 + f55119b commit 0d048da

File tree

3 files changed

+94
-51
lines changed

3 files changed

+94
-51
lines changed

primitives/src/channel.rs

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,19 @@ pub mod postgres {
219219
}
220220
}
221221

222+
impl From<&Row> for Channel {
223+
fn from(row: &Row) -> Self {
224+
Self {
225+
id: row.get("channel_id"),
226+
creator: row.get("creator"),
227+
deposit_asset: row.get("deposit_asset"),
228+
deposit_amount: row.get("deposit_amount"),
229+
valid_until: row.get("valid_until"),
230+
spec: row.get::<_, Json<ChannelSpec>>("spec").0,
231+
}
232+
}
233+
}
234+
222235
impl ToSql for ChannelId {
223236
fn to_sql(
224237
&self,
@@ -244,17 +257,4 @@ pub mod postgres {
244257
<String as ToSql>::to_sql_checked(&string, ty, out)
245258
}
246259
}
247-
248-
impl From<&Row> for Channel {
249-
fn from(row: &Row) -> Self {
250-
Self {
251-
id: row.get("channel_id"),
252-
creator: row.get("creator"),
253-
deposit_asset: row.get("deposit_asset"),
254-
deposit_amount: row.get("deposit_amount"),
255-
valid_until: row.get("valid_until"),
256-
spec: row.get::<_, Json<ChannelSpec>>("spec").0,
257-
}
258-
}
259-
}
260260
}

sentry/src/lib.rs

Lines changed: 40 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ use regex::Regex;
1414
use routes::cfg::config;
1515
use routes::channel::{create_channel, last_approved};
1616
use slog::{error, Logger};
17+
use std::collections::HashMap;
1718

1819
pub mod middleware {
1920
pub mod auth;
@@ -102,23 +103,13 @@ impl<A: Adapter + 'static> Application<A> {
102103
Ok(req) => req,
103104
Err(error) => {
104105
error!(&self.logger, "{}", &error; "module" => "middleware-auth");
105-
return map_response_error(ResponseError::BadRequest);
106+
return map_response_error(ResponseError::BadRequest("invalid auth".into()));
106107
}
107108
};
108109

109110
let mut response = match (req.uri().path(), req.method()) {
110111
("/cfg", &Method::GET) => config(req, &self).await,
111-
("/channel", &Method::POST) => {
112-
// example with middleware
113-
// @TODO remove later
114-
let req = match chain(req, vec![config_middleware]).await {
115-
Ok(req) => req,
116-
Err(error) => {
117-
return map_response_error(error);
118-
}
119-
};
120-
create_channel(req, &self).await
121-
}
112+
("/channel", &Method::POST) => create_channel(req, &self).await,
122113
("/channel/list", &Method::GET) => Err(ResponseError::NotFound),
123114
// This is important becuase it prevents us from doing
124115
// expensive regex matching for routes without /channel
@@ -134,6 +125,15 @@ impl<A: Adapter + 'static> Application<A> {
134125
.map_or("".to_string(), |m| m.as_str().to_string())]);
135126
req.extensions_mut().insert(param);
136127

128+
// example with middleware
129+
// @TODO remove later
130+
let req = match chain(req, vec![config_middleware]).await {
131+
Ok(req) => req,
132+
Err(error) => {
133+
return map_response_error(error);
134+
}
135+
};
136+
137137
last_approved(req, &self).await
138138
} else {
139139
Err(ResponseError::NotFound)
@@ -152,7 +152,7 @@ impl<A: Adapter + 'static> Application<A> {
152152
#[derive(Debug)]
153153
pub enum ResponseError {
154154
NotFound,
155-
BadRequest,
155+
BadRequest(String),
156156
}
157157

158158
impl<T> From<T> for ResponseError
@@ -162,14 +162,14 @@ where
162162
fn from(error: T) -> Self {
163163
// @TODO use a error proper logger?
164164
println!("{:#?}", error);
165-
ResponseError::BadRequest
165+
ResponseError::BadRequest("Bad Request: try again later".into())
166166
}
167167
}
168168

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

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

183-
pub fn bad_request() -> Response<Body> {
184-
let body = Body::from("Bad Request: try again later");
183+
pub fn bad_response(response_body: String) -> Response<Body> {
184+
let mut error_response = HashMap::new();
185+
error_response.insert("error", response_body);
186+
187+
let body = Body::from(serde_json::to_string(&error_response).expect("serialise err response"));
188+
185189
let mut response = Response::new(body);
190+
response
191+
.headers_mut()
192+
.insert("Content-type", "application/json".parse().unwrap());
193+
186194
let status = response.status_mut();
187195
*status = StatusCode::BAD_REQUEST;
196+
197+
response
198+
}
199+
200+
pub fn success_response(response_body: String) -> Response<Body> {
201+
let body = Body::from(response_body);
202+
203+
let mut response = Response::new(body);
204+
response
205+
.headers_mut()
206+
.insert("Content-type", "application/json".parse().unwrap());
207+
208+
let status = response.status_mut();
209+
*status = StatusCode::OK;
210+
188211
response
189212
}
190213

sentry/src/routes/channel.rs

Lines changed: 41 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,53 +1,74 @@
11
use self::channel_list::ChannelListQuery;
22
use crate::middleware::channel::get_channel;
3+
use crate::success_response;
34
use crate::Application;
45
use crate::ResponseError;
56
use crate::RouteParams;
67
use futures::TryStreamExt;
78
use hex::FromHex;
89
use hyper::{Body, Request, Response};
910
use primitives::adapter::Adapter;
11+
use primitives::sentry::SuccessResponse;
1012
use primitives::{Channel, ChannelId};
13+
use slog::error;
1114

15+
pub async fn create_channel<A: Adapter>(
16+
req: Request<Body>,
17+
app: &Application<A>,
18+
) -> Result<Response<Body>, ResponseError> {
19+
let body = req.into_body().try_concat().await?;
1220

13-
mod channel_create {
14-
use serde::Serialize;
21+
let channel = serde_json::from_slice::<Channel>(&body)?;
1522

16-
#[derive(Serialize)]
17-
pub(crate) struct ChannelCreateResponse {
18-
pub success: bool,
23+
if let Err(e) = app.adapter.validate_channel(&channel) {
24+
return Err(ResponseError::BadRequest(e.to_string()));
1925
}
20-
}
21-
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
2626

27+
let spec = serde_json::to_string(&channel.spec)?;
28+
let result = app.pool
29+
.run(move |connection| {
30+
async move {
31+
match connection.prepare("INSERT INTO channels (channel_id, creator, deposit_asset, deposit_amount, valid_until, spec) values ($1, $2, $3, $4, $5, $6)").await {
32+
Ok(stmt) => match connection.execute(&stmt, &[&channel.id, &channel.creator, &channel.deposit_asset, &channel.deposit_amount, &channel.valid_until, &spec]).await {
33+
Ok(row) => {
34+
Ok((row, connection))
35+
},
36+
Err(e) => Err((e, connection)),
37+
},
38+
Err(e) => Err((e, connection)),
39+
}
40+
}
41+
})
42+
.await;
43+
44+
if let Err(err) = result {
45+
error!(&app.logger, "{}", &err; "module" => "create_channel");
46+
return Err(ResponseError::BadRequest(
47+
"err occured; please try again later".into(),
48+
));
49+
}
2750

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();
51+
let create_response = SuccessResponse { success: true };
3352

34-
Ok(Response::builder().status(200).body(body).unwrap())
53+
Ok(success_response(serde_json::to_string(&create_response)?))
3554
}
3655

3756
pub async fn channel_list(req: Request<Body>) -> Result<Response<Body>, ResponseError> {
3857
// @TODO: Get from Config
3958
let _channel_find_limit = 5;
4059

41-
let query =
42-
serde_urlencoded::from_str::<ChannelListQuery>(&req.uri().query().unwrap_or(""))?;
60+
let query = serde_urlencoded::from_str::<ChannelListQuery>(&req.uri().query().unwrap_or(""))?;
4361

4462
// @TODO: List all channels returned from the DB
4563
println!("{:?}", query);
4664

4765
Err(ResponseError::NotFound)
4866
}
4967

50-
pub async fn last_approved<A: Adapter>(req: Request<Body>, app: &Application<A>) -> Result<Response<Body>, ResponseError> {
68+
pub async fn last_approved<A: Adapter>(
69+
req: Request<Body>,
70+
app: &Application<A>,
71+
) -> Result<Response<Body>, ResponseError> {
5172
// get request params
5273
let route_params = req
5374
.extensions()
@@ -62,7 +83,6 @@ pub async fn last_approved<A: Adapter>(req: Request<Body>, app: &Application<A>)
6283
.unwrap())
6384
}
6485

65-
6686
mod channel_list {
6787
use chrono::{DateTime, Utc};
6888
use serde::{Deserialize, Deserializer};

0 commit comments

Comments
 (0)