refactor: 提取 Sidecar 启动配置为可配置常量
- 将 Sidecar 启动相关的硬编码配置提取为可配置的常量,并统一使用这些常量以提高代码可维护性和可读性。
This commit is contained in:
@@ -5,7 +5,29 @@ use tauri::Manager;
|
||||
use tauri_plugin_shell::process::{CommandChild, CommandEvent};
|
||||
use tauri_plugin_shell::ShellExt;
|
||||
|
||||
// 全局状态:存储 Sidecar 进程句柄
|
||||
// ===== 配置常量 =====
|
||||
|
||||
/// Sidecar Server 启动超时时间(秒)
|
||||
const STARTUP_TIMEOUT_SECS: u64 = 5;
|
||||
|
||||
/// 默认起始端口
|
||||
const DEFAULT_PORT: u16 = 3000;
|
||||
|
||||
/// 端口扫描范围(从起始端口开始扫描的端口数量)
|
||||
const PORT_SCAN_RANGE: u16 = 100;
|
||||
|
||||
/// 窗口默认宽度
|
||||
const DEFAULT_WINDOW_WIDTH: f64 = 1200.0;
|
||||
|
||||
/// 窗口默认高度
|
||||
const DEFAULT_WINDOW_HEIGHT: f64 = 800.0;
|
||||
|
||||
/// 窗口标题
|
||||
const WINDOW_TITLE: &str = "Tauri App";
|
||||
|
||||
// ===== 数据结构 =====
|
||||
|
||||
/// 全局状态:存储 Sidecar 进程句柄
|
||||
pub struct SidecarProcess(pub Mutex<Option<CommandChild>>);
|
||||
|
||||
// 检查端口是否可用
|
||||
@@ -17,7 +39,7 @@ async fn is_port_available(port: u16) -> bool {
|
||||
|
||||
// 查找可用端口
|
||||
async fn find_available_port(start: u16) -> u16 {
|
||||
for port in start..start + 100 {
|
||||
for port in start..start + PORT_SCAN_RANGE {
|
||||
if is_port_available(port).await {
|
||||
return port;
|
||||
}
|
||||
@@ -29,7 +51,7 @@ async fn find_available_port(start: u16) -> u16 {
|
||||
pub fn spawn_sidecar(app_handle: tauri::AppHandle) {
|
||||
tauri::async_runtime::spawn(async move {
|
||||
// 查找可用端口
|
||||
let port = find_available_port(3000).await;
|
||||
let port = find_available_port(DEFAULT_PORT).await;
|
||||
println!("使用端口: {}", port);
|
||||
|
||||
// 启动 sidecar
|
||||
@@ -48,7 +70,7 @@ pub fn spawn_sidecar(app_handle: tauri::AppHandle) {
|
||||
|
||||
// 监听 stdout,等待服务器就绪信号
|
||||
let start_time = std::time::Instant::now();
|
||||
let timeout = Duration::from_secs(5);
|
||||
let timeout = Duration::from_secs(STARTUP_TIMEOUT_SECS);
|
||||
let mut server_ready = false;
|
||||
|
||||
while let Some(event) = rx.recv().await {
|
||||
@@ -68,8 +90,8 @@ pub fn spawn_sidecar(app_handle: tauri::AppHandle) {
|
||||
"main",
|
||||
tauri::WebviewUrl::External(url.parse().unwrap()),
|
||||
)
|
||||
.title("Tauri App")
|
||||
.inner_size(1200.0, 800.0)
|
||||
.title(WINDOW_TITLE)
|
||||
.inner_size(DEFAULT_WINDOW_WIDTH, DEFAULT_WINDOW_HEIGHT)
|
||||
.center()
|
||||
.build()
|
||||
.expect("创建窗口失败");
|
||||
@@ -80,7 +102,10 @@ pub fn spawn_sidecar(app_handle: tauri::AppHandle) {
|
||||
|
||||
// 超时检查
|
||||
if start_time.elapsed() > timeout {
|
||||
eprintln!("✗ 启动超时: Server 未能在 5 秒内启动");
|
||||
eprintln!(
|
||||
"✗ 启动超时: Server 未能在 {} 秒内启动",
|
||||
STARTUP_TIMEOUT_SECS
|
||||
);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user