Skip to content

Commit 80005de

Browse files
zdzCopilot
andcommitted
refactor: reduce clones via Arc, fix clippy pedantic warnings
- Replace Cow<HostStat> with Arc<HostStat> in stat_map and StatsResp to eliminate unnecessary deep copies; enable serde 'rc' feature - Migrate lazy_static! to std::sync::LazyLock (status.rs, sys_info.rs, stats.rs) - De-async handlers with no await (assets.rs, http.rs); fix axum compatibility - Fix truncating casts: usize/u64 as u32 -> try_from() with fallback - Simplify add_template generics to (&str, &str, String) - Fix similar-name bindings: notified->any_notified, notifiers->notify_list - Move const OS_LIST to module level to avoid items-after-statements lint - Use clone_from instead of = x.clone() where applicable - Fix vnstat calc_traffic: take &VnstatJson, remove unnecessary Result wrapper - Replace map_or(true, ...) with is_none_or(...) in http.rs - Add #[allow] annotations for: struct_excessive_bools, too_many_lines, unnecessary_wraps, missing_panics_doc, assertions_on_constants - Remove duplicate geoip match arm; use integer arithmetic for uptime - Add jwt usize::try_from cast; fix assertion on constants in main.rs Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent 9859b53 commit 80005de

25 files changed

Lines changed: 299 additions & 302 deletions

client/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ edition = "2021"
33
name = "stat_client"
44
version = "1.8.2"
55

6-
rust-version = "1.76"
6+
rust-version = "1.94"
77

88
authors = ["doge <doge.py@gmail.com>"]
99
categories = ["monitoring-tools"]

