refactor(core): optimize RunningMode handling and improve state management

This commit is contained in:
Tunglies
2025-10-28 19:16:42 +08:00
parent 2af0af0837
commit 2a7ccb5bde
4 changed files with 23 additions and 18 deletions
+10 -9
View File
@@ -15,12 +15,13 @@ use anyhow::Result;
use compact_str::CompactString;
use flexi_logger::DeferredNow;
use log::Level;
use scopeguard::defer;
use std::collections::VecDeque;
use tauri_plugin_shell::ShellExt;
impl CoreManager {
pub async fn get_clash_logs(&self) -> Result<VecDeque<CompactString>> {
match self.get_running_mode() {
match *self.get_running_mode() {
RunningMode::Service => service::get_clash_logs_by_service().await,
RunningMode::Sidecar => Ok(ClashLogger::global().get_logs().clone()),
RunningMode::NotRunning => Ok(VecDeque::new()),
@@ -49,11 +50,8 @@ impl CoreManager {
let pid = child.pid();
logging!(trace, Type::Core, "Sidecar started with PID: {}", pid);
{
let mut state = self.state.lock();
state.child_sidecar = Some(CommandChildGuard::new(child));
state.running_mode = RunningMode::Sidecar;
}
self.set_running_child_sidecar(CommandChildGuard::new(child));
self.set_running_mode(RunningMode::Sidecar);
let shared_writer: SharedWriter =
std::sync::Arc::new(tokio::sync::Mutex::new(sidecar_writer().await?));
@@ -93,14 +91,15 @@ impl CoreManager {
pub(super) fn stop_core_by_sidecar(&self) -> Result<()> {
logging!(info, Type::Core, "Stopping sidecar");
defer! {
self.set_running_mode(RunningMode::NotRunning);
}
let mut state = self.state.lock();
if let Some(child) = state.child_sidecar.take() {
let pid = child.pid();
drop(child);
logging!(trace, Type::Core, "Sidecar stopped (PID: {:?})", pid);
}
state.running_mode = RunningMode::NotRunning;
Ok(())
}
@@ -114,8 +113,10 @@ impl CoreManager {
pub(super) async fn stop_core_by_service(&self) -> Result<()> {
logging!(info, Type::Core, "Stopping service");
defer! {
self.set_running_mode(RunningMode::NotRunning);
}
service::stop_core_by_service().await?;
self.set_running_mode(RunningMode::NotRunning);
Ok(())
}
}