use crate::error::GarrisonResult;
use async_trait::async_trait;
#[cfg(feature = "firewall-maxminddb")]
pub mod maxminddb;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct GeoCoord {
pub lat: f64,
pub lon: f64,
}
impl GeoCoord {
pub fn new(lat: f64, lon: f64) -> Self {
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 = parts.next()?.trim().parse().ok()?;
let lon = parts.next()?.trim().parse().ok()?;
Some(Self { lat, lon })
}
}
#[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);
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());
}
}