186 lines
5.0 KiB
Rust
186 lines
5.0 KiB
Rust
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, Instant};
|
|
|
|
use tauri::Manager;
|
|
|
|
static BACKEND: Mutex<Option<Child>> = Mutex::new(None);
|
|
static PORT: AtomicU16 = AtomicU16::new(0);
|
|
|
|
struct Launch {
|
|
program: PathBuf,
|
|
args: Vec<String>,
|
|
cwd: PathBuf,
|
|
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()
|
|
}
|
|
|
|
#[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);
|
|
}
|
|
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 !program.is_file() {
|
|
return None;
|
|
}
|
|
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(&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(plan.data_dir.join("backend.log"))
|
|
{
|
|
if let Ok(error_log) = log.try_clone() {
|
|
command.stdout(Stdio::from(log)).stderr(Stdio::from(error_log));
|
|
}
|
|
}
|
|
#[cfg(windows)]
|
|
{
|
|
use std::os::windows::process::CommandExt;
|
|
command.creation_flags(0x0800_0000);
|
|
}
|
|
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() {
|
|
if let Ok(mut slot) = BACKEND.lock() {
|
|
if let Some(child) = slot.as_mut() {
|
|
let _ = child.kill();
|
|
let _ = child.wait();
|
|
}
|
|
*slot = None;
|
|
}
|
|
}
|
|
|
|
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
|
pub fn run() {
|
|
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| {
|
|
if matches!(event, tauri::RunEvent::Exit) {
|
|
stop_backend();
|
|
}
|
|
});
|
|
}
|