feat: 生成接口令牌并在线程里启动或重启后台
This commit is contained in:
Generated
+1
@@ -717,6 +717,7 @@ dependencies = [
|
||||
name = "desktop"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"getrandom 0.3.4",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tauri",
|
||||
|
||||
@@ -28,6 +28,7 @@ tauri-plugin-opener = "2"
|
||||
tauri-plugin-dialog = "2"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
getrandom = "0.3"
|
||||
tauri-plugin-single-instance = "2"
|
||||
windows-sys = { version = "0.61", features = [
|
||||
"Win32_Foundation",
|
||||
|
||||
+182
-57
@@ -1,17 +1,19 @@
|
||||
use std::net::{SocketAddr, TcpStream};
|
||||
use std::path::PathBuf;
|
||||
use std::net::TcpListener;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Child, Command, Stdio};
|
||||
use std::sync::atomic::{AtomicU16, Ordering};
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use tauri::Manager;
|
||||
|
||||
#[cfg(windows)]
|
||||
mod job;
|
||||
|
||||
static BACKEND: Mutex<Option<Child>> = Mutex::new(None);
|
||||
static PORT: AtomicU16 = AtomicU16::new(0);
|
||||
struct BackendState {
|
||||
child: Option<Child>,
|
||||
port: u16,
|
||||
token: String,
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
struct Launch {
|
||||
program: PathBuf,
|
||||
@@ -20,14 +22,50 @@ struct Launch {
|
||||
data_dir: PathBuf,
|
||||
}
|
||||
|
||||
fn pick_port() -> u16 {
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind local port");
|
||||
listener.local_addr().expect("local address").port()
|
||||
// 启动锁先于状态锁,避免重启和启动线程互相等待。
|
||||
static LAUNCH: Mutex<()> = Mutex::new(());
|
||||
static BACKEND: Mutex<BackendState> = Mutex::new(BackendState {
|
||||
child: None,
|
||||
port: 0,
|
||||
token: String::new(),
|
||||
error: None,
|
||||
});
|
||||
|
||||
#[derive(Clone, serde::Serialize)]
|
||||
struct BackendInfo {
|
||||
port: u16,
|
||||
token: String,
|
||||
alive: bool,
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
fn lock_launch() -> std::sync::MutexGuard<'static, ()> {
|
||||
LAUNCH.lock().unwrap_or_else(|error| error.into_inner())
|
||||
}
|
||||
|
||||
fn lock_backend() -> std::sync::MutexGuard<'static, BackendState> {
|
||||
BACKEND.lock().unwrap_or_else(|error| error.into_inner())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn backend_port() -> u16 {
|
||||
PORT.load(Ordering::SeqCst)
|
||||
lock_backend().port
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn backend_info() -> BackendInfo {
|
||||
let mut state = lock_backend();
|
||||
snapshot(&mut state)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn restart_backend(app: tauri::AppHandle) -> BackendInfo {
|
||||
let _guard = lock_launch();
|
||||
let mut state = lock_backend();
|
||||
stop_child(&mut state);
|
||||
prepare(&app, &mut state);
|
||||
spawn_child(&app, &mut state);
|
||||
snapshot(&mut state)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -36,6 +74,58 @@ fn write_sample_csv(path: String) -> Result<(), String> {
|
||||
std::fs::write(path, content).map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
fn snapshot(state: &mut BackendState) -> BackendInfo {
|
||||
let alive = refresh_alive(state);
|
||||
BackendInfo {
|
||||
port: state.port,
|
||||
token: state.token.clone(),
|
||||
alive,
|
||||
error: state.error.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn refresh_alive(state: &mut BackendState) -> bool {
|
||||
let status = {
|
||||
let Some(child) = state.child.as_mut() else {
|
||||
return false;
|
||||
};
|
||||
child.try_wait()
|
||||
};
|
||||
match status {
|
||||
Ok(None) => true,
|
||||
Ok(Some(code)) => {
|
||||
let code = code
|
||||
.code()
|
||||
.map(|value| value.to_string())
|
||||
.unwrap_or_else(|| "未知".into());
|
||||
state.error = Some(format!("后台进程已退出({code})"));
|
||||
state.child = None;
|
||||
false
|
||||
}
|
||||
Err(error) => {
|
||||
state.error = Some(format!("无法检查后台进程:{error}"));
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn random_token() -> String {
|
||||
let mut bytes = [0u8; 32];
|
||||
getrandom::fill(&mut bytes).expect("系统随机数不可用");
|
||||
const HEX: &[u8; 16] = b"0123456789abcdef";
|
||||
let mut token = String::with_capacity(bytes.len() * 2);
|
||||
for byte in bytes {
|
||||
token.push(HEX[(byte >> 4) as usize] as char);
|
||||
token.push(HEX[(byte & 0x0f) as usize] as char);
|
||||
}
|
||||
token
|
||||
}
|
||||
|
||||
fn pick_port() -> u16 {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").expect("bind local port");
|
||||
listener.local_addr().expect("local address").port()
|
||||
}
|
||||
|
||||
fn repo_root() -> Option<PathBuf> {
|
||||
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.parent()
|
||||
@@ -43,7 +133,7 @@ fn repo_root() -> Option<PathBuf> {
|
||||
.map(PathBuf::from)
|
||||
}
|
||||
|
||||
fn bundled_backend(app: &tauri::App) -> Option<PathBuf> {
|
||||
fn bundled_backend(app: &tauri::AppHandle) -> Option<PathBuf> {
|
||||
let mut roots = Vec::new();
|
||||
if let Ok(dir) = app.path().resource_dir() {
|
||||
roots.push(dir);
|
||||
@@ -64,7 +154,7 @@ fn bundled_backend(app: &tauri::App) -> Option<PathBuf> {
|
||||
None
|
||||
}
|
||||
|
||||
fn installed_data_dir(app: &tauri::App) -> PathBuf {
|
||||
fn installed_data_dir(app: &tauri::AppHandle) -> PathBuf {
|
||||
let folder = app.config().identifier.clone();
|
||||
if let Ok(appdata) = std::env::var("APPDATA") {
|
||||
if !appdata.is_empty() {
|
||||
@@ -74,7 +164,7 @@ fn installed_data_dir(app: &tauri::App) -> PathBuf {
|
||||
PathBuf::from(".").join(folder)
|
||||
}
|
||||
|
||||
fn launch_plan(app: &tauri::App, port: u16) -> Option<Launch> {
|
||||
fn launch_plan(app: &tauri::AppHandle, port: u16) -> Option<Launch> {
|
||||
if !cfg!(debug_assertions) {
|
||||
if let Some(program) = bundled_backend(app) {
|
||||
let cwd = program.parent()?.to_path_buf();
|
||||
@@ -111,19 +201,28 @@ fn launch_plan(app: &tauri::App, port: u16) -> Option<Launch> {
|
||||
})
|
||||
}
|
||||
|
||||
fn start_backend(app: &tauri::App) {
|
||||
let port = pick_port();
|
||||
PORT.store(port, Ordering::SeqCst);
|
||||
let Some(plan) = launch_plan(app, port) else {
|
||||
fn prepare(_app: &tauri::AppHandle, state: &mut BackendState) {
|
||||
state.port = pick_port();
|
||||
state.token = random_token();
|
||||
state.error = None;
|
||||
}
|
||||
|
||||
fn spawn_child(app: &tauri::AppHandle, state: &mut BackendState) {
|
||||
let Some(plan) = launch_plan(app, state.port) else {
|
||||
state.error = Some("未找到后台程序".into());
|
||||
return;
|
||||
};
|
||||
let _ = std::fs::create_dir_all(&plan.data_dir);
|
||||
if let Err(error) = std::fs::create_dir_all(&plan.data_dir) {
|
||||
state.error = Some(format!("无法创建数据目录:{error}"));
|
||||
return;
|
||||
}
|
||||
let mut command = Command::new(&plan.program);
|
||||
command
|
||||
.args(&plan.args)
|
||||
.current_dir(&plan.cwd)
|
||||
.env("NQI_PORT", port.to_string())
|
||||
.env("NQI_PORT", state.port.to_string())
|
||||
.env("NQI_DATA_DIR", &plan.data_dir)
|
||||
.env("NQI_TOKEN", &state.token)
|
||||
.env("NQI_PARENT_PID", std::process::id().to_string())
|
||||
.env_remove("HTTP_PROXY")
|
||||
.env_remove("HTTPS_PROXY")
|
||||
@@ -132,13 +231,12 @@ fn start_backend(app: &tauri::App) {
|
||||
.env_remove("https_proxy")
|
||||
.env_remove("all_proxy")
|
||||
.stdin(Stdio::null());
|
||||
if let Ok(log) = std::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(plan.data_dir.join("backend.log"))
|
||||
{
|
||||
if let Ok(error_log) = log.try_clone() {
|
||||
command.stdout(Stdio::from(log)).stderr(Stdio::from(error_log));
|
||||
match open_log(&plan.data_dir.join("backend.log")) {
|
||||
Some((output, error)) => {
|
||||
command.stdout(output).stderr(error);
|
||||
}
|
||||
None => {
|
||||
command.stdout(Stdio::null()).stderr(Stdio::null());
|
||||
}
|
||||
}
|
||||
#[cfg(windows)]
|
||||
@@ -146,47 +244,60 @@ fn start_backend(app: &tauri::App) {
|
||||
use std::os::windows::process::CommandExt;
|
||||
command.creation_flags(job::creation_flags());
|
||||
}
|
||||
let Ok(child) = command.spawn() else {
|
||||
return;
|
||||
let child = match command.spawn() {
|
||||
Ok(child) => child,
|
||||
Err(error) => {
|
||||
state.error = Some(format!("无法启动后台:{error}"));
|
||||
return;
|
||||
}
|
||||
};
|
||||
#[cfg(windows)]
|
||||
let child = match job::adopt(child) {
|
||||
Ok(child) => child,
|
||||
Err(_) => return,
|
||||
Err(error) => {
|
||||
state.error = Some(error);
|
||||
return;
|
||||
}
|
||||
};
|
||||
*BACKEND.lock().expect("backend lock") = Some(child);
|
||||
wait_until_ready(port);
|
||||
state.child = Some(child);
|
||||
state.error = None;
|
||||
}
|
||||
|
||||
fn wait_until_ready(port: u16) {
|
||||
let address = SocketAddr::from(([127, 0, 0, 1], port));
|
||||
let deadline = Instant::now() + Duration::from_secs(20);
|
||||
while Instant::now() < deadline {
|
||||
if TcpStream::connect_timeout(&address, Duration::from_millis(200)).is_ok() {
|
||||
return;
|
||||
}
|
||||
let exited = BACKEND
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|mut slot| slot.as_mut().and_then(|child| child.try_wait().ok().flatten()))
|
||||
.is_some();
|
||||
if exited {
|
||||
return;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
fn open_log(path: &Path) -> Option<(Stdio, Stdio)> {
|
||||
let file = std::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(path)
|
||||
.ok()?;
|
||||
let error = file.try_clone().ok()?;
|
||||
Some((Stdio::from(file), Stdio::from(error)))
|
||||
}
|
||||
|
||||
fn stop_child(state: &mut BackendState) {
|
||||
#[cfg(windows)]
|
||||
job::terminate_tree();
|
||||
if let Some(mut child) = state.child.take() {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
}
|
||||
}
|
||||
|
||||
fn stop_backend() {
|
||||
#[cfg(windows)]
|
||||
job::terminate_tree();
|
||||
if let Ok(mut slot) = BACKEND.lock() {
|
||||
if let Some(child) = slot.as_mut() {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
}
|
||||
*slot = None;
|
||||
let _guard = lock_launch();
|
||||
let mut state = lock_backend();
|
||||
stop_child(&mut state);
|
||||
}
|
||||
|
||||
fn ensure_started(app: &tauri::AppHandle) {
|
||||
let _guard = lock_launch();
|
||||
let mut state = lock_backend();
|
||||
if refresh_alive(&mut state) {
|
||||
return;
|
||||
}
|
||||
if state.port == 0 || state.token.is_empty() {
|
||||
prepare(app, &mut state);
|
||||
}
|
||||
spawn_child(app, &mut state);
|
||||
}
|
||||
|
||||
fn focus_existing(app: &tauri::AppHandle) {
|
||||
@@ -221,9 +332,23 @@ pub fn run() {
|
||||
builder
|
||||
.plugin(tauri_plugin_opener::init())
|
||||
.plugin(tauri_plugin_dialog::init())
|
||||
.invoke_handler(tauri::generate_handler![backend_port, write_sample_csv])
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
backend_port,
|
||||
backend_info,
|
||||
restart_backend,
|
||||
write_sample_csv
|
||||
])
|
||||
.setup(|app| {
|
||||
start_backend(app);
|
||||
let handle = app.handle().clone();
|
||||
{
|
||||
let _guard = lock_launch();
|
||||
let mut state = lock_backend();
|
||||
prepare(&handle, &mut state);
|
||||
}
|
||||
std::thread::Builder::new()
|
||||
.name("nqi-backend".into())
|
||||
.spawn(move || ensure_started(&handle))
|
||||
.expect("无法创建后台启动线程");
|
||||
Ok(())
|
||||
})
|
||||
.build(tauri::generate_context!())
|
||||
|
||||
Reference in New Issue
Block a user