reqwest_proxy_pool/
pool.rs1use crate::config::{ProxyPoolConfig, ProxySelectionStrategy};
4use crate::error::NoProxyAvailable;
5use crate::proxy::{Proxy, ProxyStatus};
6use crate::utils;
7
8use futures::future;
9use log::{info, warn};
10use parking_lot::{Mutex, RwLock};
11use rand::Rng;
12use std::collections::HashSet;
13use std::sync::Arc;
14use std::time::Instant;
15use tokio::time::{self};
16
17pub struct ProxyPool {
19 proxies: RwLock<Vec<Proxy>>,
21 pub config: ProxyPoolConfig,
23 last_proxy_index: Mutex<usize>,
25}
26
27impl ProxyPool {
28 pub async fn new(config: ProxyPoolConfig) -> Result<Arc<Self>, reqwest::Error> {
31 let pool = Arc::new(Self {
32 proxies: RwLock::new(Vec::new()),
33 config,
34 last_proxy_index: Mutex::new(0),
35 });
36
37 pool.initialize_proxies().await?;
39
40 info!("Starting synchronous initial health check");
42 pool.check_all_proxies().await;
43
44 let (total, healthy) = pool.get_stats();
46 info!("Initial proxy pool status: {}/{} healthy proxies", healthy, total);
47
48 let pool_clone = Arc::clone(&pool);
50 tokio::spawn(async move {
51 loop {
52 time::sleep(pool_clone.config.health_check_interval).await;
53 pool_clone.check_all_proxies().await;
54
55 let (total, healthy) = pool_clone.get_stats();
56 info!("Proxy pool status update: {}/{} healthy proxies", healthy, total);
57 }
58 });
59
60 Ok(pool)
61 }
62
63 async fn initialize_proxies(&self) -> Result<(), reqwest::Error> {
65 info!("Initializing proxy pool from {} sources", self.config.sources.len());
66
67 let mut all_proxies = HashSet::new();
68
69 for source in &self.config.sources {
71 match utils::fetch_proxies_from_source(source).await {
72 Ok(source_proxies) => {
73 info!("Fetched {} proxies from {}", source_proxies.len(), source);
74 all_proxies.extend(source_proxies);
75 }
76 Err(e) => {
77 warn!("Failed to fetch proxies from {}: {}", source, e);
78 }
79 }
80 }
81
82 info!("Found {} unique proxies before health check", all_proxies.len());
83
84 {
86 let mut proxies = self.proxies.write();
87 for url in all_proxies {
88 proxies.push(Proxy::new(url, self.config.max_requests_per_second));
89 }
90 }
91
92 Ok(())
93 }
94
95 pub async fn check_all_proxies(&self) {
97 info!("Starting health check for all proxies");
98
99 let proxies = {
100 let guard = self.proxies.read();
101 guard.clone()
102 };
103
104 let mut futures = Vec::new();
105
106 for proxy in &proxies {
107 let proxy_url = proxy.url.clone();
108 let check_url = self.config.health_check_url.clone();
109 let timeout = self.config.health_check_timeout;
110
111 let future = async move {
112 let start = Instant::now();
113
114 let proxy_client = match reqwest::Client::builder()
116 .timeout(timeout)
117 .proxy(proxy.to_reqwest_proxy().unwrap())
118 .build()
119 {
120 Ok(client) => client,
121 Err(_) => return (proxy_url, false, None),
122 };
123
124 match proxy_client.get(&check_url).send().await {
126 Ok(resp) if resp.status().is_success() => {
127 let elapsed = start.elapsed().as_secs_f64();
128 (proxy_url, true, Some(elapsed))
129 }
130 _ => (proxy_url, false, None),
131 }
132 };
133
134 futures.push(future);
135 }
136
137 let results = future::join_all(futures).await;
139
140 let mut healthy_count = 0;
141 let mut unhealthy_count = 0;
142
143 {
145 let mut proxies = self.proxies.write();
146
147 for (url, is_healthy, response_time) in results {
148 if let Some(proxy) = proxies.iter_mut().find(|p| p.url == url) {
149 let old_status = proxy.status;
150
151 if is_healthy {
152 proxy.status = ProxyStatus::Healthy;
153 proxy.response_time = response_time;
154 healthy_count += 1;
155 } else {
156 proxy.status = ProxyStatus::Unhealthy;
157 unhealthy_count += 1;
158 }
159
160 if old_status != proxy.status {
162 info!("Proxy {} status changed: {:?} -> {:?}",
163 proxy.url, old_status, proxy.status);
164 }
165
166 proxy.last_check = Instant::now();
167 }
168 }
169 }
170
171 info!("Health check completed: {} healthy, {} unhealthy",
172 healthy_count, unhealthy_count);
173 }
174
175 pub fn get_proxy(&self) -> Result<Proxy, NoProxyAvailable> {
177 let proxies = self.proxies.read();
178
179 let healthy_proxies: Vec<&Proxy> = proxies.iter()
181 .filter(|p| p.status == ProxyStatus::Healthy)
182 .collect();
183
184 if healthy_proxies.is_empty() {
185 return Err(NoProxyAvailable);
186 }
187
188 let selected = match self.config.selection_strategy {
190 ProxySelectionStrategy::FastestResponse => {
191 healthy_proxies.iter()
193 .min_by(|a, b| {
194 a.response_time.unwrap_or(f64::MAX)
195 .partial_cmp(&b.response_time.unwrap_or(f64::MAX))
196 .unwrap_or(std::cmp::Ordering::Equal)
197 })
198 .unwrap()
199 },
200 ProxySelectionStrategy::MostReliable => {
201 healthy_proxies.iter()
203 .max_by(|a, b| {
204 a.success_rate().partial_cmp(&b.success_rate())
205 .unwrap_or(std::cmp::Ordering::Equal)
206 })
207 .unwrap()
208 },
209 ProxySelectionStrategy::Random => {
210 let mut rng = rand::rng();
212 let idx = rng.random_range(0..healthy_proxies.len());
213 &healthy_proxies[idx]
214 },
215 ProxySelectionStrategy::RoundRobin => {
216 let mut last_index = self.last_proxy_index.lock();
218 *last_index = (*last_index + 1) % healthy_proxies.len();
219 &healthy_proxies[*last_index]
220 }
221 };
222
223 Ok((*selected).clone())
224 }
225
226 pub fn report_proxy_success(&self, url: &str) {
228 let mut proxies = self.proxies.write();
229 if let Some(proxy) = proxies.iter_mut().find(|p| p.url == url) {
230 proxy.success_count += 1;
231 proxy.status = ProxyStatus::Healthy;
232 }
233 }
234
235 pub fn report_proxy_failure(&self, url: &str) {
237 let mut proxies = self.proxies.write();
238 if let Some(proxy) = proxies.iter_mut().find(|p| p.url == url) {
239 proxy.failure_count += 1;
240
241 let failure_ratio = proxy.failure_count as f64 /
243 (proxy.success_count + proxy.failure_count) as f64;
244
245 if failure_ratio > 0.5 && proxy.failure_count >= 3 {
246 let old_status = proxy.status;
247 proxy.status = ProxyStatus::Unhealthy;
248
249 if old_status != ProxyStatus::Unhealthy {
250 warn!("Proxy {} marked unhealthy: {} failures, {} successes",
251 proxy.url, proxy.failure_count, proxy.success_count);
252 }
253 }
254 }
255 }
256
257 pub fn get_stats(&self) -> (usize, usize) {
259 let proxies = self.proxies.read();
260 let total = proxies.len();
261 let healthy = proxies.iter()
262 .filter(|p| p.status == ProxyStatus::Healthy)
263 .count();
264
265 (total, healthy)
266 }
267}