refactor(lightweight): use the task countdown driver

This commit is contained in:
Tunglies
2026-11-28 21:49:56 +08:00
parent 63100bbc80
commit 12ad0c85d9
4 changed files with 143 additions and 57 deletions
+60
View File
@@ -0,0 +1,60 @@
use std::{future::Future, time::Duration};
use tokio::{sync::mpsc, time::sleep};
enum Command<T> {
Arm(T),
Disarm,
}
pub struct Countdown<T> {
commands: mpsc::UnboundedSender<Command<T>>,
}
impl<T> Countdown<T> {
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<T, Fut>(
mut delay: impl FnMut(T) -> Option<Fut> + Send,
mut elapsed: impl FnMut(T) + Send,
) -> (Countdown<T>, impl Future<Output = ()> + Send)
where
T: Copy + Send,
Fut: Future<Output = Duration> + 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)
}
+1
View File
@@ -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;
+54 -1
View File
@@ -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<T: Send>(receiver: &mut mpsc::UnboundedReceiver<T>) -> Result<T
.ok_or_else(|| "driver event channel closed".into())
}
#[tokio::test(start_paused = true)]
async fn countdown_keeps_the_first_arm_until_it_expires() -> 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();
+28 -56
View File
@@ -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<WindowListeners> = Mutex::new(WindowListeners {
},
});
enum TimerCommand {
Arm(u64),
Disarm,
}
static TIMER_GENERATION: AtomicU64 = AtomicU64::new(0);
static TIMER_COMMANDS: LazyLock<mpsc::UnboundedSender<TimerCommand>> = LazyLock::new(|| {
let (sender, receiver) = mpsc::unbounded_channel();
AsyncHandler::spawn(move || run_light_weight_timer(receiver));
sender
static COUNTDOWN: LazyLock<Countdown<u64>> = 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<TimerCommand>) {
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))
}