Skip to content

Commit

Permalink
run cargo fmt on project
Browse files Browse the repository at this point in the history
  • Loading branch information
digizeph committed Feb 3, 2024
1 parent 8add29d commit 50a90e6
Show file tree
Hide file tree
Showing 6 changed files with 76 additions and 37 deletions.
37 changes: 25 additions & 12 deletions src/radar/bgp/prefix_origins.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use serde::{Deserialize, Serialize};
use crate::radar::bgp::BgpRoutesMeta;
use crate::radar::client::RadarClient;
use crate::radar::error::RadarError;
use serde::{Deserialize, Serialize};

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PrefixOriginsEntry {
Expand All @@ -23,11 +23,17 @@ struct PrefixOriginsResponse {
pub success: bool,
}

impl RadarClient{

pub fn get_bgp_prefix_origins(&self, origin: Option<u32>, prefix: Option<String>, rpki_status: Option<String>) -> Result<PrefixOriginsResult, RadarError>{
impl RadarClient {
pub fn get_bgp_prefix_origins(
&self,
origin: Option<u32>,
prefix: Option<String>,
rpki_status: Option<String>,
) -> Result<PrefixOriginsResult, RadarError> {
if origin.is_none() && prefix.is_none() {
return Err(RadarError::InvalidParamsError("prefix_origins: origin or prefix must be specified".to_string()));
return Err(RadarError::InvalidParamsError(
"prefix_origins: origin or prefix must be specified".to_string(),
));
}

let mut route = "radar/bgp/routes/pfx2as".to_string();
Expand All @@ -49,11 +55,12 @@ impl RadarClient{

let response = self.send_request(route.as_str())?;
if !response.status().is_success() {
return Err(RadarError::RequestError(response.error_for_status().unwrap_err()));
return Err(RadarError::RequestError(
response.error_for_status().unwrap_err(),
));
}
Ok(response.json::<PrefixOriginsResponse>()?.result)
}

}

#[cfg(test)]
Expand All @@ -65,12 +72,18 @@ mod tests {
let client = RadarClient::new().unwrap();

assert!(client.get_bgp_prefix_origins(None, None, None).is_err());
let res = client.get_bgp_prefix_origins(Some(13335), None, None).unwrap();
assert!(res.prefix_origins.len()>1);
let res = client.get_bgp_prefix_origins(None, Some("1.1.1.0/24".to_string()), None).unwrap();
let res = client
.get_bgp_prefix_origins(Some(13335), None, None)
.unwrap();
assert!(res.prefix_origins.len() > 1);
let res = client
.get_bgp_prefix_origins(None, Some("1.1.1.0/24".to_string()), None)
.unwrap();
assert_eq!(res.prefix_origins.len(), 1);
// non-existing prefix
let res = client.get_bgp_prefix_origins(None, Some("1.1.1.1/25".to_string()), None).unwrap();
let res = client
.get_bgp_prefix_origins(None, Some("1.1.1.1/25".to_string()), None)
.unwrap();
assert_eq!(res.prefix_origins.len(), 0);
}
}
}
39 changes: 26 additions & 13 deletions src/radar/bgp/routing_stats.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use serde::{Deserialize, Serialize};
use crate::radar::bgp::BgpRoutesMeta;
use crate::radar::client::RadarClient;
use crate::radar::error::RadarError;
use serde::{Deserialize, Serialize};

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RoutingStatsEntry {
Expand Down Expand Up @@ -37,11 +37,16 @@ struct RoutingStatsResponse {
pub success: bool,
}

impl RadarClient{

pub fn get_bgp_routing_stats(&self, asn: Option<u32>, country_code: Option<String>) -> Result<RoutingStatsResult, RadarError>{
impl RadarClient {
pub fn get_bgp_routing_stats(
&self,
asn: Option<u32>,
country_code: Option<String>,
) -> Result<RoutingStatsResult, RadarError> {
if asn.is_some() && country_code.is_some() {
return Err(RadarError::InvalidParamsError("bgp_routing_stats: only one of asn or country code can be specified".to_string()));
return Err(RadarError::InvalidParamsError(
"bgp_routing_stats: only one of asn or country code can be specified".to_string(),
));
}

let mut route = "radar/bgp/routes/stats".to_string();
Expand All @@ -52,7 +57,9 @@ impl RadarClient{
}
if let Some(code) = country_code {
if code.len() != 2 {
return Err(RadarError::InvalidParamsError("bgp_routing_stats: country code must be 2 characters".to_string()));
return Err(RadarError::InvalidParamsError(
"bgp_routing_stats: country code must be 2 characters".to_string(),
));
}
params.push(format!("location={}", code));
}
Expand All @@ -63,7 +70,9 @@ impl RadarClient{

let response = self.send_request(route.as_str())?;
if !response.status().is_success() {
return Err(RadarError::RequestError(response.error_for_status().unwrap_err()));
return Err(RadarError::RequestError(
response.error_for_status().unwrap_err(),
));
}
Ok(response.json::<RoutingStatsResponse>()?.result)
}
Expand All @@ -80,25 +89,29 @@ mod tests {
// global routing table stats
let res = client.get_bgp_routing_stats(None, None);
assert!(res.is_ok());
assert!(res.unwrap().stats.routes_total>1_000_000);
assert!(res.unwrap().stats.routes_total > 1_000_000);

// per_asn routing table stats
let res = client.get_bgp_routing_stats(Some(13335), None);
assert!(res.is_ok());
assert!(res.unwrap().stats.routes_total>1_000);
assert!(res.unwrap().stats.routes_total > 1_000);

// per_asn routing table stats
let res = client.get_bgp_routing_stats(None, Some("US".to_string()));
assert!(res.is_ok());
assert!(res.unwrap().stats.routes_total>1_000);
assert!(res.unwrap().stats.routes_total > 1_000);

// per_asn routing table stats
let res = client.get_bgp_routing_stats(None, Some("us".to_string()));
assert!(res.is_ok());
assert!(res.unwrap().stats.routes_total>1_000);
assert!(res.unwrap().stats.routes_total > 1_000);

// error cases
assert!(client.get_bgp_routing_stats(None, Some("united stats".to_string())).is_err());
assert!(client.get_bgp_routing_stats(Some(13335), Some("US".to_string())).is_err());
assert!(client
.get_bgp_routing_stats(None, Some("united stats".to_string()))
.is_err());
assert!(client
.get_bgp_routing_stats(Some(13335), Some("US".to_string()))
.is_err());
}
}
26 changes: 19 additions & 7 deletions src/radar/client.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use reqwest::{header};
use reqwest::blocking::{Client, Response};
use crate::radar::error::RadarError;
use reqwest::blocking::{Client, Response};
use reqwest::header;

pub const CF_API_BASE_URL: &str = "https://api.cloudflare.com/client/v4";

Expand All @@ -15,13 +15,23 @@ impl RadarClient {

let api_token = match std::env::var("CF_API_TOKEN") {
Ok(token) => token,
Err(_) => return Err(RadarError::TokenError("missing environment variable CF_API_TOKEN".to_string())),
Err(_) => {
return Err(RadarError::TokenError(
"missing environment variable CF_API_TOKEN".to_string(),
))
}
};

// build reqwest client with default authorization token
let mut headers = header::HeaderMap::new();
headers.insert("Authorization", header::HeaderValue::from_str(format!("Bearer {}", api_token).as_str()).unwrap());
headers.insert("Content-Type", header::HeaderValue::from_static("application/json"));
headers.insert(
"Authorization",
header::HeaderValue::from_str(format!("Bearer {}", api_token).as_str()).unwrap(),
);
headers.insert(
"Content-Type",
header::HeaderValue::from_static("application/json"),
);
let client = reqwest::blocking::ClientBuilder::new()
.user_agent("radar-rs/0.1")
.default_headers(headers)
Expand All @@ -33,7 +43,9 @@ impl RadarClient {
}

fn verify_token(client: &Client) -> Result<(), RadarError> {
let response = client.get(format!("{}/user/tokens/verify", CF_API_BASE_URL)).send()?;
let response = client
.get(format!("{}/user/tokens/verify", CF_API_BASE_URL))
.send()?;
if !response.status().is_success() {
return Err(RadarError::TokenError("invalid api token".to_string()));
}
Expand All @@ -55,4 +67,4 @@ mod tests {
// NOTE: need to set a valid CF_API_TOKEN in .env file
RadarClient::new().unwrap();
}
}
}
1 change: 1 addition & 0 deletions src/radar/entities/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

2 changes: 1 addition & 1 deletion src/radar/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,4 @@ pub enum RadarError {

#[error("network request error: {0}")]
RequestError(#[from] reqwest::Error),
}
}
8 changes: 4 additions & 4 deletions src/radar/mod.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
mod entities;
mod bgp;
mod error;
mod client;
mod entities;
mod error;

pub use error::RadarError;
pub use bgp::*;
pub use client::RadarClient;
pub use bgp::*;
pub use error::RadarError;

0 comments on commit 50a90e6

Please sign in to comment.