Skip to content
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
4 changes: 2 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ cadence = "^1.6.0"
envy = "^0.4.2"
futures = "^0.3"
lazy_static = "^1.5.0"
maxminddb = "^0.26.0"
maxminddb = "0.27.1"
regex = "^1.12.2"
sentry = "^0.45.0"
sentry-actix = "^0.45.0"
Expand Down
63 changes: 49 additions & 14 deletions src/endpoints/classify.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,11 @@ fn country_iso_code<S: Serializer>(
country_info: &Option<geoip2::Country>,
serializer: S,
) -> Result<S::Ok, S::Error> {
let iso_code: Option<&str> = country_info
.clone()
.and_then(|country_info| country_info.country)
.and_then(|country| country.iso_code);

match iso_code {
Some(code) => serializer.serialize_str(code),
match country_info {
Some(x) => match x.country.iso_code {
Some(code) => serializer.serialize_str(code),
_ => serializer.serialize_none(),
},
None => serializer.serialize_none(),
}
}
Expand Down Expand Up @@ -78,17 +76,54 @@ mod tests {
let value = serde_json::to_value(&classification).unwrap();
assert_eq!(*value.get("country").unwrap(), Value::Null);

let none_names = geoip2::Names {
german: None,
english: None,
spanish: None,
french: None,
japanese: None,
brazilian_portuguese: None,
russian: None,
simplified_chinese: None,
};

classification.country = Some(geoip2::Country {
country: Some(geoip2::country::Country {
country: geoip2::country::Country {
geoname_id: None,
iso_code: Some("US"),
names: None,
names: geoip2::Names {
german: None,
english: Some("United States of America"),
spanish: None,
french: None,
japanese: None,
brazilian_portuguese: None,
russian: None,
simplified_chinese: None,
},
is_in_european_union: None,
},
continent: geoip2::country::Continent {
code: None,
geoname_id: None,
names: none_names.clone(),
},
registered_country: geoip2::city::Country {
geoname_id: None,
is_in_european_union: None,
iso_code: None,
names: none_names.clone(),
},
represented_country: geoip2::city::RepresentedCountry {
geoname_id: None,
is_in_european_union: None,
}),
continent: None,
registered_country: None,
represented_country: None,
traits: None,
iso_code: None,
names: none_names.clone(),
representation_type: None,
},
traits: geoip2::city::Traits {
is_anycast: Some(false),
},
});

let value = serde_json::to_value(&classification).unwrap();
Expand Down
39 changes: 14 additions & 25 deletions src/endpoints/country.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,21 +75,9 @@ pub async fn get_country(
}

// return country if we can identify it based on IP address
state
.geoip
.locate(req.client_ip()?)
.map(move |location| {
let country_opt = match location {
Some(x) => x.country,
None => None,
};

if country_opt.is_none() {
let mut response = HttpResponse::NotFound();
metrics.incr_with_tags("country_miss").send();
return response.json(&COUNTRY_NOT_FOUND_RESPONSE);
}

let country_info = state.geoip.locate(req.client_ip()?);
match country_info {
Ok(Some(country_info)) => {
let mut response = HttpResponse::Ok();
response.append_header((
http::header::CACHE_CONTROL,
Expand All @@ -98,16 +86,17 @@ pub async fn get_country(

metrics.incr_with_tags("country_hit").send();

let country = country_opt.unwrap();
response.json(CountryResponse {
country_code: country.iso_code.unwrap_or_default(),
country_name: match country.names {
Some(x) => x["en"],
None => "",
},
})
})
.map_err(|err| ClassifyError::from_source("Future failure", err))
Ok(response.json(CountryResponse {
country_code: country_info.country.iso_code.unwrap_or_default(),
country_name: country_info.country.names.english.unwrap_or_default(),
}))
}
_ => {
let mut response = HttpResponse::NotFound();
metrics.incr_with_tags("country_miss").send();
Ok(response.json(&COUNTRY_NOT_FOUND_RESPONSE))
}
}
}

#[cfg(test)]
Expand Down
2 changes: 1 addition & 1 deletion src/endpoints/dockerflow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ pub async fn heartbeat(app_data: Data<EndpointState>) -> Result<HttpResponse, Cl
.and_then(|res| match res {
Some(country_info) => country_info
.country
.and_then(|country| country.iso_code)
.iso_code
.map(|iso_code| Ok(!iso_code.is_empty()))
.unwrap_or(Ok(false)),
None => Ok(false),
Expand Down
45 changes: 19 additions & 26 deletions src/geoip.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::errors::ClassifyError;
use cadence::{StatsdClient, prelude::*};
use maxminddb::{self, MaxMindDbError, geoip2};
use maxminddb::{self, geoip2};
use std::{fmt, net::IpAddr, path::PathBuf, sync::Arc};

pub struct GeoIp {
Expand All @@ -14,32 +14,25 @@ impl GeoIp {
}

pub fn locate(&'_ self, ip: IpAddr) -> Result<Option<geoip2::Country<'_>>, ClassifyError> {
self.reader
let lookup_result = self
.reader
.as_ref()
.ok_or_else(|| ClassifyError::new("No geoip database available"))?
.lookup(ip)
.inspect(|country_info: &Option<geoip2::Country>| {
// Send a metrics ping about the geolocation result
let iso_code = country_info
.clone()
.and_then(|country_info| country_info.country)
.and_then(|country| country.iso_code);
self.metrics
.incr_with_tags("location")
.with_tag("country", iso_code.unwrap_or("unknown"))
.send();
})
.or_else(|err| match err {
MaxMindDbError::InvalidNetwork(_) => {
self.metrics
.incr_with_tags("location")
.with_tag("country", "unknown")
.send();
Ok(None)
}
_ => Err(err),
})
.map_err(|err| err.into())
.lookup(ip);
if let Some(country_info) = lookup_result?.decode::<geoip2::Country>()? {
// Send a metrics ping about the geolocation result
let iso_code = country_info.country.iso_code.unwrap_or("unknown");
self.metrics
.incr_with_tags("location")
.with_tag("country", iso_code)
.send();
return Ok(Some(country_info));
}
self.metrics
.incr_with_tags("location")
.with_tag("country", "unknown")
.send();
Ok(None)
}
}

Expand Down Expand Up @@ -115,7 +108,7 @@ mod tests {

let ip = "7.7.7.7".parse()?;
let rv = geoip.locate(ip).unwrap().unwrap();
assert_eq!(rv.country.unwrap().iso_code.unwrap(), "US");
assert_eq!(rv.country.iso_code.unwrap(), "US");
Ok(())
}

Expand Down
Loading