Skip to content

Commit 3e786e2

Browse files
committed
sentry - Session now includes the Auth, instead of the opposite + clean iterators for payouts
1 parent 7f6480d commit 3e786e2

File tree

9 files changed

+62
-96
lines changed

9 files changed

+62
-96
lines changed

sentry/src/access.rs

Lines changed: 18 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use chrono::Utc;
22
use futures::future::try_join_all;
33
use redis::aio::MultiplexedConnection;
44

5-
use crate::{AuthSession, Session};
5+
use crate::Session;
66
use primitives::event_submission::{RateLimit, Rule};
77
use primitives::sentry::Event;
88
use primitives::Channel;
@@ -38,7 +38,6 @@ impl fmt::Display for Error {
3838
// @TODO: Make pub(crate)
3939
pub async fn check_access(
4040
redis: &MultiplexedConnection,
41-
auth_session: Option<&AuthSession>,
4241
session: &Session,
4342
rate_limit: &RateLimit,
4443
channel: &Channel,
@@ -61,7 +60,7 @@ pub async fn check_access(
6160
return Err(Error::ChannelIsExpired);
6261
}
6362

64-
let (is_creator, auth_uid) = match auth_session.as_ref() {
63+
let (is_creator, auth_uid) = match &session.auth {
6564
Some(auth) => (auth.uid == channel.creator, auth.uid.to_string()),
6665
None => (false, Default::default()),
6766
};
@@ -258,19 +257,19 @@ mod test {
258257
async fn session_uid_rate_limit() {
259258
let (config, redis) = setup().await;
260259

260+
let auth = Auth {
261+
era: 0,
262+
uid: IDS["follower"].clone(),
263+
};
264+
261265
let session = Session {
266+
auth: Some(auth),
262267
ip: Default::default(),
263268
referrer_header: None,
264269
country: None,
265270
os: None,
266271
};
267272

268-
let auth = AuthSession {
269-
era: 0,
270-
uid: IDS["follower"].clone(),
271-
session: session.clone(),
272-
};
273-
274273
let rule = Rule {
275274
uids: None,
276275
rate_limit: Some(RateLimit {
@@ -281,26 +280,12 @@ mod test {
281280
let events = get_impression_events(2);
282281
let channel = get_channel(rule);
283282

284-
let response = check_access(
285-
&redis,
286-
Some(&auth),
287-
&session,
288-
&config.ip_rate_limit,
289-
&channel,
290-
&events,
291-
)
292-
.await;
283+
let response =
284+
check_access(&redis, &session, &config.ip_rate_limit, &channel, &events).await;
293285
assert_eq!(Ok(()), response);
294286

295-
let err_response = check_access(
296-
&&redis,
297-
Some(&auth),
298-
&session,
299-
&config.ip_rate_limit,
300-
&channel,
301-
&events,
302-
)
303-
.await;
287+
let err_response =
288+
check_access(&&redis, &session, &config.ip_rate_limit, &channel, &events).await;
304289
assert_eq!(
305290
Err(Error::RulesError(
306291
"rateLimit: too many requests".to_string()
@@ -313,17 +298,17 @@ mod test {
313298
async fn ip_rate_limit() {
314299
let (config, redis) = setup().await;
315300

301+
let auth = Auth {
302+
era: 0,
303+
uid: IDS["follower"].clone(),
304+
};
305+
316306
let session = Session {
317307
ip: Default::default(),
318308
referrer_header: None,
319309
country: None,
320310
os: None,
321-
};
322-
323-
let auth = AuthSession {
324-
era: 0,
325-
uid: IDS["follower"].clone(),
326-
session: session.clone(),
311+
auth: Some(auth),
327312
};
328313

329314
let rule = Rule {
@@ -337,7 +322,6 @@ mod test {
337322

338323
let err_response = check_access(
339324
&redis,
340-
Some(&auth),
341325
&session,
342326
&config.ip_rate_limit,
343327
&channel,
@@ -354,7 +338,6 @@ mod test {
354338

355339
let response = check_access(
356340
&redis,
357-
Some(&auth),
358341
&session,
359342
&config.ip_rate_limit,
360343
&channel,

sentry/src/db/analytics.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use crate::db::DbPool;
22
use crate::epoch;
3-
use crate::AuthSession;
3+
use crate::Auth;
44
use bb8::RunError;
55
use bb8_postgres::tokio_postgres::types::ToSql;
66
use chrono::Utc;
@@ -13,9 +13,9 @@ use std::collections::HashMap;
1313
use std::error::Error;
1414

1515
pub enum AnalyticsType {
16-
Advertiser { auth: AuthSession },
16+
Advertiser { auth: Auth },
1717
Global,
18-
Publisher { auth: AuthSession },
18+
Publisher { auth: Auth },
1919
}
2020

2121
pub async fn advertiser_channel_ids(

sentry/src/event_aggregator.rs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use crate::db::DbPool;
77
use crate::event_reducer;
88
use crate::Application;
99
use crate::ResponseError;
10-
use crate::{AuthSession, Session};
10+
use crate::Session;
1111
use async_std::sync::RwLock;
1212
use chrono::Utc;
1313
use lazy_static::lazy_static;
@@ -68,7 +68,6 @@ impl EventAggregator {
6868
&self,
6969
app: &'a Application<A>,
7070
channel_id: &ChannelId,
71-
auth_session: Option<&AuthSession>,
7271
session: &Session,
7372
events: &'a [Event],
7473
) -> Result<(), ResponseError> {
@@ -127,7 +126,6 @@ impl EventAggregator {
127126

128127
check_access(
129128
&app.redis,
130-
auth_session,
131129
session,
132130
&app.config.ip_rate_limit,
133131
&record.channel,

sentry/src/lib.rs

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -446,21 +446,15 @@ pub fn epoch() -> f64 {
446446
// @TODO: Make pub(crate)
447447
#[derive(Debug, Clone)]
448448
pub struct Session {
449+
pub auth: Option<Auth>,
449450
pub ip: Option<String>,
450451
pub country: Option<String>,
451452
pub referrer_header: Option<String>,
452453
pub os: Option<String>,
453454
}
454455

455456
#[derive(Debug, Clone)]
456-
pub struct AuthSession {
457+
pub struct Auth {
457458
pub era: i64,
458459
pub uid: ValidatorId,
459-
pub session: Session,
460-
}
461-
462-
impl AsRef<Session> for AuthSession {
463-
fn as_ref(&self) -> &Session {
464-
&self.session
465-
}
466460
}

sentry/src/middleware/auth.rs

Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use redis::aio::MultiplexedConnection;
66

77
use primitives::adapter::{Adapter, Session as AdapterSession};
88

9-
use crate::{AuthSession, Session};
9+
use crate::{Auth, Session};
1010

1111
/// Check `Authorization` header for `Bearer` scheme with `Adapter::session_from_token`.
1212
/// If the `Adapter` fails to create an `AdapterSession`, `ResponseError::BadRequest` will be returned.
@@ -21,15 +21,6 @@ pub(crate) async fn for_request(
2121
.map(|hv| hv.to_str().ok().map(ToString::to_string))
2222
.flatten();
2323

24-
let session = Session {
25-
ip: get_request_ip(&req),
26-
country: None,
27-
referrer_header: referrer,
28-
os: None,
29-
};
30-
31-
req.extensions_mut().insert(session.clone());
32-
3324
let authorization = req.headers().get(AUTHORIZATION);
3425

3526
let prefix = "Bearer ";
@@ -73,13 +64,20 @@ pub(crate) async fn for_request(
7364
}
7465
};
7566

76-
let auth = AuthSession {
67+
let auth = Auth {
7768
era: adapter_session.era,
7869
uid: adapter_session.uid,
79-
session,
8070
};
8171

82-
req.extensions_mut().insert(auth);
72+
let session = Session {
73+
ip: get_request_ip(&req),
74+
country: None,
75+
referrer_header: referrer,
76+
os: None,
77+
auth: Some(auth),
78+
};
79+
80+
req.extensions_mut().insert(session);
8381
}
8482

8583
Ok(req)
@@ -134,7 +132,7 @@ mod test {
134132
.expect("Handling the Request shouldn't have failed");
135133

136134
assert!(
137-
no_auth.extensions().get::<AuthSession>().is_none(),
135+
no_auth.extensions().get::<Auth>().is_none(),
138136
"There shouldn't be a Session in the extensions"
139137
);
140138

@@ -147,7 +145,7 @@ mod test {
147145
.await
148146
.expect("Handling the Request shouldn't have failed");
149147
assert!(
150-
incorrect_auth.extensions().get::<AuthSession>().is_none(),
148+
incorrect_auth.extensions().get::<Auth>().is_none(),
151149
"There shouldn't be a Session in the extensions"
152150
);
153151

@@ -180,7 +178,7 @@ mod test {
180178
.expect("Valid requests should succeed");
181179
let session = altered_request
182180
.extensions()
183-
.get::<AuthSession>()
181+
.get::<Auth>()
184182
.expect("There should be a Session set inside the request");
185183

186184
assert_eq!(IDS["leader"], session.uid);

sentry/src/payout.rs

Lines changed: 8 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -34,24 +34,18 @@ fn payout(
3434
min_price: BigNum,
3535
publisher: &ValidatorId,
3636
) -> BigNum {
37-
let matching_rules: Vec<&PriceMultiplicationRules> = rules
38-
.iter()
39-
.filter(|&rule| match_rule(rule, &event, &session, &publisher))
40-
.collect();
41-
let fixed_amount_rule = matching_rules
42-
.iter()
43-
.find(|&rule| rule.amount.is_some())
44-
.map(|&rule| rule.amount.as_ref().expect("should have value"));
37+
let fixed_amount_rule = rules.iter().find_map(|rule| {
38+
match (match_rule(rule, &event, &session, &publisher), &rule.amount) {
39+
(true, Some(amount)) => rule.amount.clone(),
40+
_ => None,
41+
}
42+
});
4543

4644
let price_by_rules = match fixed_amount_rule {
47-
Some(amount) => amount.clone(),
45+
Some(amount) => amount,
4846
None => {
4947
let exponent: f64 = 10.0;
50-
let multiplier = rules
51-
.iter()
52-
.filter(|&rule| rule.multiplier.is_some())
53-
.map(|rule| rule.multiplier.expect("should have value"))
54-
.fold(1.0, |result, i| result * i);
48+
let multiplier = rules.iter().filter_map(|&rule| rule.multiplier).product();
5549
let value: u64 = (multiplier * exponent.powi(18)) as u64;
5650
let result = min_price * BigNum::from(value);
5751

sentry/src/routes/analytics.rs

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
use crate::db::analytics::{
22
advertiser_channel_ids, get_advanced_reports, get_analytics, AnalyticsType,
33
};
4-
use crate::success_response;
54
use crate::Application;
6-
use crate::AuthSession;
5+
use crate::Auth;
76
use crate::ResponseError;
87
use crate::RouteParams;
8+
use crate::{success_response, Session};
99
use hyper::{Body, Request, Response};
1010
use primitives::adapter::Adapter;
1111
use primitives::analytics::{AnalyticsQuery, AnalyticsResponse};
@@ -17,11 +17,13 @@ pub async fn publisher_analytics<A: Adapter>(
1717
req: Request<Body>,
1818
app: &Application<A>,
1919
) -> Result<Response<Body>, ResponseError> {
20-
let sess = req.extensions().get::<AuthSession>();
20+
let session = req
21+
.extensions()
22+
.get::<Session>()
23+
.ok_or(ResponseError::Unauthorized)?;
24+
let auth = session.auth.ok_or(ResponseError::Unauthorized)?;
2125

22-
let analytics_type = AnalyticsType::Publisher {
23-
auth: sess.cloned().ok_or(ResponseError::Unauthorized)?,
24-
};
26+
let analytics_type = AnalyticsType::Publisher { auth };
2527

2628
process_analytics(req, app, analytics_type)
2729
.await
@@ -65,7 +67,7 @@ pub async fn advertiser_analytics<A: Adapter>(
6567
req: Request<Body>,
6668
app: &Application<A>,
6769
) -> Result<Response<Body>, ResponseError> {
68-
let sess = req.extensions().get::<AuthSession>();
70+
let sess = req.extensions().get::<Auth>();
6971
let analytics_type = AnalyticsType::Advertiser {
7072
auth: sess.ok_or(ResponseError::Unauthorized)?.to_owned(),
7173
};
@@ -110,10 +112,7 @@ pub async fn advanced_analytics<A: Adapter>(
110112
req: Request<Body>,
111113
app: &Application<A>,
112114
) -> Result<Response<Body>, ResponseError> {
113-
let auth = req
114-
.extensions()
115-
.get::<AuthSession>()
116-
.expect("auth is required");
115+
let auth = req.extensions().get::<Auth>().expect("auth is required");
117116
let advertiser_channels = advertiser_channel_ids(&app.pool, &auth.uid).await?;
118117

119118
let query = serde_urlencoded::from_str::<AnalyticsQuery>(&req.uri().query().unwrap_or(""))?;

sentry/src/routes/channel.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use crate::success_response;
55
use crate::Application;
66
use crate::ResponseError;
77
use crate::RouteParams;
8-
use crate::{AuthSession, Session};
8+
use crate::{Auth, Session};
99
use bb8::RunError;
1010
use bb8_postgres::tokio_postgres::error;
1111
use futures::future::try_join_all;
@@ -184,7 +184,7 @@ pub async fn insert_events<A: Adapter + 'static>(
184184
) -> Result<Response<Body>, ResponseError> {
185185
let (req_head, req_body) = req.into_parts();
186186

187-
let auth_session = req_head.extensions.get::<AuthSession>();
187+
let auth_session = req_head.extensions.get::<Auth>();
188188
let session = req_head
189189
.extensions
190190
.get::<Session>()
@@ -205,7 +205,7 @@ pub async fn insert_events<A: Adapter + 'static>(
205205
.ok_or_else(|| ResponseError::BadRequest("invalid request".to_string()))?;
206206

207207
app.event_aggregator
208-
.record(app, &channel_id, auth_session, session, &events)
208+
.record(app, &channel_id, session, &events)
209209
.await?;
210210

211211
Ok(Response::builder()
@@ -220,7 +220,7 @@ pub async fn create_validator_messages<A: Adapter + 'static>(
220220
) -> Result<Response<Body>, ResponseError> {
221221
let session = req
222222
.extensions()
223-
.get::<AuthSession>()
223+
.get::<Auth>()
224224
.expect("auth request session")
225225
.to_owned();
226226

0 commit comments

Comments
 (0)