Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

House keeping #44

Merged
merged 3 commits into from
Dec 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions .github/workflows/cd_crates.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,11 @@ permissions:

jobs:
publish:

runs-on: ubuntu-latest

steps:
- name: Checkout
uses: actions/checkout@v3
uses: actions/checkout@v4

- name: Build
run: cargo build --verbose
Expand Down
16 changes: 13 additions & 3 deletions .github/workflows/unittest.yaml → .github/workflows/rust.yaml
Original file line number Diff line number Diff line change
@@ -1,18 +1,28 @@
name: Unit Tests
name: Rust lints and tests

on:
pull_request:
branches: [ master ]
push:
branches: [ master ]

permissions:
contents: read

jobs:
run:

runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v4

- name: Run Clippy
env:
RUSTFLAGS: "-Dwarnings"
run: cargo clippy

- name: Check formatting
run: cargo fmt --check

- name: Build
run: cargo build --verbose
Expand Down
14 changes: 1 addition & 13 deletions .rustfmt.toml
Original file line number Diff line number Diff line change
@@ -1,14 +1,2 @@
max_width = 79
hard_tabs = false
tab_spaces = 4
newline_style = "Auto"
use_small_heuristics = "Default"
reorder_imports = true
reorder_modules = true
remove_nested_parens = true
fn_args_layout = "Tall"
edition = "2018"
merge_derives = true
use_try_shorthand = false
use_field_init_shorthand = false
force_explicit_abi = true
edition = "2021"
11 changes: 8 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,13 @@
name = "ipinfo"
description = "ipinfo: A Rust library for IPInfo"
version = "3.0.0"
authors = ["Amr Ali <[email protected]>", "Uman Shahzad <[email protected]>", "Umar Farooq <[email protected]>", "Fayzan Ahmad <[email protected]>"]
edition = "2018"
authors = [
"Amr Ali <[email protected]>",
"Uman Shahzad <[email protected]>",
"Umar Farooq <[email protected]>",
"Fayzan Ahmad <[email protected]>",
]
edition = "2021"
license = "Apache-2.0"
homepage = "https://github.com/ipinfo/rust/"
readme = "README.md"
Expand All @@ -22,7 +27,7 @@ serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
include_dir = "0.7.3"
ipnetwork = "0.20.0"
tokio = { version = "1", features = ["macros", "time"]}
tokio = { version = "1", features = ["macros", "time"] }
lazy_static = "1.4"

[profile.release]
Expand Down
4 changes: 2 additions & 2 deletions examples/lookup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::env;

