Skip to content

Commit

Permalink
fix(proxies): reduce tray updating interval
Browse files Browse the repository at this point in the history
  • Loading branch information
greenhat616 committed Feb 20, 2024
1 parent eeea0ee commit 13b8dac
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 2 deletions.
1 change: 1 addition & 0 deletions backend/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions backend/tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ simd-json = "0.13.8"
runas = "=1.0.0" # blocked by https://github.com/mitsuhiko/rust-runas/issues/13
backon = "0.4.1"
rust-i18n = "3"
adler = "1.0.2"

[target.'cfg(windows)'.dependencies]
deelevate = "0.2.0"
Expand Down
15 changes: 13 additions & 2 deletions backend/tauri/src/core/clash/proxies.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
/// It is used to provide the unite interface between tray and frontend.
/// TODO: add a diff algorithm to reduce the data transfer, and the rerendering of the tray menu.
use super::{api, CLASH_API_DEFAULT_BACKOFF_STRATEGY};
use adler::adler32;
use anyhow::Result;
use backon::Retryable;
use log::warn;
Expand Down Expand Up @@ -193,6 +194,7 @@ impl Proxies {

pub struct ProxiesGuard {
inner: Proxies,
checksum: Option<u32>,
updated_at: u64,
sender: broadcast::Sender<()>,
}
Expand All @@ -203,6 +205,7 @@ impl ProxiesGuard {
PROXIES.get_or_init(|| {
let (tx, _) = broadcast::channel(5); // 默认提供 5 个消费位置,提供一定的缓冲
Arc::new(RwLock::new(ProxiesGuard {
checksum: None,
sender: tx,
inner: Proxies::default(),
updated_at: 0,
Expand All @@ -214,9 +217,10 @@ impl ProxiesGuard {
self.sender.subscribe()
}

pub fn replace(&mut self, proxies: Proxies) {
pub fn replace(&mut self, proxies: Proxies, checksum: u32) {
let now = chrono::Utc::now().timestamp() as u64;
self.inner = proxies;
self.checksum = Some(checksum);
self.updated_at = now;

if let Err(e) = self.sender.send(()) {
Expand Down Expand Up @@ -256,9 +260,16 @@ type ProxiesGuardSingleton = &'static Arc<RwLock<ProxiesGuard>>;
impl ProxiesGuardExt for ProxiesGuardSingleton {
async fn update(&self) -> Result<()> {
let proxies = Proxies::fetch().await?;
let buf = simd_json::to_string(&proxies)?;
let checksum = adler32(buf.as_bytes())?;
{
self.write().replace(proxies);
let reader = self.read();
if reader.checksum == Some(checksum) {
return Ok(());
}
}
let mut writer = self.write();
writer.replace(proxies, checksum);
Ok(())
}

Expand Down

0 comments on commit 13b8dac

Please sign in to comment.