refactor: consolidate DB lookup boilerplate, UA detection, and polish error/module docs

Phase 1 (DRY):
- db.rs: extract with_reader() helper to eliminate repeated load-guard-lookup
  boilerplate across 6 lookup functions; use From<MmdbProxy> for ProxyInfo
- ua_detect.rs: extract matches_any_prefix() shared by both prefix-matching fns

Phase 4 (Quality polish):
- error.rs: implement Debug, Display, and std::error::Error on AppError
- Add module-level //! docs to all source modules
This commit is contained in:
NetworkCats
2026-03-22 17:33:09 +08:00
parent ccfa7decda
commit 77410593f2
10 changed files with 71 additions and 42 deletions
+2
View File
@@ -1,3 +1,5 @@
//! Application configuration loaded from environment variables.
use std::env;
use std::net::SocketAddr;
+38 -36
View File
@@ -1,3 +1,5 @@
//! MaxMind MMDB database loading, shared state, and lookup functions.
use std::net::IpAddr;
use std::path::Path;
use std::sync::Arc;
@@ -7,7 +9,7 @@ use maxminddb::Reader;
use serde::Deserialize;
use crate::models::{
IpInfo, MmdbAsn, MmdbCity, MmdbCountry, MmdbProxy, MmdbRecord, ProxyInfo, from_mmdb_record,
from_mmdb_record, IpInfo, MmdbAsn, MmdbCity, MmdbCountry, MmdbProxy, MmdbRecord, ProxyInfo,
};
pub type DbReader = Reader<Vec<u8>>;
@@ -30,11 +32,24 @@ pub fn is_ready(db: &SharedDb) -> bool {
}
pub fn lookup(db: &SharedDb, ip: IpAddr) -> Option<IpInfo> {
with_reader(db, ip, |result| {
let record: MmdbRecord<'_> = result.decode().ok()??;
Some(from_mmdb_record(ip, &record))
})?
}
/// Loads the shared reader, performs a lookup, and passes the raw lookup result
/// to `f` for decoding. This eliminates the repeated load-guard-lookup boilerplate
/// while letting callers choose their own deserialization type and lifetime.
fn with_reader<R>(
db: &SharedDb,
ip: IpAddr,
f: impl FnOnce(maxminddb::LookupResult<'_, Vec<u8>>) -> R,
) -> Option<R> {
let guard = db.load();
let reader = Option::as_ref(&guard)?;
let result = reader.lookup(ip).ok()?;
let record: MmdbRecord<'_> = result.decode().ok()??;
Some(from_mmdb_record(ip, &record))
Some(f(result))
}
// Lightweight deserialization structs for single-field endpoints.
@@ -65,51 +80,38 @@ struct CityOnly<'a> {
}
pub fn lookup_proxy(db: &SharedDb, ip: IpAddr) -> Option<ProxyInfo> {
let guard = db.load();
let reader = Option::as_ref(&guard)?;
let result = reader.lookup(ip).ok()?;
let record: ProxyOnly = result.decode().ok()??;
Some(ProxyInfo {
is_proxy: record.proxy.is_proxy,
is_vpn: record.proxy.is_vpn,
is_tor: record.proxy.is_tor,
is_hosting: record.proxy.is_hosting,
is_cdn: record.proxy.is_cdn,
is_school: record.proxy.is_school,
is_anonymous: record.proxy.is_anonymous,
})
with_reader(db, ip, |result| {
let record: ProxyOnly = result.decode().ok()??;
Some(record.proxy.into())
})?
}
pub fn lookup_asn_number(db: &SharedDb, ip: IpAddr) -> Option<u32> {
let guard = db.load();
let reader = Option::as_ref(&guard)?;
let result = reader.lookup(ip).ok()?;
let record: AsnOnly<'_> = result.decode().ok()??;
record.asn.autonomous_system_number
with_reader(db, ip, |result| {
let record: AsnOnly<'_> = result.decode().ok()??;
record.asn.autonomous_system_number
})?
}
pub fn lookup_asn_org(db: &SharedDb, ip: IpAddr) -> Option<String> {
let guard = db.load();
let reader = Option::as_ref(&guard)?;
let result = reader.lookup(ip).ok()?;
let record: AsnOnly<'_> = result.decode().ok()??;
record.asn.autonomous_system_organization.map(str::to_owned)
with_reader(db, ip, |result| {
let record: AsnOnly<'_> = result.decode().ok()??;
record.asn.autonomous_system_organization.map(str::to_owned)
})?
}
pub fn lookup_country_name(db: &SharedDb, ip: IpAddr) -> Option<String> {
let guard = db.load();
let reader = Option::as_ref(&guard)?;
let result = reader.lookup(ip).ok()?;
let record: CountryOnly<'_> = result.decode().ok()??;
record.country.names.english.map(str::to_owned)
with_reader(db, ip, |result| {
let record: CountryOnly<'_> = result.decode().ok()??;
record.country.names.english.map(str::to_owned)
})?
}
pub fn lookup_city_name(db: &SharedDb, ip: IpAddr) -> Option<String> {
let guard = db.load();
let reader = Option::as_ref(&guard)?;
let result = reader.lookup(ip).ok()?;
let record: CityOnly<'_> = result.decode().ok()??;
record.city.names.english.map(str::to_owned)
with_reader(db, ip, |result| {
let record: CityOnly<'_> = result.decode().ok()??;
record.city.names.english.map(str::to_owned)
})?
}
#[cfg(test)]
+11
View File
@@ -1,6 +1,9 @@
//! Application error types with HTTP status code mapping.
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
#[derive(Debug)]
pub enum AppError {
IpNotFound,
InvalidIp,
@@ -36,6 +39,14 @@ impl AppError {
}
}
impl std::fmt::Display for AppError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.message())
}
}
impl std::error::Error for AppError {}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
(self.status_code(), self.message()).into_response()
+2
View File
@@ -1,3 +1,5 @@
//! Internationalization support with PO-file-based translations and locale negotiation.
use std::collections::HashMap;
use std::sync::LazyLock;
+2
View File
@@ -1,3 +1,5 @@
//! IP address validation: determines whether an address is publicly routable.
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
/// Returns `true` if the given IPv4 address is a globally routable public address.
+2
View File
@@ -1,3 +1,5 @@
//! Axum middleware for applying security headers to responses.
use axum::extract::Request;
use axum::http::header::{self, HeaderValue};
use axum::middleware::Next;
+2
View File
@@ -1,3 +1,5 @@
//! Axum router construction with host-based routing for IPv4 and main domains.
use std::sync::Arc;
use axum::Router;
+2
View File
@@ -1,3 +1,5 @@
//! Embedded static file serving with immutable cache headers.
use std::collections::HashMap;
use std::sync::LazyLock;
+8 -6
View File
@@ -1,3 +1,5 @@
//! User-agent detection for distinguishing CLI/HTTP-library clients from browsers.
const CLI_PREFIXES: &[&str] = &[
"curl/",
"Wget/",
@@ -53,16 +55,16 @@ const HTTP_LIB_PREFIXES: &[&str] = &[
"mint/",
];
fn matches_any_prefix(user_agent: &str, prefixes: &[&str]) -> bool {
prefixes.iter().any(|prefix| user_agent.starts_with(prefix))
}
fn is_cli_user_agent(user_agent: &str) -> bool {
CLI_PREFIXES
.iter()
.any(|prefix| user_agent.starts_with(prefix))
matches_any_prefix(user_agent, CLI_PREFIXES)
}
fn is_http_lib_user_agent(user_agent: &str) -> bool {
HTTP_LIB_PREFIXES
.iter()
.any(|prefix| user_agent.starts_with(prefix))
matches_any_prefix(user_agent, HTTP_LIB_PREFIXES)
}
pub fn is_plain_text_agent(user_agent: &str) -> bool {
+2
View File
@@ -1,3 +1,5 @@
//! Background database updater: downloads and hot-swaps the MMDB database on a daily schedule.
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};