1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
use self::campaign::FullCampaign;
use super::{Error, Value};
use crate::{sentry::EventType, Address, IPFS};
use chrono::{serde::ts_seconds, DateTime, Utc};
use serde::{Deserialize, Serialize};
use field::{Field, GetField};
serde_with::with_prefix!(adview_prefix "adView.");
serde_with::with_prefix!(adslot_prefix "adSlot.");
pub type Map = serde_json::Map<String, serde_json::Value>;
pub mod field;
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
#[serde(untagged)]
pub enum Get<G, V> {
#[serde(skip_deserializing)]
Getter(G),
Value(V),
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase", into = "Map")]
pub struct Input {
#[serde(flatten, with = "adview_prefix")]
pub ad_view: Option<AdView>,
#[serde(flatten)]
pub global: Global,
#[serde(flatten)]
pub campaign: Option<campaign::GetCampaign>,
#[serde(flatten)]
pub balances: Option<balances::GetBalances>,
#[serde(skip_serializing_if = "Option::is_none")]
pub ad_unit_id: Option<IPFS>,
#[serde(flatten, with = "adslot_prefix")]
pub ad_slot: Option<AdSlot>,
}
impl Input {
pub fn with_campaign(mut self, campaign: crate::Campaign) -> Self {
self.campaign = Some(Get::Getter(FullCampaign {
campaign,
event_type: self.global.event_type,
}));
self
}
pub fn with_balances(mut self, balances: crate::UnifiedMap) -> Self {
self.balances = Some(Get::Getter(balances::Getter {
balances,
publisher_id: self.global.publisher_id,
}));
self
}
pub fn try_get(&self, field: &str) -> Result<Value, Error> {
let field = field.parse::<Field>().map_err(|_| Error::UnknownVariable)?;
self.get(&field).ok_or(Error::UnknownVariable)
}
pub fn to_map(&self) -> Map {
field::FIELDS
.iter()
.filter_map(|field| {
self.get(field)
.map(|value| (field.to_string(), value.into()))
})
.collect()
}
}
impl From<Input> for Map {
fn from(input: Input) -> Self {
input.to_map()
}
}
impl GetField for Input {
type Output = Option<Value>;
type Field = Field;
fn get(&self, field: &Self::Field) -> Self::Output {
match field {
Field::AdView(ad_view) => self.ad_view.get(ad_view),
Field::Global(global) => self.global.get(global),
Field::Campaign(channel) => self.campaign.get(channel).flatten(),
Field::Balances(balances) => self.balances.get(balances).flatten(),
Field::AdSlot(ad_slot) => self.ad_slot.get(ad_slot).flatten(),
Field::AdUnit(ad_unit) => match ad_unit {
field::AdUnit::AdUnitId => self
.ad_unit_id
.as_ref()
.map(|ipfs| Value::String(ipfs.to_string())),
},
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct AdView {
pub seconds_since_campaign_impression: Option<u64>,
pub has_custom_preferences: bool,
pub navigator_language: String,
}
impl GetField for AdView {
type Output = Value;
type Field = field::AdView;
fn get(&self, field: &Self::Field) -> Self::Output {
match field {
field::AdView::SecondsSinceCampaignImpression => Value::Number(
self.seconds_since_campaign_impression
.unwrap_or(u64::MAX)
.into(),
),
field::AdView::HasCustomPreferences => Value::Bool(self.has_custom_preferences),
field::AdView::NavigatorLanguage => Value::String(self.navigator_language.clone()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct Global {
pub ad_slot_id: IPFS,
pub ad_slot_type: String,
pub publisher_id: Address,
pub country: Option<String>,
pub event_type: EventType,
#[serde(with = "ts_seconds")]
pub seconds_since_epoch: DateTime<Utc>,
#[serde(rename = "userAgentOS")]
pub user_agent_os: Option<String>,
pub user_agent_browser_family: Option<String>,
}
impl GetField for Global {
type Output = Option<Value>;
type Field = field::Global;
fn get(&self, field: &Self::Field) -> Self::Output {
match field {
field::Global::AdSlotId => Some(Value::String(self.ad_slot_id.to_string())),
field::Global::AdSlotType => Some(Value::String(self.ad_slot_type.clone())),
field::Global::PublisherId => Some(Value::String(self.publisher_id.to_string())),
field::Global::Country => self.country.clone().map(Value::String),
field::Global::EventType => Some(Value::String(self.event_type.to_string())),
field::Global::SecondsSinceEpoch => {
Some(Value::new_number(self.seconds_since_epoch.timestamp()))
}
field::Global::UserAgentOS => self.user_agent_os.clone().map(Value::String),
field::Global::UserAgentBrowserFamily => {
self.user_agent_browser_family.clone().map(Value::String)
}
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct AdSlot {
pub categories: Vec<String>,
pub hostname: String,
}
impl GetField for AdSlot {
type Output = Option<Value>;
type Field = field::AdSlot;
fn get(&self, field: &Self::Field) -> Self::Output {
match field {
field::AdSlot::Categories => Some(Value::Array(
self.categories
.iter()
.map(|string| Value::String(string.clone()))
.collect(),
)),
field::AdSlot::Hostname => Some(Value::String(self.hostname.clone())),
}
}
}
pub mod campaign {
use serde::Deserialize;
use super::{field, Get, GetField, Value};
use crate::{
sentry::EventType, targeting::get_pricing_bounds, Address, CampaignId, ToHex, UnifiedNum,
};
pub type GetCampaign = Get<FullCampaign, Values>;
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct Values {
pub advertiser_id: Address,
pub campaign_id: CampaignId,
pub campaign_seconds_active: u64,
pub campaign_seconds_duration: u64,
pub campaign_budget: UnifiedNum,
pub event_min_price: Option<UnifiedNum>,
pub event_max_price: Option<UnifiedNum>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct FullCampaign {
pub campaign: crate::Campaign,
pub(super) event_type: EventType,
}
impl GetField for Get<FullCampaign, Values> {
type Output = Option<Value>;
type Field = field::Campaign;
fn get(&self, field: &Self::Field) -> Self::Output {
match field {
field::Campaign::AdvertiserId => Some(Value::String(match self {
Get::Getter(FullCampaign { campaign, .. }) => campaign.creator.to_string(),
Get::Value(Values { advertiser_id, .. }) => advertiser_id.to_string(),
})),
field::Campaign::CampaignId => Some(Value::String(match self {
Get::Getter(FullCampaign { campaign, .. }) => campaign.id.to_hex_prefixed(),
Get::Value(Values { campaign_id, .. }) => campaign_id.to_hex_prefixed(),
})),
field::Campaign::CampaignSecondsActive => Some(Value::Number(match self {
Get::Getter(FullCampaign { campaign, .. }) => {
let duration =
chrono::Utc::now() - campaign.active.from.unwrap_or(campaign.created);
let seconds = duration
.to_std()
.map(|duration| duration.as_secs())
.unwrap_or(0);
seconds.into()
}
Get::Value(Values {
campaign_seconds_active,
..
}) => (*campaign_seconds_active).into(),
})),
field::Campaign::CampaignSecondsDuration => Some(Value::Number(match self {
Get::Getter(FullCampaign { campaign, .. }) => {
let duration =
campaign.active.to - campaign.active.from.unwrap_or(campaign.created);
let seconds = duration
.to_std()
.map(|std_duration| std_duration.as_secs())
.unwrap_or(0);
seconds.into()
}
Get::Value(Values {
campaign_seconds_duration,
..
}) => (*campaign_seconds_duration).into(),
})),
field::Campaign::CampaignBudget => Some(Value::UnifiedNum(match self {
Get::Getter(FullCampaign { campaign, .. }) => campaign.budget,
Get::Value(Values {
campaign_budget, ..
}) => *campaign_budget,
})),
field::Campaign::EventMinPrice => match self {
Get::Getter(FullCampaign {
campaign,
event_type,
}) => Some(Value::UnifiedNum(
get_pricing_bounds(campaign, event_type).min,
)),
Get::Value(Values {
event_min_price, ..
}) => event_min_price.map(Value::UnifiedNum),
},
field::Campaign::EventMaxPrice => match self {
Get::Getter(FullCampaign {
campaign,
event_type,
}) => Some(Value::UnifiedNum(
get_pricing_bounds(campaign, event_type).max,
)),
Get::Value(Values {
event_max_price, ..
}) => event_max_price.map(Value::UnifiedNum),
},
}
}
}
}
pub mod balances {
use super::{field, Get, GetField, Value};
use crate::{Address, UnifiedMap, UnifiedNum};
use serde::Deserialize;
pub type GetBalances = Get<Getter, Values>;
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct Values {
pub campaign_total_spent: UnifiedNum,
pub publisher_earned_from_campaign: UnifiedNum,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Getter {
pub balances: UnifiedMap,
pub(super) publisher_id: Address,
}
impl GetField for Get<Getter, Values> {
type Output = Option<Value>;
type Field = field::Balances;
fn get(&self, field: &Self::Field) -> Self::Output {
match field {
field::Balances::CampaignTotalSpent => match self {
Get::Getter(Getter { balances, .. }) => balances
.values()
.sum::<Option<UnifiedNum>>()
.map(Value::UnifiedNum),
Get::Value(Values {
campaign_total_spent,
..
}) => Some(Value::UnifiedNum(*campaign_total_spent)),
},
field::Balances::PublisherEarnedFromCampaign => {
Some(Value::UnifiedNum(match self {
Get::Getter(Getter {
balances,
publisher_id,
}) => balances.get(publisher_id).cloned().unwrap_or_default(),
Get::Value(Values {
publisher_earned_from_campaign,
..
}) => *publisher_earned_from_campaign,
}))
}
}
}
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::{
sentry::IMPRESSION,
test_util::{LEADER, PUBLISHER},
};
pub use crate::{
test_util::{DUMMY_CAMPAIGN as CAMPAIGN, DUMMY_IPFS as IPFS},
AdUnit, UnifiedMap,
};
use chrono::{TimeZone, Utc};
use serde_json::json;
#[test]
fn input_serialization_and_deserialization() {
let full_json = json!({
"adView.secondsSinceCampaignImpression": 10,
"adView.hasCustomPreferences": true,
"adView.navigatorLanguage": "en",
"adSlotId": "QmcUVX7fvoLMM93uN2bD3wGTH8MXSxeL8hojYfL2Lhp7mR",
"adSlotType": "legacy_300x100",
"publisherId": "0xE882ebF439207a70dDcCb39E13CA8506c9F45fD9",
"country": "BG",
"eventType": "IMPRESSION",
"secondsSinceEpoch": 1591444800,
"userAgentOS": "Ubuntu",
"userAgentBrowserFamily": "Firefox",
"adUnitId": "Qmasg8FrbuSQpjFu3kRnZF9beg8rEBFrqgi1uXDRwCbX5f",
"advertiserId": "0xaCBaDA2d5830d1875ae3D2de207A1363B316Df2F",
"campaignId": "0x936da01f9abd4d9d80c702af85c822a8",
"campaignTotalSpent": "40",
"campaignSecondsActive": 40633521,
"campaignSecondsDuration": 2509030800_u64,
"campaignBudget": "100000000000",
"eventMinPrice": "1",
"eventMaxPrice": "10",
"publisherEarnedFromCampaign": "30",
"adSlot.categories": ["IAB3", "IAB13-7", "IAB5"],
"adSlot.hostname": "adex.network",
});
let actual_date = Utc.ymd(2020, 6, 6).and_hms(12, 0, 0);
let balances: UnifiedMap = vec![(*PUBLISHER, 30.into()), (*LEADER, 10.into())]
.into_iter()
.collect();
let full_input = Input {
ad_view: Some(AdView {
seconds_since_campaign_impression: Some(10),
has_custom_preferences: true,
navigator_language: "en".into(),
}),
global: Global {
ad_slot_id: IPFS[0],
ad_slot_type: "legacy_300x100".into(),
publisher_id: *PUBLISHER,
country: Some("BG".into()),
event_type: IMPRESSION,
seconds_since_epoch: actual_date,
user_agent_os: Some("Ubuntu".into()),
user_agent_browser_family: Some("Firefox".into()),
},
campaign: Some(Get::Value(campaign::Values {
advertiser_id: CAMPAIGN.creator,
campaign_id: CAMPAIGN.id,
campaign_seconds_active: 40633521,
campaign_seconds_duration: 2509030800,
campaign_budget: CAMPAIGN.budget,
event_min_price: Some(
CAMPAIGN
.pricing(IMPRESSION)
.map(|price| price.min)
.expect("should have price"),
),
event_max_price: Some(
CAMPAIGN
.pricing(IMPRESSION)
.map(|price| price.max)
.expect("Should have price"),
),
})),
balances: Some(Get::Getter(balances::Getter {
balances,
publisher_id: *PUBLISHER,
})),
ad_unit_id: Some(IPFS[1]),
ad_slot: Some(AdSlot {
categories: vec!["IAB3".into(), "IAB13-7".into(), "IAB5".into()],
hostname: "adex.network".into(),
}),
};
let ser_actual_json = serde_json::to_value(full_input.clone()).expect("Should serialize");
pretty_assertions::assert_eq!(full_json, ser_actual_json);
pretty_assertions::assert_eq!(full_json.to_string(), ser_actual_json.to_string());
let de_actual_input =
serde_json::from_value::<Input>(ser_actual_json).expect("Should deserialize");
let expected_map: Map = full_input.into();
let actual_map: Map = de_actual_input.into();
pretty_assertions::assert_eq!(
expected_map,
actual_map,
"Comparing the output Maps of the Inputs failed"
);
}
}