From 297958d0dbb96b2be0d00141583e22309bb8e347 Mon Sep 17 00:00:00 2001 From: dev0 Date: Wed, 27 Sep 2023 23:15:58 +1000 Subject: [PATCH] some perf improves --- clash/tests/data/config/rules.yaml | 1 + clash_lib/src/app/logging.rs | 105 ++++++++++-------- clash_lib/src/app/profile/mod.rs | 22 ++-- .../app/remote_content_manager/healthcheck.rs | 5 +- clash_lib/src/lib.rs | 13 +-- 5 files changed, 74 insertions(+), 72 deletions(-) diff --git a/clash/tests/data/config/rules.yaml b/clash/tests/data/config/rules.yaml index 57deb77bf..b0ce1a4a6 100644 --- a/clash/tests/data/config/rules.yaml +++ b/clash/tests/data/config/rules.yaml @@ -222,6 +222,7 @@ rules: - DOMAIN,google.com,select - SRC-IP-CIDR,192.168.1.1/24,DIRECT - GEOIP,CN,DIRECT + - IP-CIDR,10.0.0.11/32,select - DST-PORT,53,trojan - SRC-PORT,7777,DIRECT - MATCH, DIRECT diff --git a/clash_lib/src/app/logging.rs b/clash_lib/src/app/logging.rs index 557dd7109..0c4ca4b4e 100644 --- a/clash_lib/src/app/logging.rs +++ b/clash_lib/src/app/logging.rs @@ -69,57 +69,64 @@ where } pub fn setup_logging(level: LogLevel, collector: EventCollector) -> anyhow::Result<()> { - let filter = EnvFilter::builder() - .with_default_directive( - format!("clash={}", level) - .parse::() - .unwrap() - .into(), - ) - .from_env_lossy(); - - let jaeger = if let Ok(jager_endpoint) = std::env::var("JAGER_ENDPOINT") { - global::set_text_map_propagator(opentelemetry_jaeger::Propagator::new()); - - let tracer = opentelemetry_jaeger::new_collector_pipeline() - .with_service_name("clash-rs") - .with_endpoint(jager_endpoint) - .with_hyper() - .install_batch(opentelemetry::runtime::Tokio)?; - - Some(tracing_opentelemetry::layer().with_tracer(tracer)) - } else { - None - }; - - let ios_os_log = if cfg!(target_os = "ios") { - Some(OsLogger::new("com.watfaq.clash", "default")) - } else { - None - }; - - let subscriber = tracing_subscriber::registry() - .with(jaeger) - .with(filter) - .with(collector) - .with( - tracing_subscriber::fmt::Layer::new() - .with_ansi(std::io::stdout().is_terminal()) - .pretty() - .with_file(true) - .with_line_number(true) - .with_writer(std::io::stdout), - ) - .with(ios_os_log); - - let v = tracing::subscriber::set_global_default(subscriber) - .map_err(|x| anyhow!("setup logging error: {}", x))?; - - if let Ok(jager_endpiont) = std::env::var("JAGER_ENDPOINT") { - debug!("jager endpoint: {}", jager_endpiont); + #[cfg(feature = "tracing")] + { + console_subscriber::init(); + } + #[cfg(not(feature = "tracing"))] + { + let filter = EnvFilter::builder() + .with_default_directive( + format!("clash={}", level) + .parse::() + .unwrap() + .into(), + ) + .from_env_lossy(); + + let jaeger = if let Ok(jager_endpoint) = std::env::var("JAGER_ENDPOINT") { + global::set_text_map_propagator(opentelemetry_jaeger::Propagator::new()); + + let tracer = opentelemetry_jaeger::new_collector_pipeline() + .with_service_name("clash-rs") + .with_endpoint(jager_endpoint) + .with_hyper() + .install_batch(opentelemetry::runtime::Tokio)?; + + Some(tracing_opentelemetry::layer().with_tracer(tracer)) + } else { + None + }; + + let ios_os_log = if cfg!(target_os = "ios") { + Some(OsLogger::new("com.watfaq.clash", "default")) + } else { + None + }; + + let subscriber = tracing_subscriber::registry() + .with(jaeger) + .with(filter) + .with(collector) + .with( + tracing_subscriber::fmt::Layer::new() + .with_ansi(std::io::stdout().is_terminal()) + .pretty() + .with_file(true) + .with_line_number(true) + .with_writer(std::io::stdout), + ) + .with(ios_os_log); + + tracing::subscriber::set_global_default(subscriber) + .map_err(|x| anyhow!("setup logging error: {}", x))?; + + if let Ok(jager_endpiont) = std::env::var("JAGER_ENDPOINT") { + debug!("jager endpoint: {}", jager_endpiont); + } } - Ok(v) + Ok(()) } struct EventVisitor<'a>(&'a mut Vec); diff --git a/clash_lib/src/app/profile/mod.rs b/clash_lib/src/app/profile/mod.rs index 59275d2ac..61a64fee6 100644 --- a/clash_lib/src/app/profile/mod.rs +++ b/clash_lib/src/app/profile/mod.rs @@ -11,11 +11,11 @@ struct Db { } #[derive(Clone)] -pub struct ThreadSafeCacheFile(Arc>); +pub struct ThreadSafeCacheFile(Arc>); impl ThreadSafeCacheFile { pub fn new(path: &str, store_selected: bool) -> Self { - let store = Arc::new(tokio::sync::Mutex::new(CacheFile::new( + let store = Arc::new(tokio::sync::RwLock::new(CacheFile::new( path, store_selected, ))); @@ -28,7 +28,7 @@ impl ThreadSafeCacheFile { let store = store_clone; loop { tokio::time::sleep(tokio::time::Duration::from_secs(10)).await; - let db = store.lock().await.db.clone(); + let db = store.read().await.db.clone(); let s = match serde_yaml::to_string(&db) { Ok(s) => s, Err(e) => { @@ -50,14 +50,14 @@ impl ThreadSafeCacheFile { } pub async fn set_selected(&self, group: &str, server: &str) { - let mut g = self.0.lock().await; + let mut g = self.0.write().await; if g.store_selected() { g.set_selected(group, server); } } pub async fn get_selected(&self, group: &str) -> Option { - let g = self.0.lock().await; + let g = self.0.read().await; if g.store_selected() { g.db.selected.get(group).map(Clone::clone) } else { @@ -67,28 +67,28 @@ impl ThreadSafeCacheFile { #[allow(dead_code)] pub async fn get_selected_map(&self) -> HashMap { - let g = self.0.lock().await; + let g = self.0.read().await; if g.store_selected() { - self.0.lock().await.get_selected_map() + g.get_selected_map() } else { HashMap::new() } } pub async fn set_ip_to_host(&self, ip: &str, host: &str) { - self.0.lock().await.set_ip_to_host(ip, host); + self.0.write().await.set_ip_to_host(ip, host); } pub async fn set_host_to_ip(&self, host: &str, ip: &str) { - self.0.lock().await.set_host_to_ip(host, ip); + self.0.write().await.set_host_to_ip(host, ip); } pub async fn get_fake_ip(&self, ip_or_host: &str) -> Option { - self.0.lock().await.get_fake_ip(ip_or_host) + self.0.read().await.get_fake_ip(ip_or_host) } pub async fn delete_fake_ip_pair(&self, ip: &str, host: &str) { - self.0.lock().await.delete_fake_ip_pair(ip, host); + self.0.write().await.delete_fake_ip_pair(ip, host); } } diff --git a/clash_lib/src/app/remote_content_manager/healthcheck.rs b/clash_lib/src/app/remote_content_manager/healthcheck.rs index f10d7f250..527cd9423 100644 --- a/clash_lib/src/app/remote_content_manager/healthcheck.rs +++ b/clash_lib/src/app/remote_content_manager/healthcheck.rs @@ -65,9 +65,10 @@ impl HealthCheck { _ = ticker.tick() => { pm_debug!("healthcheck ticking: {}, lazy: {}", url, lazy); let now = tokio::time::Instant::now(); - if !lazy || now.duration_since(inner.read().await.last_check).as_secs() >= interval { + let mut inner = inner.write().await; + if !lazy || now.duration_since(inner.last_check).as_secs() >= interval { proxy_manager.check(&proxies, &url, None).await; - inner.write().await.last_check = now; + inner.last_check = now; } }, } diff --git a/clash_lib/src/lib.rs b/clash_lib/src/lib.rs index 4d706910c..e2be61208 100644 --- a/clash_lib/src/lib.rs +++ b/clash_lib/src/lib.rs @@ -105,9 +105,6 @@ pub fn shutdown() -> bool { } async fn start_async(opts: Options) -> Result<(), Error> { - #[cfg(feature = "tracing")] - console_subscriber::init(); - let (shutdown_tx, mut shutdown_rx) = mpsc::channel(1); RUNTIME_CONTROLLER.set(std::sync::RwLock::new(RuntimeController { shutdown_tx })); @@ -121,14 +118,10 @@ async fn start_async(opts: Options) -> Result<(), Error> { let (log_tx, _) = broadcast::channel(100); - #[cfg(not(feature = "tracing"))] - { - let log_collector = app::logging::EventCollector::new(vec![log_tx.clone()]); + let log_collector = app::logging::EventCollector::new(vec![log_tx.clone()]); - app::logging::setup_logging(config.general.log_level, log_collector).map_err(|x| { - Error::InvalidConfig(format!("failed to setup logging: {}", x.to_string())) - })?; - } + app::logging::setup_logging(config.general.log_level, log_collector) + .map_err(|x| Error::InvalidConfig(format!("failed to setup logging: {}", x.to_string())))?; let mut tasks = Vec::::new(); let mut runners = Vec::new();