feat: 改为安装包分发并使用动态端口

This commit is contained in:
2026-10-25 02:31:23 +08:00
parent 5ca491834e
commit f5779369a5
34 changed files with 392 additions and 49 deletions
+9
View File
@@ -1,3 +1,12 @@
use std::path::PathBuf;
fn main() {
if std::env::var("PROFILE").ok().as_deref() == Some("release") {
let backend = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../backend/build/nqi-backend/nqi-backend.exe");
if !backend.is_file() {
panic!("缺少打包后端 {}", backend.display());
}
}
tauri_build::build()
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.6 KiB

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.8 KiB

After

Width:  |  Height:  |  Size: 9.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 567 B

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.7 KiB

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.7 KiB

After

Width:  |  Height:  |  Size: 5.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.0 KiB

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 536 B

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.4 KiB

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 777 B

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1020 B

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 848 B

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 37 KiB

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.5 KiB

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

+128 -30
View File
@@ -1,54 +1,128 @@
use std::net::{SocketAddr, TcpStream};
use std::path::PathBuf;
use std::process::{Child, Command, Stdio};
use std::sync::atomic::{AtomicU16, Ordering};
use std::sync::Mutex;
use std::time::Duration;
use std::time::{Duration, Instant};
use tauri::Manager;
static BACKEND: Mutex<Option<Child>> = Mutex::new(None);
static PORT: AtomicU16 = AtomicU16::new(0);
fn backend_up() -> bool {
let address: SocketAddr = "127.0.0.1:8765".parse().expect("address");
TcpStream::connect_timeout(&address, Duration::from_millis(200)).is_ok()
struct Launch {
program: PathBuf,
args: Vec<String>,
cwd: PathBuf,
data_dir: PathBuf,
}
fn start_backend() {
if backend_up() {
return;
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()
}
#[tauri::command]
fn backend_port() -> u16 {
PORT.load(Ordering::SeqCst)
}
fn repo_root() -> Option<PathBuf> {
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.parent()
.and_then(|path| path.parent())
.map(PathBuf::from)
}
fn bundled_backend(app: &tauri::App) -> Option<PathBuf> {
let mut roots = Vec::new();
if let Ok(dir) = app.path().resource_dir() {
roots.push(dir);
}
let manifest = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let Some(repo) = manifest.parent().and_then(|path| path.parent()) else {
return;
};
let python = repo
if let Ok(dir) = app.path().executable_dir() {
roots.push(dir);
}
for root in roots {
for candidate in [
root.join("nqi-backend").join("nqi-backend.exe"),
root.join("resources").join("nqi-backend").join("nqi-backend.exe"),
] {
if candidate.is_file() {
return Some(candidate);
}
}
}
None
}
fn installed_data_dir(app: &tauri::App) -> PathBuf {
let folder = app.config().identifier.clone();
if let Ok(appdata) = std::env::var("APPDATA") {
if !appdata.is_empty() {
return PathBuf::from(appdata).join(folder);
}
}
PathBuf::from(".").join(folder)
}
fn launch_plan(app: &tauri::App, port: u16) -> Option<Launch> {
if !cfg!(debug_assertions) {
if let Some(program) = bundled_backend(app) {
let cwd = program.parent()?.to_path_buf();
return Some(Launch {
program,
args: Vec::new(),
cwd,
data_dir: installed_data_dir(app),
});
}
}
let repo = repo_root()?;
let program = repo
.join("backend")
.join(".venv")
.join("Scripts")
.join("python.exe");
if !python.exists() {
return;
if !program.is_file() {
return None;
}
let log_dir = repo.join("data");
let _ = std::fs::create_dir_all(&log_dir);
let mut command = Command::new(python);
Some(Launch {
program,
args: vec![
"-m".into(),
"uvicorn".into(),
"app.main:app".into(),
"--host".into(),
"127.0.0.1".into(),
"--port".into(),
port.to_string(),
],
cwd: repo.join("backend"),
data_dir: repo.join("data"),
})
}
fn start_backend(app: &tauri::App) {
let port = pick_port();
PORT.store(port, Ordering::SeqCst);
let Some(plan) = launch_plan(app, port) else {
return;
};
let _ = std::fs::create_dir_all(&plan.data_dir);
let mut command = Command::new(&plan.program);
command
.args([
"-m",
"uvicorn",
"app.main:app",
"--host",
"127.0.0.1",
"--port",
"8765",
])
.current_dir(repo.join("backend"))
.args(&plan.args)
.current_dir(&plan.cwd)
.env("NQI_PORT", port.to_string())
.env("NQI_DATA_DIR", &plan.data_dir)
.stdin(Stdio::null());
if let Ok(log) = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(log_dir.join("backend.log"))
.open(plan.data_dir.join("backend.log"))
{
if let Ok(error_log) = log.try_clone() {
command.stdout(log).stderr(error_log);
command.stdout(Stdio::from(log)).stderr(Stdio::from(error_log));
}
}
#[cfg(windows)]
@@ -59,6 +133,26 @@ fn start_backend() {
if let Ok(child) = command.spawn() {
*BACKEND.lock().expect("backend lock") = Some(child);
}
wait_until_ready(port);
}
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 stop_backend() {
@@ -73,10 +167,14 @@ fn stop_backend() {
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
start_backend();
tauri::Builder::default()
.plugin(tauri_plugin_opener::init())
.plugin(tauri_plugin_dialog::init())
.invoke_handler(tauri::generate_handler![backend_port])
.setup(|app| {
start_backend(app);
Ok(())
})
.build(tauri::generate_context!())
.expect("error while building tauri application")
.run(|_app, event| {
+14 -2
View File
@@ -24,13 +24,25 @@
}
},
"bundle": {
"active": false,
"active": true,
"targets": ["nsis"],
"publisher": "NqiTools",
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico"
]
],
"windows": {
"webviewInstallMode": {
"type": "skip"
},
"nsis": {
"installMode": "currentUser",
"languages": ["SimpChinese"],
"displayLanguageSelector": false
}
}
}
}
@@ -0,0 +1,7 @@
{
"bundle": {
"resources": {
"../../backend/build/nqi-backend/": "nqi-backend/"
}
}
}