#[tokio::main]
async fn main() {
let token = env::args().skip(1).next();
let token = env::args().nth(1);

let config = IpInfoConfig {
token,
Expand All @@ -15,7 +15,7 @@ async fn main() {
let res = ipinfo.lookup("8.8.8.8").await;
match res {
Ok(r) => {
println!("{} lookup result: {:?}", "8.8.8.8", r);
println!("8.8.8.8 lookup result: {:?}", r);
}
Err(e) => println!("error occurred: {}", &e.to_string()),
}
Expand Down
7 changes: 4 additions & 3 deletions examples/lookup_batch.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
use ipinfo::{BatchReqOpts, IpInfo, IpInfoConfig};
use std::env;

#[tokio::main]
async fn main() {
let token = env::args().skip(1).next();
let token = env::args().nth(1);

let config = IpInfoConfig {
token,
Expand All @@ -17,8 +18,8 @@ async fn main() {

match res2 {
Ok(r) => {
println!("{}: {:?}", "8.8.8.8", r["8.8.8.8"]);
println!("{}: {:?}", "4.2.2.4", r["4.2.2.4"]);
println!("8.8.8.8: {:?}", r["8.8.8.8"]);
println!("4.2.2.4: {:?}", r["4.2.2.4"]);
}
Err(e) => println!("error occurred: {}", &e.to_string()),
}
Expand Down
4 changes: 0 additions & 4 deletions src/data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,6 @@ lazy_static! {
"#;
serde_json::from_str(json_data).expect("error parsing JSON!")
};

pub static ref COUNTRIES: HashMap<String, String> = {
let json_data = r#"
{
Expand Down Expand Up @@ -519,7 +518,6 @@ lazy_static! {
"#;
serde_json::from_str(json_data).expect("error parsing JSON!")
};

pub static ref CURRENCIES: HashMap<String, CountryCurrency> = {
let json_data = r#"
{
Expand Down Expand Up @@ -777,7 +775,6 @@ lazy_static! {
"#;
serde_json::from_str(json_data).expect("error parsing JSON!")
};

pub static ref EU: Vec<String> = {
let json_data = r#"
[
Expand Down Expand Up @@ -812,7 +809,6 @@ lazy_static! {
"#;
serde_json::from_str(json_data).expect("error parsing JSON!")
};

pub static ref FLAGS: HashMap<String, CountryFlag> = {
let json_data = r#"
{
Expand Down
54 changes: 31 additions & 23 deletions src/ipinfo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ use std::{collections::HashMap, num::NonZeroUsize, time::Duration};

use crate::{
cache_key, is_bogon, Continent, CountryCurrency, CountryFlag, IpDetails,
IpError, BATCH_MAX_SIZE, BATCH_REQ_TIMEOUT_DEFAULT, VERSION,
COUNTRIES, EU, FLAGS, CONTINENTS, CURRENCIES,
IpError, BATCH_MAX_SIZE, BATCH_REQ_TIMEOUT_DEFAULT, CONTINENTS, COUNTRIES,
CURRENCIES, EU, FLAGS, VERSION,
};

use lru::LruCache;
Expand All @@ -29,7 +29,8 @@ use reqwest::header::{

use tokio::time::timeout;

const COUNTRY_FLAG_URL : &str= "https://cdn.ipinfo.io/static/images/countries-flags/";
const COUNTRY_FLAG_URL: &str =
"https://cdn.ipinfo.io/static/images/countries-flags/";
/// IpInfo structure configuration.
pub struct IpInfoConfig {
/// IPinfo access token.
Expand All @@ -45,7 +46,7 @@ pub struct IpInfoConfig {
pub defaut_countries: Option<HashMap<String, String>>,

// Default list of EU countries
pub default_eu: Option<Vec<String> >,
pub default_eu: Option<Vec<String>>,

// Default mapping of country codes to their respective flag emoji and unicode
pub default_flags: Option<HashMap<String, CountryFlag>>,
Expand Down Expand Up @@ -240,9 +241,8 @@ impl IpInfo {
}

// Add country_name and EU status to response
for detail in results.to_owned() {
let mut mut_details = results.get_mut(&detail.0).unwrap();
self.populate_static_details(&mut mut_details);
for detail in results.values_mut() {
self.populate_static_details(detail);
}

// Add Bogon IP Results
Expand All @@ -264,15 +264,15 @@ impl IpInfo {
}

async fn _lookup_batch(
self: &Self,
&self,
client: reqwest::Client,
ips: &[&str],
) -> Result<HashMap<String, IpDetails>, IpError> {
// Lookup cache misses which are not bogon
let response = client
.post(&format!("{}/batch", self.url))
.headers(Self::construct_headers())
.bearer_auth(&self.token.as_ref().unwrap_or(&"".to_string()))
.bearer_auth(self.token.as_deref().unwrap_or_default())
.json(&json!(ips))
.send()
.await?;
Expand All @@ -296,7 +296,7 @@ impl IpInfo {
// Parse the results
let result: HashMap<String, IpDetails> =
serde_json::from_str(&raw_resp)?;
return Ok(result);
Ok(result)
}

/// looks up IPDetails for a single IP Address
Expand All @@ -313,7 +313,7 @@ impl IpInfo {
/// }
/// ```
pub async fn lookup(&mut self, ip: &str) -> Result<IpDetails, IpError> {
if is_bogon(&ip.to_string()) {
if is_bogon(ip) {
return Ok(IpDetails {
ip: ip.to_string(),
bogon: Some(true),
Expand All @@ -324,16 +324,16 @@ impl IpInfo {
// Check for cache hit
let cached_detail = self.cache.get(&cache_key(ip));

if !cached_detail.is_none() {
return Ok(cached_detail.unwrap().clone());
if let Some(cached_detail) = cached_detail {
return Ok(cached_detail.clone());
}

// lookup in case of a cache miss
let response = self
.client
.get(&format!("{}/{}", self.url, ip))
.headers(Self::construct_headers())
.bearer_auth(&self.token.as_ref().unwrap_or(&"".to_string()))
.bearer_auth(self.token.as_deref().unwrap_or_default())
.send()
.await?;

Expand Down Expand Up @@ -406,7 +406,9 @@ impl IpInfo {
self.country_flags.get(&details.country).unwrap();
details.country_flag = Some(country_flag.to_owned());
let file_ext = ".svg";
details.country_flag_url = Some(COUNTRY_FLAG_URL.to_string() + &details.country + file_ext);
details.country_flag_url = Some(
COUNTRY_FLAG_URL.to_string() + &details.country + file_ext,
);
let country_currency =
self.country_currencies.get(&details.country).unwrap();
details.country_currency = Some(country_currency.to_owned());
Expand Down Expand Up @@ -439,13 +441,13 @@ mod tests {
use std::env;

fn get_ipinfo_client() -> IpInfo {
return IpInfo::new(IpInfoConfig {
IpInfo::new(IpInfoConfig {
token: Some(env::var("IPINFO_TOKEN").unwrap().to_string()),
timeout: Duration::from_secs(3),
cache_size: 100,
..Default::default()
})
.expect("should construct");
.expect("should construct")
}

#[test]
Expand Down Expand Up @@ -514,7 +516,13 @@ mod tests {
assert_eq!(ip8.city, "Mountain View");
assert_eq!(ip8.region, "California");
assert_eq!(ip8.country, "US");
assert_eq!(ip8.country_flag_url, Some("https://cdn.ipinfo.io/static/images/countries-flags/US.svg".to_owned()));
assert_eq!(
ip8.country_flag_url,
Some(
"https://cdn.ipinfo.io/static/images/countries-flags/US.svg"
.to_owned()
)
);
assert_eq!(
ip8.country_flag,
Some(CountryFlag {
Expand Down Expand Up @@ -580,10 +588,10 @@ mod tests {

#[test]
fn test_is_bogon() {
assert_eq!(true, is_bogon("169.254.0.1"));
assert_eq!(true, is_bogon("192.0.2.1"));
assert_eq!(false, is_bogon("8.8.8.8"));
assert_eq!(true, is_bogon("2001:db8::1"));
assert_eq!(false, is_bogon("2606:4700:4700:1111::2"));
assert!(is_bogon("169.254.0.1"));
assert!(is_bogon("192.0.2.1"));
assert!(!is_bogon("8.8.8.8"));
assert!(is_bogon("2001:db8::1"));
assert!(!is_bogon("2606:4700:4700:1111::2"));
}
}
4 changes: 2 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,12 @@ const VERSION: &str = env!("CARGO_PKG_VERSION");
#[macro_use]
mod error;
mod api;
mod data;
mod ipinfo;
mod util;
mod data;

pub use crate::ipinfo::*;
pub use api::*;
pub use data::*;
pub use error::*;
pub use util::*;
pub use data::*;
Loading