use crate::error::{GarrisonError, GarrisonResult};
use async_trait::async_trait;
#[cfg(feature = "firewall-maxminddb")]
pub mod matcher;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct GeoCoord {
pub lat: f64,
pub lon: f64,
}
impl GeoCoord {
pub fn new(lat: f64, lon: f64) -> Result<Self, GarrisonError> {
if !(-90.0..=90.0).contains(&lat) {
return Err(GarrisonError::InvalidParam(format!(
"firewall-geo-lat-out-of-range::{}",
lat
)));
}
if !(-180.0..=180.0).contains(&lon) {
return Err(GarrisonError::InvalidParam(format!(
"firewall-geo-lon-out-of-range::{}",
lon
)));
}
Ok(Self { lat, lon })
}
pub fn to_csv(self) -> String {
format!("{},{}", self.lat, self.lon)
}
pub fn from_csv(s: &str) -> Option<Self> {
let mut parts = s.splitn(2, ',');
let lat: f64 = parts.next()?.trim().parse().ok()?;
let lon: f64 = parts.next()?.trim().parse().ok()?;
Self::new(lat, lon).ok()
}
}
#[async_trait]
pub trait GeoLookup: Send + Sync {
async fn lookup(&self, ip: &str) -> GarrisonResult<Option<GeoCoord>>;
}
#[async_trait]
pub trait CountryLookup: Send + Sync {
async fn lookup_country(&self, ip: &str) -> GarrisonResult<Option<String>>;
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn geo_coord_csv_roundtrip() {
let coord = GeoCoord::new(39.9042, 116.4074).unwrap();
let csv = coord.to_csv();
let parsed = GeoCoord::from_csv(&csv).unwrap();
assert_eq!(coord, parsed);
}
#[test]
fn geo_coord_from_csv_rejects_invalid() {
assert!(GeoCoord::from_csv("invalid").is_none());
assert!(GeoCoord::from_csv("abc,def").is_none());
assert!(GeoCoord::from_csv("").is_none());
assert!(GeoCoord::from_csv("1.0").is_none());
}
#[test]
fn geo_coord_new_rejects_lat_out_of_range() {
let above = GeoCoord::new(90.5, 0.0);
assert!(
matches!(&above, Err(GarrisonError::InvalidParam(msg)) if msg.contains("lat")),
"纬度 90.5 应返回 InvalidParam 且消息含 'lat',实际: {:?}",
above
);
let below = GeoCoord::new(-90.5, 0.0);
assert!(
matches!(&below, Err(GarrisonError::InvalidParam(msg)) if msg.contains("lat")),
"纬度 -90.5 应返回 InvalidParam 且消息含 'lat',实际: {:?}",
below
);
}
#[test]
fn geo_coord_new_rejects_lon_out_of_range() {
let above = GeoCoord::new(0.0, 180.5);
assert!(
matches!(&above, Err(GarrisonError::InvalidParam(msg)) if msg.contains("lon")),
"经度 180.5 应返回 InvalidParam 且消息含 'lon',实际: {:?}",
above
);
let below = GeoCoord::new(0.0, -180.5);
assert!(
matches!(&below, Err(GarrisonError::InvalidParam(msg)) if msg.contains("lon")),
"经度 -180.5 应返回 InvalidParam 且消息含 'lon',实际: {:?}",
below
);
}
#[test]
fn geo_coord_new_accepts_boundary_values() {
assert!(GeoCoord::new(-90.0, -180.0).is_ok());
assert!(GeoCoord::new(90.0, 180.0).is_ok());
assert!(GeoCoord::new(0.0, 0.0).is_ok());
}
#[test]
fn geo_coord_new_rejects_nan() {
assert!(GeoCoord::new(f64::NAN, 0.0).is_err());
assert!(GeoCoord::new(0.0, f64::NAN).is_err());
}
#[test]
fn geo_coord_from_csv_trims_whitespace() {
let parsed = GeoCoord::from_csv(" 39.9042 , 116.4074 ").expect("带空白 CSV 应可解析");
assert_eq!(parsed.lat, 39.9042);
assert_eq!(parsed.lon, 116.4074);
}
#[test]
fn geo_coord_from_csv_rejects_out_of_range_coords() {
assert!(GeoCoord::from_csv("91.0,0.0").is_none(), "纬度越界应 None");
assert!(GeoCoord::from_csv("-90.5,0.0").is_none(), "纬度越界应 None");
assert!(GeoCoord::from_csv("0.0,181.0").is_none(), "经度越界应 None");
assert!(
GeoCoord::from_csv("0.0,-180.5").is_none(),
"经度越界应 None"
);
}
#[test]
fn geo_coord_to_csv_format() {
let coord = GeoCoord::new(-33.865143, 151.209900).unwrap();
assert_eq!(coord.to_csv(), "-33.865143,151.2099");
}
#[tokio::test]
async fn mock_geo_and_country_lookup_trait_objects() {
struct MockGeo;
struct MockCountry;
#[async_trait]
impl GeoLookup for MockGeo {
async fn lookup(&self, ip: &str) -> GarrisonResult<Option<GeoCoord>> {
if ip == "1.2.3.4" {
Ok(Some(GeoCoord::new(1.0, 2.0).unwrap()))
} else {
Ok(None)
}
}
}
#[async_trait]
impl CountryLookup for MockCountry {
async fn lookup_country(&self, ip: &str) -> GarrisonResult<Option<String>> {
if ip == "1.2.3.4" {
Ok(Some("CN".to_string()))
} else {
Ok(None)
}
}
}
let geo: std::sync::Arc<dyn GeoLookup> = std::sync::Arc::new(MockGeo);
let country: std::sync::Arc<dyn CountryLookup> = std::sync::Arc::new(MockCountry);
let hit = geo.lookup("1.2.3.4").await.unwrap();
assert_eq!(hit, Some(GeoCoord { lat: 1.0, lon: 2.0 }));
assert_eq!(geo.lookup("unknown").await.unwrap(), None);
assert_eq!(
country.lookup_country("1.2.3.4").await.unwrap(),
Some("CN".into())
);
assert_eq!(country.lookup_country("unknown").await.unwrap(), None);
}
}