fix: add recovery lock to prevent concurrency issues during lightweight mode exit

This commit is contained in:
wonfen
2025-04-21 12:20:55 +08:00
parent 824ad9fa29
commit dc46eb9d21
3 changed files with 88 additions and 11 deletions

View File

@@ -1,6 +1,6 @@
use crate::{
config::Config,
core::{handle, timer::Timer, tray::Tray},
core::{handle, timer::Timer},
log_err, logging, logging_error,
utils::logging::Type,
AppHandleManager,
@@ -9,8 +9,9 @@ use crate::{
use anyhow::{Context, Result};
use delay_timer::prelude::TaskBuilder;
use once_cell::sync::OnceCell;
use parking_lot::RwLock;
use parking_lot::{Mutex, RwLock};
use std::sync::Arc;
use std::time::{Duration, Instant};
use tauri::{Listener, Manager};
pub static AUTO_LIGHT_WEIGHT_MODE_INIT: OnceCell<()> = OnceCell::new();
@@ -20,10 +21,17 @@ const LIGHT_WEIGHT_TASK_UID: &str = "light_weight_task";
// 轻量模式状态标志
static IS_LIGHTWEIGHT_MODE: OnceCell<Arc<RwLock<bool>>> = OnceCell::new();
// 添加一个锁来防止并发退出轻量模式
static EXIT_LOCK: OnceCell<Mutex<(bool, Instant)>> = OnceCell::new();
fn get_lightweight_mode() -> &'static Arc<RwLock<bool>> {
IS_LIGHTWEIGHT_MODE.get_or_init(|| Arc::new(RwLock::new(false)))
}
fn get_exit_lock() -> &'static Mutex<(bool, Instant)> {
EXIT_LOCK.get_or_init(|| Mutex::new((false, Instant::now())))
}
// 检查是否处于轻量模式
pub fn is_in_lightweight_mode() -> bool {
*get_lightweight_mode().read()
@@ -64,12 +72,35 @@ pub fn entry_lightweight_mode() {
// 标记已进入轻量模式
set_lightweight_mode(true);
let _ = cancel_light_weight_timer();
logging_error!(Type::Tray, true, Tray::global().update_menu());
}
// 从轻量模式恢复
// 添加从轻量模式恢复的函数
pub fn exit_lightweight_mode() {
// 获取锁,检查是否已经有退出操作在进行中
let mut exit_lock = get_exit_lock().lock();
let (is_exiting, last_exit_time) = *exit_lock;
let now = Instant::now();
// 如果已经有一个退出操作在进行并且距离上次退出时间不超过2秒跳过本次退出
if is_exiting && now.duration_since(last_exit_time) < Duration::from_secs(2) {
logging!(
warn,
Type::Lightweight,
true,
"已有退出轻量模式操作正在进行中,跳过本次请求"
);
return;
}
*exit_lock = (true, now);
// 确保当前确实处于轻量模式才执行退出操作
if !is_in_lightweight_mode() {
logging!(info, Type::Lightweight, true, "当前不在轻量模式,无需退出");
exit_lock.0 = false;
return;
}
// 标记退出轻量模式
set_lightweight_mode(false);
logging!(info, Type::Lightweight, true, "正在退出轻量模式");
@@ -77,7 +108,8 @@ pub fn exit_lightweight_mode() {
// 重置UI就绪状态
crate::utils::resolve::reset_ui_ready();
logging_error!(Type::Tray, true, Tray::global().update_menu());
// 释放锁
exit_lock.0 = false;
}
pub fn add_light_weight_timer() {