Skip to content

Commit 5ccc395

Browse files
authored
Merge pull request #311 from AdExNetwork/channel-and-channel_spec-targeting_rules_fields
Channel and ChannelSpec targeting_rules fields
2 parents 6e07526 + f37b121 commit 5ccc395

File tree

9 files changed

+54
-17
lines changed

9 files changed

+54
-17
lines changed

adapter/src/ethereum.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -669,12 +669,14 @@ mod test {
669669
deposit_asset: eth_checksum::checksum(&format!("{:?}", token_contract.address())),
670670
deposit_amount: 2_000.into(),
671671
valid_until: Utc::now() + Duration::days(2),
672+
targeting_rules: vec![],
672673
spec: ChannelSpec {
673674
title: None,
674675
validators: SpecValidators::new(leader_validator_desc, follower_validator_desc),
675676
max_per_impression: 10.into(),
676677
min_per_impression: 10.into(),
677678
targeting: vec![],
679+
targeting_rules: vec![],
678680
min_targeting_score: None,
679681
event_submission: Some(EventSubmission { allow: vec![] }),
680682
created: Utc::now(),

primitives/src/channel.rs

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,16 @@
11
use std::error::Error;
22
use std::fmt;
3+
use std::ops::Deref;
34

45
use chrono::serde::{ts_milliseconds, ts_milliseconds_option, ts_seconds};
56
use chrono::{DateTime, Utc};
67
use serde::{Deserialize, Deserializer, Serialize};
78
use serde_hex::{SerHex, StrictPfx};
89

9-
use crate::big_num::BigNum;
10-
use crate::{AdUnit, EventSubmission, TargetingTag, ValidatorDesc, ValidatorId};
10+
use crate::{
11+
targeting::Rule, AdUnit, BigNum, EventSubmission, TargetingTag, ValidatorDesc, ValidatorId,
12+
};
1113
use hex::{FromHex, FromHexError};
12-
use std::ops::Deref;
1314

1415
#[derive(Serialize, Deserialize, PartialEq, Eq, Copy, Clone, Hash)]
1516
#[serde(transparent)]
@@ -84,6 +85,8 @@ pub struct Channel {
8485
pub deposit_amount: BigNum,
8586
#[serde(with = "ts_seconds")]
8687
pub valid_until: DateTime<Utc>,
88+
#[serde(default)]
89+
pub targeting_rules: Vec<Rule>,
8790
pub spec: ChannelSpec,
8891
}
8992

@@ -171,6 +174,8 @@ pub struct ChannelSpec {
171174
/// An array of AdUnit (optional)
172175
#[serde(default, skip_serializing_if = "Vec::is_empty")]
173176
pub ad_units: Vec<AdUnit>,
177+
#[serde(default)]
178+
pub targeting_rules: Vec<Rule>,
174179
#[serde(default, skip_serializing_if = "Vec::is_empty")]
175180
pub price_multiplication_rules: Vec<PriceMultiplicationRules>,
176181
#[serde(default)]
@@ -339,6 +344,7 @@ impl Error for ChannelError {
339344
pub mod postgres {
340345
use super::ChannelId;
341346
use super::{Channel, ChannelSpec};
347+
use crate::targeting::Rule;
342348
use bytes::BytesMut;
343349
use hex::FromHex;
344350
use postgres_types::{accepts, to_sql_checked, FromSql, IsNull, Json, ToSql, Type};
@@ -353,6 +359,7 @@ pub mod postgres {
353359
deposit_asset: row.get("deposit_asset"),
354360
deposit_amount: row.get("deposit_amount"),
355361
valid_until: row.get("valid_until"),
362+
targeting_rules: row.get::<_, Json<Vec<Rule>>>("targeting_rules").0,
356363
spec: row.get::<_, Json<ChannelSpec>>("spec").0,
357364
}
358365
}

primitives/src/targeting/eval.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -587,6 +587,26 @@ fn math_operator(lhs: Number, rhs: Number, ops: MathOperator) -> Result<Number,
587587
}
588588
}
589589

590+
#[cfg(feature = "postgres")]
591+
pub mod postgres {
592+
use super::*;
593+
use bytes::BytesMut;
594+
use postgres_types::{accepts, to_sql_checked, IsNull, Json, ToSql, Type};
595+
use std::error::Error;
596+
597+
impl ToSql for Rule {
598+
fn to_sql(
599+
&self,
600+
ty: &Type,
601+
w: &mut BytesMut,
602+
) -> Result<IsNull, Box<dyn Error + Sync + Send>> {
603+
Json(self).to_sql(ty, w)
604+
}
605+
606+
accepts!(JSONB);
607+
to_sql_checked!();
608+
}
609+
}
590610
#[cfg(test)]
591611
mod test {
592612
use super::*;

primitives/src/util/tests/prep_db.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,13 +64,15 @@ lazy_static! {
6464
creator: ValidatorId::try_from("033ed90e0fec3f3ea1c9b005c724d704501e0196").expect("Should be valid ValidatorId"),
6565
deposit_asset: "0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359".to_string(),
6666
deposit_amount: 1_000.into(),
67+
targeting_rules: vec![],
6768
// UNIX timestamp for 2100-01-01
6869
valid_until: Utc.timestamp(4_102_444_800, 0),
6970
spec: ChannelSpec {
7071
title: None,
7172
validators: SpecValidators::new(DUMMY_VALIDATOR_LEADER.clone(), DUMMY_VALIDATOR_FOLLOWER.clone()),
7273
max_per_impression: 10.into(),
7374
min_per_impression: 1.into(),
75+
targeting_rules: vec![],
7476
targeting: vec![],
7577
min_targeting_score: None,
7678
event_submission: Some(EventSubmission { allow: vec![] }),
Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
1-
INSERT INTO
2-
channels
3-
VALUES
1+
INSERT INTO
2+
channels (id, creator, deposit_asset, deposit_amount, valid_until, targeting_rules, spec)
3+
VALUES
44
(
5-
'0x061d5e2a67d0a9a10f1c732bca12a676d83f79663a396f7d87b3e30b9b411088',
6-
'0x033ed90e0fec3f3ea1c9b005c724d704501e0196',
7-
'0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359',
5+
'0x061d5e2a67d0a9a10f1c732bca12a676d83f79663a396f7d87b3e30b9b411088',
6+
'0x033ed90e0fec3f3ea1c9b005c724d704501e0196',
7+
'0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359',
88
'1000',
99
to_timestamp(4102444800),
10-
'{"minPerImpression":"1","maxPerImpression":"10","pricingBounds":{"CLICK":{"min":"0","max":"0"}},"withdrawPeriodStart":4073414400000,"validators":[{"id":"0xce07CbB7e054514D590a0262C93070D838bFBA2e","url":"http://localhost:8005","fee":"100"},{"id":"0xC91763D7F14ac5c5dDfBCD012e0D2A61ab9bDED3","url":"http://localhost:8006","fee":"100"}]}'
11-
);
10+
'[]',
11+
'{"targeting_rules": [], "minPerImpression":"1","maxPerImpression":"10","created":1564383600000,"pricingBounds":{"CLICK":{"min":"0","max":"0"}},"withdrawPeriodStart":4073414400000,"validators":[{"id":"0xce07CbB7e054514D590a0262C93070D838bFBA2e","url":"http://localhost:8005","fee":"100"},{"id":"0xC91763D7F14ac5c5dDfBCD012e0D2A61ab9bDED3","url":"http://localhost:8006","fee":"100"}]}'
12+
);
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
ALTER TABLE channels DROP COLUMN targeting_rules;
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
ALTER TABLE channels ADD COLUMN targeting_rules JSONB NOT NULL DEFAULT '[]';

sentry/src/db.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,10 @@ pub async fn setup_migrations(environment: &str) {
8484
};
8585
}
8686

87-
let mut migrations = vec![make_migration!("20190806011140_initial-tables")];
87+
let mut migrations = vec![
88+
make_migration!("20190806011140_initial-tables"),
89+
make_migration!("20200625092729_channel-targeting-rules"),
90+
];
8891

8992
if environment == "development" {
9093
// seeds database tables for testing

sentry/src/db/channel.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ pub async fn get_channel_by_id(
1414
pool
1515
.run(move |connection| {
1616
async move {
17-
match connection.prepare("SELECT id, creator, deposit_asset, deposit_amount, valid_until, spec FROM channels WHERE id = $1 LIMIT 1").await {
17+
match connection.prepare("SELECT id, creator, deposit_asset, deposit_amount, valid_until, targeting_rules, spec FROM channels WHERE id = $1 LIMIT 1").await {
1818
Ok(select) => match connection.query(&select, &[&id]).await {
1919
Ok(results) => Ok((results.get(0).map(Channel::from), connection)),
2020
Err(e) => Err((e, connection)),
@@ -35,7 +35,7 @@ pub async fn get_channel_by_id_and_validator(
3535
.run(move |connection| {
3636
async move {
3737
let validator = serde_json::Value::from_str(&format!(r#"[{{"id": "{}"}}]"#, validator_id)).expect("Not a valid json");
38-
let query = "SELECT id, creator, deposit_asset, deposit_amount, valid_until, spec FROM channels WHERE id = $1 AND spec->'validators' @> $2 LIMIT 1";
38+
let query = "SELECT id, creator, deposit_asset, deposit_amount, valid_until, targeting_rules, spec FROM channels WHERE id = $1 AND spec->'validators' @> $2 LIMIT 1";
3939
match connection.prepare(query).await {
4040
Ok(select) => {
4141
match connection.query(&select, &[&id, &validator]).await {
@@ -57,8 +57,8 @@ pub async fn insert_channel(
5757
pool
5858
.run(move |connection| {
5959
async move {
60-
match connection.prepare("INSERT INTO channels (id, creator, deposit_asset, deposit_amount, valid_until, spec) values ($1, $2, $3, $4, $5, $6)").await {
61-
Ok(stmt) => match connection.execute(&stmt, &[&channel.id, &channel.creator, &channel.deposit_asset, &channel.deposit_amount, &channel.valid_until, &channel.spec]).await {
60+
match connection.prepare("INSERT INTO channels (id, creator, deposit_asset, deposit_amount, valid_until, targeting_rules, spec) values ($1, $2, $3, $4, $5, $6, $7)").await {
61+
Ok(stmt) => match connection.execute(&stmt, &[&channel.id, &channel.creator, &channel.deposit_asset, &channel.deposit_amount, &channel.valid_until, &channel.targeting_rules, &channel.spec]).await {
6262
Ok(row) => {
6363
let inserted = row == 1;
6464
Ok((inserted, connection))
@@ -138,7 +138,7 @@ mod list_channels {
138138
.run(move |connection| {
139139
async move {
140140
// To understand why we use Order by, see Postgres Documentation: https://www.postgresql.org/docs/8.1/queries-limit.html
141-
let statement = format!("SELECT id, creator, deposit_asset, deposit_amount, valid_until, spec FROM channels WHERE {} ORDER BY spec->>'created' DESC LIMIT {} OFFSET {}", where_clauses.join(" AND "), limit, skip);
141+
let statement = format!("SELECT id, creator, deposit_asset, deposit_amount, valid_until, targeting_rules, spec FROM channels WHERE {} ORDER BY spec->>'created' DESC LIMIT {} OFFSET {}", where_clauses.join(" AND "), limit, skip);
142142
match connection.prepare(&statement).await {
143143
Ok(stmt) => {
144144
match connection.query(&stmt, params.as_slice()).await {

0 commit comments

Comments
 (0)