bibby 0.2.0

The official Rust SDK for Bytebury — typed clients, smart .env initialization, and ergonomic macros for Geo, Images, PDF, Mailer, Uploader, Cron, Forms, Webhooks, Monitors, and Vault.
Documentation
//! Client and types for **Bytebury Geo** (`https://api.bytebury.com/geo/v1`).
//!
//! Look up IPv4 and IPv6 addresses, draw SVG location maps, fetch random IPs
//! by country or region, and submit geolocation corrections.

use serde::{Deserialize, Serialize};

use crate::client::Bibby;
use crate::error::Result;

const PRODUCT: &str = "geo";

/// Client for **Bytebury Geo**.
///
/// Obtained via [`Bibby::geo`].
#[derive(Debug, Clone, Copy)]
pub struct GeoClient<'a> {
    client: &'a Bibby,
}

impl<'a> GeoClient<'a> {
    pub(crate) fn new(client: &'a Bibby) -> Self {
        Self { client }
    }

    /// Looks up geolocation metadata for an IPv4 or IPv6 address.
    ///
    /// Calls `GET /geo/v1/ips/{ip}`.
    pub async fn lookup(&self, ip: &str) -> Result<IpLocation> {
        self.client.get_json(PRODUCT, &format!("ips/{ip}")).await
    }

    /// Looks up geolocation metadata for an IP address, optionally including an
    /// inline SVG map (`include_map = true`, paid plans only; counts as 2 lookups).
    ///
    /// Calls `GET /geo/v1/ips/{ip}?include_map=...`.
    pub async fn lookup_with_options(
        &self,
        ip: &str,
        options: &LookupOptions,
    ) -> Result<IpLocation> {
        self.client
            .get_json_query(PRODUCT, &format!("ips/{ip}"), options)
            .await
    }

    /// Returns a random known IP address and its location, optionally filtered
    /// by country, region, or IP version (`4` or `6`).
    ///
    /// Calls `GET /geo/v1/ips/random`.
    pub async fn random(&self, options: &RandomIpOptions) -> Result<IpLocation> {
        self.client
            .get_json_query(PRODUCT, "ips/random", options)
            .await
    }

    /// Submits a location correction for an IP's `/24` (IPv4) or `/48` (IPv6) block.
    ///
    /// Calls `POST /geo/v1/ips/{ip}/corrections`.
    pub async fn submit_correction(
        &self,
        ip: &str,
        correction: &CorrectionRequest,
    ) -> Result<IpLocation> {
        self.client
            .post_json(PRODUCT, &format!("ips/{ip}/corrections"), correction)
            .await
    }
}

/// Query options for [`GeoClient::lookup_with_options`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct LookupOptions {
    /// When `true`, includes an SVG map in [`IpLocation::map`] (paid plans only).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub include_map: Option<bool>,
}

impl LookupOptions {
    /// Creates options requesting an inline SVG map.
    pub fn with_map() -> Self {
        Self {
            include_map: Some(true),
        }
    }
}

/// Query options for [`GeoClient::random`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct RandomIpOptions {
    /// ISO 3166-1 alpha-2 country code (e.g. `"US"`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub country_code: Option<String>,
    /// ISO 3166-2 region code (e.g. `"US-CT"`). Implies its country.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub region_code: Option<String>,
    /// IP version: `4` (default) or `6`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version: Option<u8>,
}

impl RandomIpOptions {
    /// Filters random IPs to a specific ISO 3166-1 alpha-2 country code.
    pub fn country(mut self, code: impl Into<String>) -> Self {
        self.country_code = Some(code.into());
        self
    }

    /// Filters random IPs to a specific ISO 3166-2 region code.
    pub fn region(mut self, code: impl Into<String>) -> Self {
        self.region_code = Some(code.into());
        self
    }

    /// Requests IPv4 (`4`) or IPv6 (`6`) addresses.
    pub fn version(mut self, version: u8) -> Self {
        self.version = Some(version);
        self
    }
}

/// Request body for [`GeoClient::submit_correction`].
#[derive(Debug, Clone, Serialize)]
pub struct CorrectionRequest {
    /// ISO 3166-1 alpha-2 country code (e.g. `"US"`).
    pub country_code: String,
    /// Optional ISO 3166-2 region code (e.g. `"US-CT"`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub region_code: Option<String>,
}

