use std::fmt;
use std::str::FromStr;
use std::time::Duration;
use crate::ScraperConfig;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TuningMode {
#[default]
Adaptive,
Conservative,
}
impl FromStr for TuningMode {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_ascii_lowercase().as_str() {
"adaptive" | "auto" | "fast" | "自适应" => Ok(Self::Adaptive),
"conservative" | "safe" | "low" | "保守" => Ok(Self::Conservative),
other => Err(format!(
"Unknown tuning mode: '{other}', expected 'adaptive' or 'conservative'"
)),
}
}
}
impl fmt::Display for TuningMode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Adaptive => write!(f, "adaptive"),
Self::Conservative => write!(f, "conservative"),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HardwareTier {
Micro,
Small,
Mid,
High,
Extreme,
}
impl HardwareTier {
pub fn name(&self) -> &'static str {
match self {
Self::Micro => "Micro (1C1GB class)",
Self::Small => "Small (2C2GB ~ 4C4GB class)",
Self::Mid => "Mid Desktop (8C16GB class / i7-10700)",
Self::High => "High-End Server (32C128GB class / EPYC 9B45)",
Self::Extreme => "Extreme Supernode (64C+ 128GB+ FD>=65k)",
}
}
}
pub use pagesift_policy::adaptive::{
AutonomousTuningEngine, PerformanceDiagnosis, ResponseSurfaceOptimizer, SafetyStatus,
SurfacePoint, TuningKnobs,
};
#[derive(Debug, Clone, Copy)]
pub struct HostHardware {
pub logical_cores: usize,
pub total_memory_bytes: u64,
pub fd_limit: usize,
pub tier: HardwareTier,
}
impl HostHardware {
pub fn detect() -> Self {
let cores = std::thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(4);
let mem_bytes =
detect_system_memory_bytes().unwrap_or((cores as u64) * 2 * 1024 * 1024 * 1024);
let fd_limit = detect_fd_limit();
let tier = classify_hardware(cores, mem_bytes, fd_limit);
Self {
logical_cores: cores,
total_memory_bytes: mem_bytes,
fd_limit,
tier,
}
}
pub fn memory_gb(&self) -> f64 {
self.total_memory_bytes as f64 / (1024.0 * 1024.0 * 1024.0)
}
}
#[derive(Debug, Clone)]
pub struct TuningProfile {
pub mode: TuningMode,
pub hardware: HostHardware,
pub global_concurrency: usize,
pub per_host_concurrency: usize,
pub mpsc_buffer_capacity: usize,
pub connect_timeout: Duration,
pub total_timeout: Duration,
pub max_body_bytes: usize,
}
impl TuningProfile {
pub fn new(mode: TuningMode) -> Self {
let hardware = HostHardware::detect();
Self::for_hardware(hardware, mode)
}
pub fn for_hardware(hw: HostHardware, mode: TuningMode) -> Self {
let cpu_capacity = match mode {
TuningMode::Conservative => (hw.logical_cores * 8).clamp(8, 512),
TuningMode::Adaptive => match hw.tier {
HardwareTier::Micro => 16,
HardwareTier::Small => 48,
HardwareTier::Mid => hw.logical_cores * 20,
HardwareTier::High => (hw.logical_cores * 24).clamp(320, 1536),
HardwareTier::Extreme => (hw.logical_cores * 24).clamp(1024, 4096),
},
};
let mem_capacity = (hw.total_memory_bytes / (2 * 1024 * 1024)) as usize;
let fd_capacity = (hw.fd_limit * 7) / 10;
let safe_concurrency = cpu_capacity.min(mem_capacity).min(fd_capacity).max(4);
let (conn_timeout, total_timeout, per_host) = match mode {
TuningMode::Conservative => (Duration::from_secs(4), Duration::from_secs(12), 2),
TuningMode::Adaptive => match hw.tier {
HardwareTier::Micro => (Duration::from_millis(4500), Duration::from_secs(12), 1),
HardwareTier::Small => (Duration::from_millis(4000), Duration::from_secs(10), 2),
HardwareTier::Mid => (
Duration::from_millis(3500),
Duration::from_secs(10),
2,
),
HardwareTier::High => (
Duration::from_millis(3500),
Duration::from_secs(10),
2,
),
HardwareTier::Extreme => (Duration::from_millis(3000), Duration::from_secs(8), 4),
},
};
Self {
mode,
hardware: hw,
global_concurrency: safe_concurrency,
per_host_concurrency: per_host,
mpsc_buffer_capacity: safe_concurrency * 2,
connect_timeout: conn_timeout,
total_timeout,
max_body_bytes: 15 * 1024 * 1024,
}
}
pub fn apply_to_config(&self, cfg: &mut ScraperConfig) {
cfg.fetcher.connect_timeout = self.connect_timeout;
cfg.fetcher.total_timeout = self.total_timeout;
cfg.fetcher.max_body_bytes = self.max_body_bytes;
cfg.policy.rate.global_concurrency = self.global_concurrency;
cfg.policy.rate.per_host_concurrency = self.per_host_concurrency;
}
}
fn detect_system_memory_bytes() -> Option<u64> {
if let Ok(content) = std::fs::read_to_string("/proc/meminfo") {
for line in content.lines() {
if line.starts_with("MemTotal:") {
let parts: Vec<&str> = line.split_whitespace().collect();
if parts.len() >= 2 {
if let Ok(kb) = parts[1].parse::<u64>() {
return Some(kb * 1024);
}
}
}
}
}
None
}
fn detect_fd_limit() -> usize {
if let Ok(content) = std::fs::read_to_string("/proc/self/limits") {
for line in content.lines() {
if line.contains("Max open files") {
let parts: Vec<&str> = line.split_whitespace().collect();
if parts.len() >= 5 {
if let Ok(soft) = parts[3].parse::<usize>() {
return soft;
}
}
}
}
}
4096
}
pub fn classify_hardware(cores: usize, mem_bytes: u64, _fd_limit: usize) -> HardwareTier {
let mem_gb = mem_bytes as f64 / (1024.0 * 1024.0 * 1024.0);
if cores >= 64 && mem_gb >= 96.0 {
HardwareTier::Extreme
} else if cores >= 24 && mem_gb >= 48.0 {
HardwareTier::High
} else if cores >= 6 && mem_gb >= 12.0 {
HardwareTier::Mid
} else if cores >= 2 && mem_gb >= 1.8 {
HardwareTier::Small
} else {
HardwareTier::Micro
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_tier_classification_safety() {
assert_eq!(
classify_hardware(128, 256 * 1024 * 1024 * 1024, 100000),
HardwareTier::Extreme
);
let tier_4c_256g = classify_hardware(4, 256 * 1024 * 1024 * 1024, 65535);
assert_ne!(tier_4c_256g, HardwareTier::Extreme);
assert_eq!(tier_4c_256g, HardwareTier::Small);
let hw_4c = HostHardware {
logical_cores: 4,
total_memory_bytes: 256 * 1024 * 1024 * 1024,
fd_limit: 65535,
tier: tier_4c_256g,
};
let profile_4c = TuningProfile::for_hardware(hw_4c, TuningMode::Adaptive);
assert!(profile_4c.global_concurrency <= 96);
let hw_epyc = HostHardware {
logical_cores: 32,
total_memory_bytes: 128 * 1024 * 1024 * 1024,
fd_limit: 1048576,
tier: HardwareTier::High,
};
let profile_epyc = TuningProfile::for_hardware(hw_epyc, TuningMode::Adaptive);
assert_eq!(profile_epyc.global_concurrency, 768);
assert_eq!(profile_epyc.connect_timeout, Duration::from_millis(3500));
assert_eq!(profile_epyc.total_timeout, Duration::from_secs(10));
}
}