Skip to content

Commit f53468a

Browse files
committed
sentry - returning a Channel
1 parent baeef5d commit f53468a

File tree

3 files changed

+61
-27
lines changed

3 files changed

+61
-27
lines changed

sentry/src/lib.rs

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
11
#![deny(clippy::all)]
22
#![deny(rust_2018_idioms)]
33

4+
use crate::db::DbPool;
45
use crate::middleware::auth;
56
use crate::middleware::cors::{cors, Cors};
6-
use bb8::Pool;
7-
use bb8_postgres::{tokio_postgres::NoTls, PostgresConnectionManager};
87
use hyper::service::{make_service_fn, service_fn};
98
use hyper::{Body, Error, Method, Request, Response, Server, StatusCode};
109
use primitives::adapter::Adapter;
@@ -45,7 +44,7 @@ pub struct Application<A: Adapter> {
4544
adapter: A,
4645
logger: Logger,
4746
redis: MultiplexedConnection,
48-
_postgres: Pool<PostgresConnectionManager<NoTls>>,
47+
pool: DbPool,
4948
_clustered: bool,
5049
port: u16,
5150
config: Config,
@@ -57,7 +56,7 @@ impl<A: Adapter + 'static> Application<A> {
5756
config: Config,
5857
logger: Logger,
5958
redis: MultiplexedConnection,
60-
postgres: Pool<PostgresConnectionManager<NoTls>>,
59+
pool: DbPool,
6160
clustered: bool,
6261
port: u16,
6362
) -> Self {
@@ -66,7 +65,7 @@ impl<A: Adapter + 'static> Application<A> {
6665
config,
6766
logger,
6867
redis,
69-
_postgres: postgres,
68+
pool,
7069
_clustered: clustered,
7170
port,
7271
}
@@ -81,17 +80,19 @@ impl<A: Adapter + 'static> Application<A> {
8180
let adapter_config = (self.adapter.clone(), self.config.clone());
8281
let redis = self.redis.clone();
8382
let logger = self.logger.clone();
83+
let pool = self.pool.clone();
8484
async move {
8585
Ok::<_, Error>(service_fn(move |req| {
8686
let adapter_config = adapter_config.clone();
8787
let redis = redis.clone();
8888
let logger = logger.clone();
89+
let pool = pool.clone();
8990
async move {
9091
Ok::<_, Error>(
9192
handle_routing(
9293
req,
9394
(&adapter_config.0, &adapter_config.1),
94-
redis,
95+
(pool, redis),
9596
&logger,
9697
)
9798
.await,
@@ -127,7 +128,7 @@ where
127128
async fn handle_routing(
128129
req: Request<Body>,
129130
(adapter, config): (&impl Adapter, &Config),
130-
redis: MultiplexedConnection,
131+
(pool, redis): (DbPool, MultiplexedConnection),
131132
logger: &Logger,
132133
) -> Response<Body> {
133134
let headers = match cors(&req) {
@@ -149,7 +150,7 @@ async fn handle_routing(
149150
let mut response = match (req.uri().path(), req.method()) {
150151
("/cfg", &Method::GET) => crate::routes::cfg::return_config(&config),
151152
(route, _) if route.starts_with("/channel") => {
152-
crate::routes::channel::handle_channel_routes(req, adapter).await
153+
crate::routes::channel::handle_channel_routes(req, (&pool, adapter)).await
153154
}
154155
_ => Err(ResponseError::NotFound),
155156
}
@@ -174,7 +175,8 @@ pub fn not_found() -> Response<Body> {
174175
response
175176
}
176177

177-
pub fn bad_request(_: Box<dyn std::error::Error>) -> Response<Body> {
178+
pub fn bad_request(err: Box<dyn std::error::Error>) -> Response<Body> {
179+
println!("{:#?}", err);
178180
let body = Body::from("Bad Request: try again later");
179181
let mut response = Response::new(body);
180182
let status = response.status_mut();

sentry/src/middleware/channel.rs

Lines changed: 27 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,45 @@
1-
use primitives::postgres::field::{BigNumPg, ChannelIdPg};
21
use crate::db::DbPool;
2+
use crate::ResponseError;
3+
use bb8::RunError;
34
use bb8_postgres::tokio_postgres::{types::Json, Row};
45
use hyper::{Body, Request};
56
use primitives::channel::ChannelId;
7+
use primitives::postgres::field::{BigNumPg, ChannelIdPg};
68
use primitives::{Channel, ChannelSpec};
7-
use std::error;
89

910
pub async fn channel_load(
1011
mut req: Request<Body>,
11-
(pool, id): (DbPool, &ChannelId),
12-
) -> Result<Request<Body>, Box<dyn error::Error>> {
13-
let channel_id = hex::encode(id);
12+
(pool, id): (&DbPool, &ChannelId),
13+
) -> Result<Request<Body>, ResponseError> {
14+
let channel = get_channel(pool, id)
15+
.await?
16+
.ok_or(ResponseError::NotFound)?;
17+
18+
req.extensions_mut().insert(channel);
19+
20+
Ok(req)
21+
}
22+
23+
// @TODO: Maybe move this to more generic place?
24+
pub async fn get_channel(
25+
pool: &DbPool,
26+
id: &ChannelId,
27+
) -> Result<Option<Channel>, RunError<bb8_postgres::tokio_postgres::Error>> {
28+
let id = hex::encode(id);
1429

15-
let channel = pool
30+
pool
1631
.run(move |connection| {
1732
async move {
18-
match connection.prepare("SELECT channel_id, creator, deposit_asset, deposit_amount, valid_until, spec FROM channels WHERE channel_id = $1").await {
19-
Ok(select) => match connection.query_one(&select, &[&channel_id]).await {
20-
Ok(row) => Ok((channel_map(&row), connection)),
21-
Err(e) => Err((e, connection)),
22-
},
33+
match connection.prepare("SELECT channel_id, creator, deposit_asset, deposit_amount, valid_until, spec FROM channels WHERE channel_id = $1 LIMIT 1").await {
34+
Ok(select) => match connection.query(&select, &[&id]).await {
35+
Ok(results) => Ok((results.get(0).map(|row| channel_map(&row)), connection)),
36+
Err(e) => Err((e, connection)),
37+
},
2338
Err(e) => Err((e, connection)),
2439
}
2540
}
2641
})
27-
.await?;
28-
29-
req.extensions_mut().insert(channel);
30-
31-
Ok(req)
42+
.await
3243
}
3344

3445
fn channel_map(row: &Row) -> Channel {

sentry/src/routes/channel.rs

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,23 @@ use futures::TryStreamExt;
22
use hyper::{Body, Method, Request, Response};
33

44
use primitives::adapter::Adapter;
5-
use primitives::Channel;
5+
use primitives::{Channel, ChannelId};
66

77
use self::channel_list::ChannelListQuery;
8+
use crate::db::DbPool;
9+
use crate::middleware::channel::get_channel;
810
use crate::ResponseError;
11+
use hex::FromHex;
12+
use lazy_static::lazy_static;
13+
use regex::Regex;
914

15+
lazy_static! {
16+
static ref CHANNEL_GET_BY_ID: Regex =
17+
Regex::new(r"^/channel/0x([a-zA-Z0-9]{64})/?$").expect("The regex should be valid");
18+
}
1019
pub async fn handle_channel_routes(
1120
req: Request<Body>,
12-
adapter: &impl Adapter,
21+
(pool, adapter): (&DbPool, &impl Adapter),
1322
) -> Result<Response<Body>, ResponseError> {
1423
// Channel Creates
1524
if req.uri().path() == "/channel" && req.method() == Method::POST {
@@ -24,6 +33,18 @@ pub async fn handle_channel_routes(
2433
return Ok(Response::builder().status(200).body(body).unwrap());
2534
}
2635

36+
// @TODO: This is only a PoC, see https://github.com/AdExNetwork/adex-validator-stack-rust/issues/9
37+
if let (Some(caps), &Method::GET) = (CHANNEL_GET_BY_ID.captures(req.uri().path()), req.method())
38+
{
39+
let channel_id = ChannelId::from_hex(caps.get(1).unwrap().as_str())?;
40+
let channel = get_channel(&pool, &channel_id).await?.unwrap();
41+
42+
return Ok(Response::builder()
43+
.header("Content-type", "application/json")
44+
.body(serde_json::to_string(&channel)?.into())
45+
.unwrap());
46+
}
47+
2748
// Channel List
2849
if req.uri().path().starts_with("/channel/list") {
2950
// @TODO: Get from Config

0 commit comments

Comments
 (0)