impl CorrectionRequest {
    /// Creates a correction targeting a country (and optionally a region).
    pub fn new(country_code: impl Into<String>) -> Self {
        Self {
            country_code: country_code.into(),
            region_code: None,
        }
    }

    /// Sets the ISO 3166-2 region code on this correction.
    pub fn region_code(mut self, region_code: impl Into<String>) -> Self {
        self.region_code = Some(region_code.into());
        self
    }
}

/// A named country or region code.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct NamedCode {
    /// ISO code (e.g. `"US"` or `"US-CT"`).
    pub code: String,
    /// Human-readable English name.
    pub name: String,
}

/// Autonomous System network information for an IP address.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct NetworkInfo {
    /// Autonomous System Number (ASN).
    pub asn: u32,
    /// Organisation name operating the ASN, if known.
    pub organisation: Option<String>,
}

/// Connection classification for an IP address.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ConnectionType {
    /// Datacenter / cloud / hosting provider.
    Hosting,
    /// Proxy, VPN, or relay service.
    Relay,
    /// Satellite internet provider.
    Satellite,
}

/// Risk level for an IP address or email.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RiskLevel {
    /// Low risk.
    Low,
    /// Medium risk.
    Medium,
    /// High risk.
    High,
}

/// Signal contributing to an IP's risk assessment.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum IpRiskReason {
    /// Known Tor exit node.
    TorExit,
    /// Hosting / datacenter IP.
    Hosting,
    /// Relay / proxy IP.
    Relay,
}

/// Risk assessment for an IP address.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IpRisk {
    /// Overall risk tier.
    pub level: RiskLevel,
    /// Specific signals observed for this IP.
    #[serde(default)]
    pub reasons: Vec<IpRiskReason>,
}

/// Provenance of a geolocation answer.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GeoSource {
    /// Regional Internet Registry allocation data.
    Registry,
    /// Published RFC 8805 geofeed.
    Geofeed,
    /// Reverse DNS hostname hints.
    ReverseDns,
    /// Active latency measurement.
    Latency,
    /// User-submitted correction.
    Correction,
    /// DB-IP dataset.
    DbIp,
    /// Statistical estimate.
    Estimate,
}

/// Confidence tier of a geolocation answer.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Confidence {
    /// Confirmed location.
    Confirmed,
    /// Likely accurate location.
    Likely,
    /// Self-reported (e.g. geofeed).
    Reported,
    /// Estimated location.
    Estimated,
    /// Uncertain location.
    Uncertain,
}

/// Full geolocation response returned by Bytebury Geo.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct IpLocation {
    /// Normalized IP address string.
    pub ip: String,
    /// Country code and name.
    pub country: NamedCode,
    /// URL to the country's SVG flag asset.
    pub country_flag_url: String,
    /// Top-level ISO 3166-2 region, if known.
    pub region: Option<NamedCode>,
    /// Candidate regions when ambiguous.
    #[serde(default)]
    pub possible_regions: Vec<NamedCode>,
    /// City name, if known.
    pub city: Option<String>,
    /// Whether `city` was estimated rather than directly observed.
    pub city_estimated: bool,
    /// Postal or ZIP code, if known.
    pub postal_code: Option<String>,
    /// Approximate latitude in decimal degrees.
    pub latitude: Option<f64>,
    /// Approximate longitude in decimal degrees.
    pub longitude: Option<f64>,
    /// Connection classification (`hosting`, `relay`, `satellite`), if applicable.
    pub connection: Option<ConnectionType>,
    /// IANA timezone identifier (e.g. `"America/New_York"`).
    pub timezone: Option<String>,
    /// Autonomous System (ASN) details, if known.
    pub network: Option<NetworkInfo>,
    /// Risk score and signals.
    pub risk: IpRisk,
    /// Primary data source for this answer.
    pub source: GeoSource,
    /// Qualitative confidence rating.
    pub confidence: Confidence,
    /// Numeric confidence score in `0.0..=1.0`.
    pub confidence_score: f64,
    /// Raw SVG map when `include_map=true` was requested on a paid plan.
    pub map: Option<String>,
}