Skip to content

Commit 344df80

Browse files
authored
Issue #48 travis-ci, Rustfmt & Clippy (#49)
* Cargo make `Makefile.toml` * domain - channel - remove unused import * Add `.travis.yml` * run `rustfmt` * Remove `Makefile.toml` and simplify `.travis.yml` * `.travis.yml` - add env. to run `rustfmt` & `clippy` in `ci-flow` * `.travis.yml` - remove `cache` & add Makefile.toml to override clippy and fail on warnings * Makefile - override only the `args` of `tasks.clippy` * README - add badge + fix some typos * Makefile.toml - add `CARGO_MAKE_EXTEND_WORKSPACE_MAKEFILE = true` to apply the same rules for the `workspace` crates * domain - channel - Fix merge conflict * .travis.yml - conditionally install `cargo-make` and `cache: cargo` * fix `clippy` warnings * run `rustfmt`
1 parent 5faa3fc commit 344df80

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

43 files changed

+342
-208
lines changed

.travis.yml

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
language: rust
2+
rust:
3+
- nightly-2019-05-08
4+
cache: cargo
5+
env:
6+
global:
7+
- CARGO_MAKE_RUN_CHECK_FORMAT="true"
8+
- CARGO_MAKE_RUN_CLIPPY="true"
9+
matrix:
10+
fast_finish: true
11+
install:
12+
- if [[ $(cargo list | grep -c make) == 0 ]]; then cargo install --debug cargo-make ; else echo "Cargo make already installed, continuing..."; fi
13+
- cargo make ci-flow

Makefile.toml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
[env]
2+
CARGO_MAKE_EXTEND_WORKSPACE_MAKEFILE = "true"
3+
4+
[tasks.clippy]
5+
args = ["clippy", "--all-features", "--", "-D", "warnings"]

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# adex-validator-stack-rust
1+
# Adex Validator Stack in Rust [![Build Status](https://travis-ci.com/AdExNetwork/adex-validator-stack-rust.svg?token=TBKq9g6p9sWDrzNyX4kC&branch=master)](https://travis-ci.com/AdExNetwork/adex-validator-stack-rust)
22

33
Rust implementation of the Validator Stack
44

@@ -20,7 +20,7 @@ GET `/channel/list` - get a list of all channels - TODO
2020
### Rust setup
2121

2222
- Requires `nightly 2019-05-08`, because of the new syntax for `await` and our `tower-web` dependency fails to build.
23-
We've setup `rust-toolchain` but you can manually override it as well with `rustup override set nightly-2019-04-07`.
23+
We've setup `rust-toolchain` but you can manually override it as well with `rustup override set nightly-2019-05-08`.
2424

2525
#### Linux
2626
- The crate `openssl-sys` requires `libssl-dev` and `pkg-config` for Ubuntu.

domain/src/ad_unit.rs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
1-
use chrono::{DateTime, Utc};
21
use chrono::serde::ts_milliseconds;
2+
use chrono::{DateTime, Utc};
33
use serde::{Deserialize, Serialize};
44

5-
use crate::TargetingTag;
65
use crate::util::serde::ts_milliseconds_option;
6+
use crate::TargetingTag;
77

88
#[derive(Serialize, Deserialize, Debug, Clone)]
99
#[serde(rename_all = "camelCase")]
@@ -49,5 +49,4 @@ pub struct AdUnit {
4949
/// UTC timestamp in milliseconds, changed every time modifiable property is changed
5050
#[serde(default, with = "ts_milliseconds_option")]
5151
pub modified: Option<DateTime<Utc>>,
52-
53-
}
52+
}

domain/src/bignum.rs

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,11 @@ use serde::{Deserialize, Deserializer, Serialize, Serializer};
77

88
#[derive(Serialize, Deserialize, Debug, Clone)]
99
pub struct BigNum(
10-
#[serde(deserialize_with = "biguint_from_str", serialize_with = "biguint_to_str")]
11-
BigUint
10+
#[serde(
11+
deserialize_with = "biguint_from_str",
12+
serialize_with = "biguint_to_str"
13+
)]
14+
BigUint,
1215
);
1316

