From 12ad0c85d95e46c4451cdb3de793d07d36283bb8 Mon Sep 17 00:00:00 2001 From: Tunglies <77394545+Tunglies@users.noreply.github.com> Date: Sat, 28 Nov 2026 21:49:56 +0800 Subject: [PATCH] refactor(lightweight): use the task countdown driver --- crates/clash-verge-task/src/countdown.rs | 60 +++++++++++++++++ crates/clash-verge-task/src/lib.rs | 1 + crates/clash-verge-task/tests/drivers.rs | 55 +++++++++++++++- src-tauri/src/core/lightweight.rs | 84 ++++++++---------------- 4 files changed, 143 insertions(+), 57 deletions(-) create mode 100644 crates/clash-verge-task/src/countdown.rs diff --git a/crates/clash-verge-task/src/countdown.rs b/crates/clash-verge-task/src/countdown.rs new file mode 100644 index 000000000..0a68e23f0 --- /dev/null +++ b/crates/clash-verge-task/src/countdown.rs @@ -0,0 +1,60 @@ +use std::{future::Future, time::Duration}; +use tokio::{sync::mpsc, time::sleep}; + +enum Command { + Arm(T), + Disarm, +} + +pub struct Countdown { + commands: mpsc::UnboundedSender>, +} + +impl Countdown { + pub fn arm(&self, input: T) { + let _ = self.commands.send(Command::Arm(input)); + } + + pub fn disarm(&self) { + let _ = self.commands.send(Command::Disarm); + } +} + +/// Create a countdown with a caller-owned driver. An active countdown ignores +/// additional arms. Disarm and channel closure take precedence over expiry. +/// +/// Return `None` from `delay` to reject an arm before starting the countdown. +/// The delay future may be dropped on disarm, including while it loads the duration. +pub fn new( + mut delay: impl FnMut(T) -> Option + Send, + mut elapsed: impl FnMut(T) + Send, +) -> (Countdown, impl Future + Send) +where + T: Copy + Send, + Fut: Future + Send, +{ + let (commands, mut receiver) = mpsc::unbounded_channel(); + let driver = async move { + while let Some(command) = receiver.recv().await { + let Command::Arm(input) = command else { continue }; + let Some(delay) = delay(input) else { continue }; + let countdown = async { sleep(delay.await).await }; + tokio::pin!(countdown); + loop { + tokio::select! { + biased; + command = receiver.recv() => match command { + Some(Command::Arm(_)) => {} + Some(Command::Disarm) => break, + None => return, + }, + () = &mut countdown => { + elapsed(input); + break; + } + } + } + } + }; + (Countdown { commands }, driver) +} diff --git a/crates/clash-verge-task/src/lib.rs b/crates/clash-verge-task/src/lib.rs index b864cfc91..890fb4a33 100644 --- a/crates/clash-verge-task/src/lib.rs +++ b/crates/clash-verge-task/src/lib.rs @@ -1,4 +1,5 @@ //! Single-owner task drivers with caller-managed runtime and cancellation. +pub mod countdown; pub mod scheduled_task; pub mod watch_task; diff --git a/crates/clash-verge-task/tests/drivers.rs b/crates/clash-verge-task/tests/drivers.rs index ac8e79e9a..f33a0a324 100644 --- a/crates/clash-verge-task/tests/drivers.rs +++ b/crates/clash-verge-task/tests/drivers.rs @@ -1,8 +1,9 @@ use clash_verge_task::{ + countdown, scheduled_task::{self, Mailbox, Next, ScheduledTask}, watch_task, }; -use std::{error::Error, time::Duration}; +use std::{error::Error, future::ready, time::Duration}; use tokio::{ sync::{mpsc, oneshot, watch}, time::{Instant, advance, timeout}, @@ -56,6 +57,58 @@ async fn receive(receiver: &mut mpsc::UnboundedReceiver) -> Result TestResult { + let delay = Duration::from_secs(4); + let (elapsed, mut events) = mpsc::unbounded_channel(); + let (countdown, driver) = countdown::new( + move |_| Some(ready(delay)), + move |input| { + let _ = elapsed.send(input); + }, + ); + let mut driver = Box::pin(driver); + let start = Instant::now(); + countdown.arm(1); + assert!(futures::poll!(driver.as_mut()).is_pending()); + advance(Duration::from_secs(2)).await; + countdown.arm(2); + let driver = tokio::spawn(driver); + + assert_eq!(receive(&mut events).await?, 1); + assert_eq!(Instant::now() - start, delay); + drop(countdown); + driver.await?; + assert!(events.try_recv().is_err()); + Ok(()) +} + +#[tokio::test(start_paused = true)] +async fn ready_disarm_wins_and_the_next_arm_starts_a_new_countdown() -> TestResult { + let delay = Duration::from_secs(4); + let (elapsed, mut events) = mpsc::unbounded_channel(); + let (countdown, driver) = countdown::new( + move |_| Some(ready(delay)), + move |input| { + let _ = elapsed.send(input); + }, + ); + let mut driver = Box::pin(driver); + countdown.arm(1); + assert!(futures::poll!(driver.as_mut()).is_pending()); + advance(delay).await; + countdown.disarm(); + countdown.arm(2); + let rearmed_at = Instant::now(); + let driver = tokio::spawn(driver); + + assert_eq!(receive(&mut events).await?, 2); + assert_eq!(Instant::now() - rearmed_at, delay); + drop(countdown); + driver.await?; + Ok(()) +} + #[tokio::test(start_paused = true)] async fn an_earlier_request_reschedules_an_idle_wait() -> TestResult { let (completed, mut results) = mpsc::unbounded_channel(); diff --git a/src-tauri/src/core/lightweight.rs b/src-tauri/src/core/lightweight.rs index 176353d43..f3dfc8d42 100644 --- a/src-tauri/src/core/lightweight.rs +++ b/src-tauri/src/core/lightweight.rs @@ -5,15 +5,15 @@ use crate::{ }; use clash_verge_logging::{Type, logging}; +use clash_verge_task::countdown::{self, Countdown}; use crate::utils::window_manager::WindowManager; use anyhow::Result; use parking_lot::Mutex; use std::sync::LazyLock; use std::sync::atomic::{AtomicU8, AtomicU64, Ordering}; +use std::time::Duration; use tauri::Listener as _; -use tokio::sync::mpsc; -use tokio::time::{Duration, sleep}; #[repr(u8)] #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -86,17 +86,26 @@ static WINDOW_LISTENERS: Mutex = Mutex::new(WindowListeners { }, }); -enum TimerCommand { - Arm(u64), - Disarm, -} - static TIMER_GENERATION: AtomicU64 = AtomicU64::new(0); -static TIMER_COMMANDS: LazyLock> = LazyLock::new(|| { - let (sender, receiver) = mpsc::unbounded_channel(); - AsyncHandler::spawn(move || run_light_weight_timer(receiver)); - sender +static COUNTDOWN: LazyLock> = LazyLock::new(|| { + let (countdown, driver) = countdown::new( + // Unlisten can be deferred while Tauri is delivering an event. + |generation| (generation == TIMER_GENERATION.load(Ordering::Acquire)).then(light_weight_delay), + |generation| { + if generation == TIMER_GENERATION.load(Ordering::Acquire) { + logging!( + info, + Type::Timer, + "Lightweight mode timer expired, entering lightweight mode" + ); + begin_lightweight_mode(); + AsyncHandler::spawn(refresh_lightweight_tray_state); + } + }, + ); + AsyncHandler::spawn(move || driver); + countdown }); #[inline] @@ -162,7 +171,7 @@ async fn enable_auto_light_weight_mode_at(generation: u64) { pub fn disable_auto_light_weight_mode() { logging!(info, Type::Lightweight, "关闭自动轻量模式"); TIMER_GENERATION.fetch_add(1, Ordering::AcqRel); - cancel_light_weight_timer(); + COUNTDOWN.disarm(); let mut listeners = WINDOW_LISTENERS.lock(); listeners.close.cancel(); listeners.focus.cancel(); @@ -171,7 +180,7 @@ pub fn disable_auto_light_weight_mode() { pub async fn entry_lightweight_mode() -> bool { let entered = begin_lightweight_mode(); if entered { - cancel_light_weight_timer(); + COUNTDOWN.disarm(); } refresh_lightweight_tray_state().await; entered @@ -203,7 +212,7 @@ pub async fn exit_lightweight_mode() -> bool { if auto_light_weight_is_enabled().await { setup_auto_light_weight_listeners(generation); } - cancel_light_weight_timer(); + COUNTDOWN.disarm(); record_state_and_log(LightweightState::Normal); refresh_lightweight_tray_state().await; true @@ -213,7 +222,7 @@ pub async fn exit_lightweight_mode() -> bool { pub async fn add_light_weight_timer() { let generation = TIMER_GENERATION.load(Ordering::Acquire); if auto_light_weight_is_enabled().await { - let _ = TIMER_COMMANDS.send(TimerCommand::Arm(generation)); + COUNTDOWN.arm(generation); } } @@ -230,51 +239,18 @@ fn setup_auto_light_weight_listeners(generation: u64) { return; } listeners.close.setup(move || { - let _ = TIMER_COMMANDS.send(TimerCommand::Arm(generation)); + COUNTDOWN.arm(generation); logging!(info, Type::Lightweight, "监听到关闭请求,开始轻量模式计时"); }); listeners.focus.setup(move || { if generation == TIMER_GENERATION.load(Ordering::Acquire) { - cancel_light_weight_timer(); + COUNTDOWN.disarm(); logging!(debug, Type::Lightweight, "监听到窗口获得焦点,取消轻量模式计时"); } }); } -async fn run_light_weight_timer(mut commands: mpsc::UnboundedReceiver) { - while let Some(command) = commands.recv().await { - let TimerCommand::Arm(generation) = command else { - continue; - }; - // Unlisten can be deferred while Tauri is delivering an event. - if generation != TIMER_GENERATION.load(Ordering::Acquire) { - continue; - } - - let countdown = wait_for_light_weight_timeout(); - tokio::pin!(countdown); - loop { - tokio::select! { - biased; - command = commands.recv() => match command { - Some(TimerCommand::Arm(_)) => {} - Some(TimerCommand::Disarm) => break, - None => return, - }, - () = &mut countdown => { - if generation == TIMER_GENERATION.load(Ordering::Acquire) { - logging!(info, Type::Timer, "Lightweight mode timer expired, entering lightweight mode"); - begin_lightweight_mode(); - AsyncHandler::spawn(refresh_lightweight_tray_state); - } - break; - } - } - } - } -} - -async fn wait_for_light_weight_timeout() { +async fn light_weight_delay() -> Duration { let once_by_minutes = Config::verge().await.data_arc().auto_light_weight_minutes.unwrap_or(10); logging!( info, @@ -282,9 +258,5 @@ async fn wait_for_light_weight_timeout() { "Lightweight mode timer set, entering lightweight mode in {} minutes", once_by_minutes ); - sleep(Duration::from_secs(once_by_minutes.saturating_mul(60))).await; -} - -fn cancel_light_weight_timer() { - let _ = TIMER_COMMANDS.send(TimerCommand::Disarm); + Duration::from_secs(once_by_minutes.saturating_mul(60)) }