refactor: optimize timer and network management with atomic operations

This commit is contained in:
Tunglies
2025-08-01 23:02:11 +08:00
parent 569e2d5192
commit 3eb2a5b3ef
6 changed files with 58 additions and 62 deletions

View File

@@ -2,7 +2,10 @@ use anyhow::Result;
use parking_lot::Mutex;
use reqwest::{Client, ClientBuilder, Proxy, RequestBuilder, Response};
use std::{
sync::{Arc, Once},
sync::{
atomic::{AtomicUsize, Ordering},
Arc, Once,
},
time::{Duration, Instant},
};
use tokio::runtime::{Builder, Runtime};
@@ -23,12 +26,12 @@ const POOL_IDLE_TIMEOUT: Duration = Duration::from_secs(15);
/// 网络管理器
pub struct NetworkManager {
runtime: Arc<Runtime>,
self_proxy_client: Arc<Mutex<Option<Client>>>,
system_proxy_client: Arc<Mutex<Option<Client>>>,
no_proxy_client: Arc<Mutex<Option<Client>>>,
self_proxy_client: Mutex<Option<Client>>,
system_proxy_client: Mutex<Option<Client>>,
no_proxy_client: Mutex<Option<Client>>,
init: Once,
last_connection_error: Arc<Mutex<Option<(Instant, String)>>>,
connection_error_count: Arc<Mutex<usize>>,
last_connection_error: Mutex<Option<(Instant, String)>>,
connection_error_count: AtomicUsize,
}
// Use singleton_lazy macro to replace lazy_static!
@@ -47,12 +50,12 @@ impl NetworkManager {
NetworkManager {
runtime: Arc::new(runtime),
self_proxy_client: Arc::new(Mutex::new(None)),
system_proxy_client: Arc::new(Mutex::new(None)),
no_proxy_client: Arc::new(Mutex::new(None)),
self_proxy_client: Mutex::new(None),
system_proxy_client: Mutex::new(None),
no_proxy_client: Mutex::new(None),
init: Once::new(),
last_connection_error: Arc::new(Mutex::new(None)),
connection_error_count: Arc::new(Mutex::new(0)),
last_connection_error: Mutex::new(None),
connection_error_count: AtomicUsize::new(0),
}
}
@@ -85,12 +88,11 @@ impl NetworkManager {
let mut last_error = self.last_connection_error.lock();
*last_error = Some((Instant::now(), error.to_string()));
let mut error_count = self.connection_error_count.lock();
*error_count += 1;
self.connection_error_count.fetch_add(1, Ordering::Relaxed);
}
fn should_reset_clients(&self) -> bool {
let error_count = *self.connection_error_count.lock();
let error_count = self.connection_error_count.load(Ordering::Relaxed);
let last_error = self.last_connection_error.lock();
if error_count > 5 {
@@ -120,10 +122,7 @@ impl NetworkManager {
let mut client = self.no_proxy_client.lock();
*client = None;
}
{
let mut error_count = self.connection_error_count.lock();
*error_count = 0;
}
self.connection_error_count.store(0, Ordering::Relaxed);
}
/// 创建带有自定义选项的HTTP请求