refactor: streamline error handling and resource management in various modules

This commit is contained in:
Tunglies
2025-11-06 10:18:20 +08:00
Unverified
parent 671ac2ebed
commit 69a706b438
13 changed files with 66 additions and 50 deletions

View File

@@ -43,18 +43,20 @@ impl<T: Clone> Draft<T> {
{
// 先获得写锁以创建或取出草稿 Arc 的可变引用位置
let mut guard = self.inner.write();
if guard.1.is_none() {
// 创建草稿 snapshotArc clonecheap
guard.1 = Some(Arc::clone(&guard.0));
}
// 此时 guaranteed: guard.1 is Some(Arc<Box<T>>)
#[allow(clippy::unwrap_used)]
let arc_box = guard.1.as_mut().unwrap();
let mut draft_arc = if guard.1.is_none() {
Arc::clone(&guard.0)
} else {
#[allow(clippy::unwrap_used)]
guard.1.take().unwrap()
};
drop(guard);
// Arc::make_mut: 如果只有一个引用则返回可变引用;否则会克隆底层 Box<T>(要求 T: Clone
let boxed = Arc::make_mut(arc_box); // &mut Box<T>
let boxed = Arc::make_mut(&mut draft_arc); // &mut Box<T>
// 对 Box<T> 解引用得到 &mut T
f(&mut **boxed)
let result = f(&mut **boxed);
// 恢复修改后的草稿 Arc
self.inner.write().1 = Some(draft_arc);
result
}
/// 将草稿提交到已提交位置(替换),并清除草稿
@@ -90,8 +92,7 @@ impl<T: Clone> Draft<T> {
let (new_local, res) = f(local).await?;
// 将新的 Box<T> 放到已提交位置(包进 Arc
let mut guard = self.inner.write();
guard.0 = Arc::new(new_local);
self.inner.write().0 = Arc::new(new_local);
Ok(res)
}

View File

@@ -80,8 +80,7 @@ impl NetworkManager {
}
async fn record_connection_error(&self, error: &str) {
let mut last_error = self.last_connection_error.lock().await;
*last_error = Some((Instant::now(), error.into()));
*self.last_connection_error.lock().await = Some((Instant::now(), error.into()));
let mut count = self.connection_error_count.lock().await;
*count += 1;
@@ -89,13 +88,11 @@ impl NetworkManager {
async fn should_reset_clients(&self) -> bool {
let count = *self.connection_error_count.lock().await;
let last_error_guard = self.last_connection_error.lock().await;
if count > 5 {
return true;
}
if let Some((time, _)) = &*last_error_guard
if let Some((time, _)) = &*self.last_connection_error.lock().await
&& time.elapsed() < Duration::from_secs(30)
&& count > 2
{

View File

@@ -54,9 +54,7 @@ fn get_ui_ready_notify() -> &'static Arc<Notify> {
// 更新UI准备阶段
pub fn update_ui_ready_stage(stage: UiReadyStage) {
let state = get_ui_ready_state();
let mut stage_lock = state.stage.write();
*stage_lock = stage;
*state.stage.write() = stage;
// 如果是最终阶段标记UI完全就绪
if stage == UiReadyStage::Ready {
mark_ui_ready();

View File

@@ -81,6 +81,7 @@ fn should_handle_window_operation() -> bool {
if elapsed >= Duration::from_millis(WINDOW_OPERATION_DEBOUNCE_MS) {
*last_operation = now;
drop(last_operation);
WINDOW_OPERATION_IN_PROGRESS.store(true, Ordering::Release);
logging!(info, Type::Window, "[防抖] 窗口操作被允许执行");
true