client/src/geoip/ip_api_com.rs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -40,17 +40,17 @@ impl From<IpApiResp> for IpInfo {
4040
fn from(resp: IpApiResp) -> Self {
4141
IpInfo {
4242
source: SOURCE.to_string(),
43-
query: resp.query.to_string(),
43+
query: resp.query.clone(),
4444

45-
continent: resp.continent.to_string(),
46-
country: resp.country.to_string(),
47-
region_name: resp.region_name.to_string(),
48-
city: resp.city.to_string(),
45+
continent: resp.continent.clone(),
46+
country: resp.country.clone(),
47+
region_name: resp.region_name.clone(),
48+
city: resp.city.clone(),
4949

50-
isp: resp.isp.to_string(),
51-
org: resp.org.to_string(),
52-
r#as: resp.r#as.to_string(),
53-
asname: resp.asname.to_string(),
50+
isp: resp.isp.clone(),
51+
org: resp.org.clone(),
52+
r#as: resp.r#as.clone(),
53+
asname: resp.asname.clone(),
5454

5555
lat: resp.lat,
5656
lon: resp.lon,

client/src/geoip/ip_sb.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -43,10 +43,10 @@ impl From<ApiResp> for IpInfo {
4343
region_name: resp.region,
4444
city: resp.city,
4545

46-
isp: resp.isp.to_string(),
47-
org: resp.organization.to_string(),
46+
isp: resp.isp.clone(),
47+
org: resp.organization.clone(),
4848
r#as: resp.asn.to_string(),
49-
asname: resp.asn_organization.to_string(),
49+
asname: resp.asn_organization.clone(),
5050

5151
lat: resp.latitude,
5252
lon: resp.longitude,

client/src/geoip/mod.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ where
4545
}
4646
resp.json::<T>()
4747
.await
48-
.map(|resp| resp.into())
48+
.map(std::convert::Into::into)
4949
.map_err(anyhow::Error::new)
5050
}
5151
Err(err) => Err(anyhow::Error::new(err)),
@@ -56,7 +56,6 @@ pub async fn get_ip_info(args: &Args) -> Result<IpInfo> {
5656
let source = args.ip_source.as_str();
5757
match source {
5858
"ip-api.com" => ip_api_com::get_ip_info(args).await,
59-
"ip.sb" => ip_sb::get_ip_info(args).await,
6059
"ipapi.co" => ipapi_co::get_ip_info(args).await,
6160
"myip.la" => myip_la::get_ip_info(args).await,
6261
_ => ip_sb::get_ip_info(args).await,

client/src/grpc.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,10 @@ pub async fn report(args: &Args, stat_base: &mut StatRequest) -> anyhow::Result<
1919
let auth_user: String;
2020
let ssr_auth: &[u8];
2121
if args.gid.is_empty() {
22-
auth_user = args.user.to_string();
22+
auth_user = args.user.clone();
2323
ssr_auth = b"single";
2424
} else {
25-
auth_user = args.gid.to_string();
25+
auth_user = args.gid.clone();
2626
ssr_auth = b"group";
2727
}
2828
let token = MetadataValue::try_from(format!("{}@_@{}", auth_user, args.pass))?;
@@ -55,7 +55,7 @@ pub async fn report(args: &Args, stat_base: &mut StatRequest) -> anyhow::Result<
5555
channel = Channel::from_shared(addr)?.tls_config(tls_config)?.connect().await?;
5656
} else {
5757
channel = Channel::from_shared(addr)?.connect().await?;
58-
};
58+
}
5959

6060
let timeout_channel = Timeout::new(channel, Duration::from_millis(3000));
6161
let grpc_client = ServerStatusClient::with_interceptor(timeout_channel, move |mut req: Request<()>| {
@@ -73,10 +73,10 @@ pub async fn report(args: &Args, stat_base: &mut StatRequest) -> anyhow::Result<
7373
let request = tonic::Request::new(stat_rt);
7474
match client.report(request).await {
7575
Ok(resp) => {
76-
info!("grpc report resp => {:?}", resp);
76+
info!("grpc report resp => {resp:?}");
7777
}
7878
Err(status) => {
79-
error!("grpc report status => {:?}", status);
79+
error!("grpc report status => {status:?}");
8080
}
8181
}
8282
});

client/src/main.rs

Lines changed: 20 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ pub static G_CONFIG: Lazy<Mutex<ClientConfig>> = Lazy::new(|| Mutex::new(ClientC
3939
// https://docs.rs/clap/latest/clap/_derive/index.html#command-attributes
4040
#[derive(Parser, Debug, Clone)]
4141
#[command(author, version = env!("APP_VERSION"), about, long_about = None)]
42+
#[allow(clippy::struct_excessive_bools)]
4243
pub struct Args {
4344
#[arg(short, long, env = "SSR_ADDR", default_value = "http://127.0.0.1:8080/report")]
4445
addr: String,
@@ -176,6 +177,7 @@ pub struct Args {
176177
}
177178

178179
impl Args {
180+
#[must_use]
179181
pub fn skip_iface(&self, name: &str) -> bool {
180182
if !self.iface.is_empty() {
181183
if self.iface.iter().any(|fa| name.eq(fa)) {
@@ -235,7 +237,7 @@ fn http_report(args: &Args, stat_base: &mut StatRequest) -> Result<()> {
235237
}
236238
retries += 1;
237239
let delay = Duration::from_secs(2u64.pow(retries)); // Exponential backoff
238-
eprintln!("Name resolution failed, retrying in {:?}...", delay);
240+
eprintln!("Name resolution failed, retrying in {delay:?}...");
239241
sleep(delay);
240242
}
241243
}
@@ -282,15 +284,15 @@ fn http_report(args: &Args, stat_base: &mut StatRequest) -> Result<()> {
282284
// dbg!(&body_data.as_ref().unwrap().len());
283285

284286
let client = http_client.clone();
285-
let url = args.addr.to_string();
286-
let auth_pass = args.pass.to_string();
287+
let url = args.addr.clone();
288+
let auth_pass = args.pass.clone();
287289
let auth_user: String;
288290
let ssr_auth: &str;
289291
if args.gid.is_empty() {
290-
auth_user = args.user.to_string();
292+
auth_user = args.user.clone();
291293
ssr_auth = "single";
292294
} else {
293-
auth_user = args.gid.to_string();
295+
auth_user = args.gid.clone();
294296
ssr_auth = "group";
295297
}
296298

@@ -307,10 +309,10 @@ fn http_report(args: &Args, stat_base: &mut StatRequest) -> Result<()> {
307309
.await
308310
{
309311
Ok(resp) => {
310-
info!("report resp => {:?}", resp);
312+
info!("report resp => {resp:?}");
311313
}
312314
Err(err) => {
313-
error!("report error => {:?}", err);
315+
error!("report error => {err:?}");
314316
}
315317
}
316318
});
@@ -326,13 +328,13 @@ async fn refresh_ip_info(args: &Args) {
326328
info!("get ip info from ip-api.com");
327329
match geoip::get_ip_info(args).await {
328330
Ok(ip_info) => {
329-
info!("refresh_ip_info succ => {:?}", ip_info);
331+
info!("refresh_ip_info succ => {ip_info:?}");
330332
if let Ok(mut o) = G_CONFIG.lock() {
331333
o.ip_info = Some(ip_info);
332334
}
333335
}
334336
Err(err) => {
335-
error!("refresh_ip_info error => {:?}", err);
337+
error!("refresh_ip_info error => {err:?}");
336338
}
337339
}
338340

@@ -357,8 +359,9 @@ async fn main() -> Result<()> {
357359
}
358360

359361
// support check
360-
if !sysinfo::IS_SUPPORTED_SYSTEM {
361-
panic!("当前系统不支持,请切换到Python跨平台版本!");
362+
#[allow(clippy::assertions_on_constants)]
363+
{
364+
assert!(sysinfo::IS_SUPPORTED_SYSTEM, "当前系统不支持,请切换到Python跨平台版本!");
362365
}
363366

364367
let sys_info = sys_info::collect_sys_info(&args);
@@ -403,7 +406,7 @@ async fn main() -> Result<()> {
403406
}
404407

405408
let mut stat_base = StatRequest {
406-
name: args.user.to_string(),
409+
name: args.user.clone(),
407410
frame: "data".to_string(),
408411
online4: ipv4,
409412
online6: ipv6,
@@ -414,24 +417,24 @@ async fn main() -> Result<()> {
414417
..Default::default()
415418
};
416419
if !args.gid.is_empty() {
417-
stat_base.gid = args.gid.to_owned();
420+
stat_base.gid = args.gid.clone();
418421
if stat_base.name.eq("h1") {
419422
stat_base.name = sys_id;
420423
}
421424
if args.alias.eq("unknown") {
422-
args.alias = stat_base.name.to_owned();
425+
args.alias = stat_base.name.clone();
423426
} else {
424-
stat_base.alias = args.alias.to_owned();
427+
stat_base.alias = args.alias.clone();
425428
}
426429
}
427430
if args.disable_notify {
428431
stat_base.notify = false;
429432
}
430433
if !args.host_type.is_empty() {
431-
stat_base.r#type = args.host_type.to_owned();
434+
stat_base.r#type = args.host_type.clone();
432435
}
433436
if !args.location.is_empty() {
434-
stat_base.location = args.location.to_owned();
437+
stat_base.location = args.location.clone();
435438
}
436439
// dbg!(&stat_base);
437440

client/src/status.rs

Lines changed: 18 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
#![allow(unused)]
2-
use lazy_static::lazy_static;
2+
#![allow(clippy::cast_precision_loss, clippy::cast_possible_truncation, clippy::cast_sign_loss, clippy::similar_names, clippy::many_single_char_names)]
33
use once_cell::sync::OnceCell;
44
use regex::Regex;
55
use std::collections::HashMap;
@@ -14,7 +14,7 @@ use std::net::{Shutdown, ToSocketAddrs};
1414
use std::process::Command;
1515
use std::str;
1616
use std::sync::Arc;
17-
use std::sync::Mutex;
17+
use std::sync::{LazyLock, Mutex};
1818
use std::thread;
1919
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
2020

@@ -54,10 +54,8 @@ pub fn get_loadavg() -> (f64, f64, f64) {
5454
.unwrap()
5555
}
5656

57-
static MEMORY_REGEX: &str = r#"^(?P<key>\S*):\s*(?P<value>\d*)\s*kB"#;
58-
lazy_static! {
59-
static ref MEMORY_REGEX_RE: Regex = Regex::new(MEMORY_REGEX).unwrap();
60-
}
57+
static MEMORY_REGEX: &str = r"^(?P<key>\S*):\s*(?P<value>\d*)\s*kB";
58+
static MEMORY_REGEX_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(MEMORY_REGEX).unwrap());
6159
pub fn get_memory() -> (u64, u64, u64, u64) {
6260
let file = File::open("/proc/meminfo").unwrap();
6361
let buf_reader = BufReader::new(file);
@@ -66,7 +64,7 @@ pub fn get_memory() -> (u64, u64, u64, u64) {
6664
let l = line.unwrap();
6765
if let Some(caps) = MEMORY_REGEX_RE.captures(&l) {
6866
res_dict.insert(caps["key"].to_string(), caps["value"].parse::<u64>().unwrap());
69-
};
67+
}
7068
}
7169

7270
let mem_total = res_dict["MemTotal"];
@@ -100,10 +98,8 @@ pub fn tupd() -> (u32, u32, u32, u32) {
10098
}
10199

102100
static TRAFFIC_REGEX: &str =
103-
r#"([^\s]+):[\s]{0,}(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)"#;
104-
lazy_static! {
105-
static ref TRAFFIC_REGEX_RE: Regex = Regex::new(TRAFFIC_REGEX).unwrap();
106-
}
101+
r"([^\s]+):[\s]{0,}(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)";
102+
static TRAFFIC_REGEX_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(TRAFFIC_REGEX).unwrap());
107103
pub fn get_sys_traffic(args: &Args) -> (u64, u64) {
108104
let (mut network_in, mut network_out) = (0, 0);
109105
let file = File::open("/proc/net/dev").unwrap();
@@ -142,7 +138,7 @@ pub fn get_hdd(stat: &mut StatRequest) {
142138
.stdout;
143139

144140
let _ = str::from_utf8(a).map(|content| {
145-
let vs = content.trim().split('\n').collect::<Vec<&str>>().to_vec();
141+
let vs = content.lines().collect::<Vec<&str>>();
146142

147143
for (idx, s) in vs.iter().enumerate() {
148144
// header
@@ -181,9 +177,7 @@ pub struct NetSpeed {
181177
pub avgtx: u64,
182178
}
183179

184-
lazy_static! {
185-
pub static ref G_NET_SPEED: Arc<Mutex<NetSpeed>> = Arc::new(Default::default());
186-
}
180+
pub static G_NET_SPEED: LazyLock<Arc<Mutex<NetSpeed>>> = LazyLock::new(|| Arc::new(Mutex::default()));
187181

188182
#[allow(unused)]
189183
pub fn start_net_speed_collect_t(args: &Args) {
@@ -226,9 +220,7 @@ pub fn start_net_speed_collect_t(args: &Args) {
226220
});
227221
}
228222

229-
lazy_static! {
230-
pub static ref G_CPU_PERCENT: Arc<Mutex<f64>> = Arc::new(Default::default());
231-
}
223+
pub static G_CPU_PERCENT: LazyLock<Arc<Mutex<f64>>> = LazyLock::new(|| Arc::new(Mutex::default()));
232224
#[allow(unused)]
233225
pub fn start_cpu_percent_collect_t() {
234226
let mut pre_cpu: Vec<u64> = vec![0, 0, 0, 0];
@@ -280,15 +272,15 @@ pub fn get_network(args: &Args) -> (bool, bool) {
280272
for (idx, probe_addr) in addrs.into_iter().enumerate() {
281273
let _ = probe_addr.to_socket_addrs().map(|mut iter| {
282274
if let Some(addr) = iter.next() {
283-
info!("{} => {}", probe_addr, addr);
275+
info!("{probe_addr} => {addr}");
284276

285277
let r = TcpStream::connect_timeout(&addr, Duration::from_millis(TIMEOUT_MS)).map(|s| {
286278
network[idx] = true;
287279
s.shutdown(Shutdown::Both)
288280
});
289281

290-
info!("{:?}", r);
291-
};
282+
info!("{r:?}");
283+
}
292284
});
293285
}
294286

@@ -339,9 +331,9 @@ fn start_ping_collect_t(data: &Arc<Mutex<PingData>>) {
339331
let time_cost_ms = instant.elapsed().as_millis();
340332

341333
if let Ok(mut o) = ping_data.lock() {
342-
o.ping_time = time_cost_ms as u32;
334+
o.ping_time = u32::try_from(time_cost_ms).unwrap_or(u32::MAX);
343335
if package_list.len() > 30 {
344-
o.lost_rate = package_lost * 100 / package_list.len() as u32;
336+
o.lost_rate = package_lost * 100 / u32::try_from(package_list.len()).unwrap_or(u32::MAX);
345337
}
346338
}
347339

@@ -356,21 +348,21 @@ pub static G_PING_10086: OnceCell<Arc<Mutex<PingData>>> = OnceCell::new();
356348
pub fn start_all_ping_collect_t(args: &Args) {
357349
G_PING_10010
358350
.set(Arc::new(Mutex::new(PingData {
359-
probe_uri: args.cu_addr.to_owned(),
351+
probe_uri: args.cu_addr.clone(),
360352
lost_rate: 0,
361353
ping_time: 0,
362354
})))
363355
.unwrap();
364356
G_PING_189
365357
.set(Arc::new(Mutex::new(PingData {
366-
probe_uri: args.ct_addr.to_owned(),
358+
probe_uri: args.ct_addr.clone(),
367359
lost_rate: 0,
368360
ping_time: 0,
369361
})))
370362
.unwrap();
371363
G_PING_10086
372364
.set(Arc::new(Mutex::new(PingData {
373-
probe_uri: args.cm_addr.to_owned(),
365+
probe_uri: args.cm_addr.clone(),
374366
lost_rate: 0,
375367
ping_time: 0,
376368
})))

0 commit comments

Comments
 (0)