Skip to content

Commit

Permalink
some perf improves
Browse files Browse the repository at this point in the history
  • Loading branch information
ibigbug committed Sep 27, 2023
1 parent 5175bb5 commit 297958d
Show file tree
Hide file tree
Showing 5 changed files with 74 additions and 72 deletions.
1 change: 1 addition & 0 deletions clash/tests/data/config/rules.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
105 changes: 56 additions & 49 deletions clash_lib/src/app/logging.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<Directive>()
.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::<Directive>()
.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<String>);
Expand Down
22 changes: 11 additions & 11 deletions clash_lib/src/app/profile/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@ struct Db {
}

#[derive(Clone)]
pub struct ThreadSafeCacheFile(Arc<tokio::sync::Mutex<CacheFile>>);
pub struct ThreadSafeCacheFile(Arc<tokio::sync::RwLock<CacheFile>>);

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,
)));
Expand All @@ -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) => {
Expand All @@ -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<String> {
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 {
Expand All @@ -67,28 +67,28 @@ impl ThreadSafeCacheFile {

#[allow(dead_code)]
pub async fn get_selected_map(&self) -> HashMap<String, String> {
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<String> {
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);
}
}

Expand Down
5 changes: 3 additions & 2 deletions clash_lib/src/app/remote_content_manager/healthcheck.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
},
}
Expand Down
13 changes: 3 additions & 10 deletions clash_lib/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 }));
Expand All @@ -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::<Runner>::new();
let mut runners = Vec::new();
Expand Down

0 comments on commit 297958d

Please sign in to comment.