1417
impl BigNum {
@@ -21,9 +24,8 @@ impl TryFrom<&str> for BigNum {
2124
type Error = super::DomainError;
2225

2326
fn try_from(num: &str) -> Result<Self, Self::Error> {
24-
let big_uint = BigUint::from_str(&num).map_err(|err| {
25-
super::DomainError::InvalidArgument(err.description().to_string())
26-
})?;
27+
let big_uint = BigUint::from_str(&num)
28+
.map_err(|err| super::DomainError::InvalidArgument(err.description().to_string()))?;
2729

2830
Ok(Self(big_uint))
2931
}
@@ -44,16 +46,16 @@ impl TryFrom<u32> for BigNum {
4446
}
4547

4648
fn biguint_from_str<'de, D>(deserializer: D) -> Result<BigUint, D::Error>
47-
where
48-
D: Deserializer<'de>,
49+
where
50+
D: Deserializer<'de>,
4951
{
5052
let num = String::deserialize(deserializer)?;
5153
Ok(BigUint::from_str(&num).map_err(serde::de::Error::custom)?)
5254
}
5355

5456
fn biguint_to_str<S>(num: &BigUint, serializer: S) -> Result<S::Ok, S::Error>
55-
where
56-
S: Serializer
57+
where
58+
S: Serializer,
5759
{
5860
serializer.serialize_str(&num.to_str_radix(10))
5961
}

domain/src/channel.rs

Lines changed: 30 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
use std::convert::TryFrom;
22

3-
use chrono::{DateTime, Utc};
43
use chrono::serde::{ts_milliseconds, ts_seconds};
5-
use hex::{FromHex, ToHex};
4+
use chrono::{DateTime, Utc};
5+
use hex::FromHex;
66
use serde::{Deserialize, Serialize};
77
use serde_hex::{SerHex, StrictPfx};
88

9-
use crate::{AdUnit, Asset, DomainError, EventSubmission, TargetingTag, ValidatorDesc};
109
use crate::bignum::BigNum;
1110
use crate::util::serde::ts_milliseconds_option;
11+
use crate::{AdUnit, Asset, DomainError, EventSubmission, TargetingTag, ValidatorDesc};
1212

1313
#[cfg(feature = "repositories")]
1414
pub use self::repository::ChannelRepository;
@@ -55,7 +55,9 @@ impl TryFrom<&str> for ChannelId {
5555
fn try_from(value: &str) -> Result<Self, Self::Error> {
5656
let bytes = value.as_bytes();
5757
if bytes.len() != 32 {
58-
return Err(DomainError::InvalidArgument("The value of the id should have exactly 32 bytes".to_string()));
58+
return Err(DomainError::InvalidArgument(
59+
"The value of the id should have exactly 32 bytes".to_string(),
60+
));
5961
}
6062
let mut id = [0; 32];
6163
id.copy_from_slice(&bytes[..32]);
@@ -83,9 +85,12 @@ impl ChannelId {
8385
pub fn try_from_hex(hex: &str) -> Result<Self, DomainError> {
8486
let s = hex.trim_start_matches("0x");
8587

86-
let bytes: Vec<u8> = Vec::from_hex(s).map_err(|err| DomainError::InvalidArgument(err.to_string()))?;
88+
let bytes: Vec<u8> =
89+
Vec::from_hex(s).map_err(|err| DomainError::InvalidArgument(err.to_string()))?;
8790
if bytes.len() != 32 {
88-
return Err(DomainError::InvalidArgument("The value of the id should have exactly 32 bytes".to_string()));
91+
return Err(DomainError::InvalidArgument(
92+
"The value of the id should have exactly 32 bytes".to_string(),
93+
));
8994
}
9095

9196
let mut id = [0; 32];
@@ -137,7 +142,11 @@ pub struct ChannelSpec {
137142
pub created: DateTime<Utc>,
138143
/// A millisecond timestamp representing the time you want this campaign to become active (optional)
139144
/// Used by the AdViewManager
140-
#[serde(default, skip_serializing_if = "Option::is_none", with = "ts_milliseconds_option")]
145+
#[serde(
146+
default,
147+
skip_serializing_if = "Option::is_none",
148+
with = "ts_milliseconds_option"
149+
)]
141150
pub active_from: Option<DateTime<Utc>>,
142151
/// A random number to ensure the campaignSpec hash is unique
143152
pub nonce: BigNum,
@@ -166,20 +175,25 @@ pub struct ChannelListParams {
166175
}
167176

168177
impl ChannelListParams {
169-
pub fn new(valid_until_ge: DateTime<Utc>, limit: u32, page: u32, validator: Option<String>) -> Result<Self, DomainError> {
178+
pub fn new(
179+
valid_until_ge: DateTime<Utc>,
180+
limit: u32,
181+
page: u32,
182+
validator: Option<String>,
183+
) -> Result<Self, DomainError> {
170184
if page < 1 {
171-
return Err(DomainError::InvalidArgument("Page should be >= 1".to_string()));
185+
return Err(DomainError::InvalidArgument(
186+
"Page should be >= 1".to_string(),
187+
));
172188
}
173189

174190
if limit < 1 {
175-
return Err(DomainError::InvalidArgument("Limit should be >= 1".to_string()));
191+
return Err(DomainError::InvalidArgument(
192+
"Limit should be >= 1".to_string(),
193+
));
176194
}
177195

178-
let validator = validator
179-
.and_then(|s| match s.is_empty() {
180-
true => None,
181-
false => Some(s),
182-
});
196+
let validator = validator.and_then(|s| if s.is_empty() { None } else { Some(s) });
183197

184198
Ok(Self {
185199
valid_until_ge,
@@ -213,4 +227,4 @@ pub mod fixtures;
213227

214228
#[cfg(test)]
215229
#[path = "./channel_test.rs"]
216-
mod test;
230+
mod test;

domain/src/channel_fixtures.rs

Lines changed: 22 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,9 @@ use chrono::{DateTime, Utc};
44
use fake::faker::*;
55

66
use crate::asset::fixtures::get_asset;
7-
use crate::BigNum;
87
use crate::fixtures::{get_targeting_tags, get_validators};
98
use crate::test_util;
9+
use crate::BigNum;
1010
use crate::ValidatorDesc;
1111

1212
use super::{Channel, ChannelId, ChannelSpec};
@@ -27,13 +27,19 @@ pub fn get_channel_id(channel_id: &str) -> ChannelId {
2727
ChannelId { id }
2828
}
2929

30-
pub fn get_channel(id: &str, valid_until: &Option<DateTime<Utc>>, spec: Option<ChannelSpec>) -> Channel {
30+
pub fn get_channel(
31+
id: &str,
32+
valid_until: &Option<DateTime<Utc>>,
33+
spec: Option<ChannelSpec>,
34+
) -> Channel {
3135
let channel_id = get_channel_id(id);
32-
let deposit_amount = BigNum::try_from(<Faker as Number>::between(100_u32, 5000_u32)).expect("BigNum error when creating from random number");
33-
let valid_until: DateTime<Utc> = valid_until.unwrap_or(test_util::time::datetime_between(&Utc::now(), None));
36+
let deposit_amount = BigNum::try_from(<Faker as Number>::between(100_u32, 5000_u32))
37+
.expect("BigNum error when creating from random number");
38+
let valid_until: DateTime<Utc> =
39+
valid_until.unwrap_or(test_util::time::datetime_between(&Utc::now(), None));
3440
let creator = <Faker as Name>::name();
3541
let deposit_asset = get_asset();
36-
let spec = spec.unwrap_or(get_channel_spec(id, ValidatorsOption::Count(3)));
42+
let spec = spec.unwrap_or_else(|| get_channel_spec(id, ValidatorsOption::Count(3)));
3743

3844
Channel {
3945
id: channel_id,
@@ -49,7 +55,8 @@ pub fn get_channels(count: usize, valid_until_ge: Option<DateTime<Utc>>) -> Vec<
4955
(1..=count)
5056
.map(|c| {
5157
// if we have a valid_until_ge, use it to generate a valid_util for each channel
52-
let valid_until = valid_until_ge.and_then(|ref dt| Some(test_util::time::datetime_between(dt, None)));
58+
let valid_until =
59+
valid_until_ge.and_then(|ref dt| Some(test_util::time::datetime_between(dt, None)));
5360
let channel_id = format!("channel {}", c);
5461

5562
get_channel(&channel_id, &valid_until, None)
@@ -77,10 +84,14 @@ pub fn get_channel_spec(prefix: &str, validators_option: ValidatorsOption) -> Ch
7784
let title_string = Some(<Faker as Lorem>::sentence(3, 4));
7885

7986
let title = take_one(&[&title_string, &None]).to_owned();
80-
let max_per_impression = BigNum::try_from(<Faker as Number>::between(250_u32, 500_u32)).expect("BigNum error when creating from random number");
81-
let min_per_impression = BigNum::try_from(<Faker as Number>::between(1_u32, 250_u32)).expect("BigNum error when creating from random number");
82-
let nonce = BigNum::try_from(<Faker as Number>::between(100_000_000_u32, 999_999_999_u32)).expect("BigNum error when creating from random number");
83-
let min_targeting_score = take_one(&[&None, &Some(<Faker as Number>::between(1, 500))]).to_owned();
87+
let max_per_impression = BigNum::try_from(<Faker as Number>::between(250_u32, 500_u32))
88+
.expect("BigNum error when creating from random number");
89+
let min_per_impression = BigNum::try_from(<Faker as Number>::between(1_u32, 250_u32))
90+
.expect("BigNum error when creating from random number");
91+
let nonce = BigNum::try_from(<Faker as Number>::between(100_000_000_u32, 999_999_999_u32))
92+
.expect("BigNum error when creating from random number");
93+
let min_targeting_score =
94+
take_one(&[&None, &Some(<Faker as Number>::between(1, 500))]).to_owned();
8495

8596
ChannelSpec {
8697
validators,
@@ -97,4 +108,4 @@ pub fn get_channel_spec(prefix: &str, validators_option: ValidatorsOption) -> Ch
97108
withdraw_period_start: Utc::now(),
98109
ad_units: Vec::new(),
99110
}
100-
}
111+
}

domain/src/channel_test.rs

Lines changed: 32 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,23 +4,44 @@ use crate::channel::ChannelId;
44

55
#[test]
66
fn coverts_str_to_channel_id() {
7-
let channel_id = ChannelId::try_from("12345678901234567890123456789012").expect("Should create ChannelId from &str with 32 len numeric value");
8-
9-
assert_eq!("12345678901234567890123456789012".as_bytes(), &channel_id.id);
10-
11-
assert!(ChannelId::try_from("1234567890123456789012345678901").is_err(), "ChannelId was created from a &str of 31 len bytes value");
12-
assert!(ChannelId::try_from("123456789012345678901234567890123").is_err(), "ChannelId was created from a &str of 33 len bytes value");
7+
let channel_id = ChannelId::try_from("12345678901234567890123456789012")
8+
.expect("Should create ChannelId from &str with 32 len numeric value");
9+
10+
assert_eq!(
11+
"12345678901234567890123456789012".as_bytes(),
12+
&channel_id.id
13+
);
14+
15+
assert!(
16+
ChannelId::try_from("1234567890123456789012345678901").is_err(),
17+
"ChannelId was created from a &str of 31 len bytes value"
18+
);
19+
assert!(
20+
ChannelId::try_from("123456789012345678901234567890123").is_err(),
21+
"ChannelId was created from a &str of 33 len bytes value"
22+
);
1323
}
1424

1525
#[test]
1626
fn compares_channel_ids() {
17-
let first = ChannelId::try_from("12345678901234567890123456789012").expect("Should create ChannelId from &str of 32 len bytes value");
27+
let first = ChannelId::try_from("12345678901234567890123456789012")
28+
.expect("Should create ChannelId from &str of 32 len bytes value");
1829
let second = ChannelId::try_from("12345678901234567890123456789012").unwrap();
1930
let first_copy = first;
2031

21-
assert_eq!(first, first.clone(), "ChannelId and it's clone should be equal to each other");
22-
assert_eq!(first, first_copy, "ChannelId and it's copy should be equal to each other");
23-
assert_eq!(first, second, "ChannelId and it's clone should be equal to each other");
32+
assert_eq!(
33+
first,
34+
first.clone(),
35+
"ChannelId and it's clone should be equal to each other"
36+
);
37+
assert_eq!(
38+
first, first_copy,
39+
"ChannelId and it's copy should be equal to each other"
40+
);
41+
assert_eq!(
42+
first, second,
43+
"ChannelId and it's clone should be equal to each other"
44+
);
2445
}
2546

2647
#[test]
@@ -36,4 +57,4 @@ fn serialize_and_deserialize_channel_id() {
3657

3758
let from_hex: ChannelId = serde_json::from_str(expected_json).unwrap();
3859
assert_eq!(from_hex, channel_id);
39-
}
60+
}

domain/src/event_submission.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,4 +24,4 @@ pub struct RateLimit {
2424
/// in milliseconds
2525
#[serde(rename = "timeframe")]
2626
pub time_frame: u64,
27-
}
27+
}

domain/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,9 @@ pub use util::tests as test_util;
77
pub use self::ad_unit::AdUnit;
88
pub use self::asset::Asset;
99
pub use self::bignum::BigNum;
10-
pub use self::channel::{Channel, ChannelId, ChannelListParams, ChannelSpec};
1110
#[cfg(feature = "repositories")]
1211
pub use self::channel::ChannelRepository;
12+
pub use self::channel::{Channel, ChannelId, ChannelListParams, ChannelSpec};
1313
pub use self::event_submission::EventSubmission;
1414
#[cfg(feature = "repositories")]
1515
pub use self::repository::*;

0 commit comments

Comments
 (0)