chore: 恢复旧布局基线(迁移改动丢失后重建,apps/packages 布局暂存)
No files matched your search
@@ -0,0 +1,25 @@
|
||||
[package]
|
||||
name = "opsxdb-desktop"
|
||||
version = "0.1.0"
|
||||
description = "OpsxDB Tauri desktop shell"
|
||||
authors = ["OpsxDB"]
|
||||
edition = "2021"
|
||||
|
||||
[lib]
|
||||
name = "opsxdb_desktop_lib"
|
||||
crate-type = ["staticlib", "cdylib", "rlib"]
|
||||
|
||||
[build-dependencies]
|
||||
tauri-build = { version = "2", features = [] }
|
||||
|
||||
[dependencies]
|
||||
tauri = { version = "2", features = [] } # path via Manager
|
||||
tauri-plugin-opener = "2"
|
||||
tauri-plugin-single-instance = "2" # 二次启动聚焦已有窗口
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
reqwest = { version = "0.12", default-features = false, features = ["rustls-tls", "json", "blocking"] }
|
||||
tokio = { version = "1", features = ["time"] }
|
||||
url = "2"
|
||||
rand = "0.8"
|
||||
tauri-plugin-window-state = "2"
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() {
|
||||
tauri_build::build()
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "default",
|
||||
"description": "Default capabilities for the OpsxDB main window",
|
||||
"windows": [
|
||||
"main"
|
||||
],
|
||||
"permissions": [
|
||||
"core:default",
|
||||
"window-state:default",
|
||||
"opener:default"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{"core":{"default_permission":{"identifier":"default","description":"Default core plugins set.","permissions":["core:path:default","core:event:default","core:window:default","core:webview:default","core:app:default","core:image:default","core:resources:default","core:menu:default","core:tray:default"]},"permissions":{},"permission_sets":{},"global_scope_schema":null},"core:app":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-version","allow-name","allow-tauri-version","allow-identifier","allow-bundle-type","allow-register-listener","allow-remove-listener","allow-supports-multiple-windows"]},"permissions":{"allow-app-hide":{"identifier":"allow-app-hide","description":"Enables the app_hide command without any pre-configured scope.","commands":{"allow":["app_hide"],"deny":[]}},"allow-app-show":{"identifier":"allow-app-show","description":"Enables the app_show command without any pre-configured scope.","commands":{"allow":["app_show"],"deny":[]}},"allow-bundle-type":{"identifier":"allow-bundle-type","description":"Enables the bundle_type command without any pre-configured scope.","commands":{"allow":["bundle_type"],"deny":[]}},"allow-default-window-icon":{"identifier":"allow-default-window-icon","description":"Enables the default_window_icon command without any pre-configured scope.","commands":{"allow":["default_window_icon"],"deny":[]}},"allow-exit":{"identifier":"allow-exit","description":"Enables the exit command without any pre-configured scope.","commands":{"allow":["exit"],"deny":[]}},"allow-fetch-data-store-identifiers":{"identifier":"allow-fetch-data-store-identifiers","description":"Enables the fetch_data_store_identifiers command without any pre-configured scope.","commands":{"allow":["fetch_data_store_identifiers"],"deny":[]}},"allow-identifier":{"identifier":"allow-identifier","description":"Enables the identifier command without any pre-configured scope.","commands":{"allow":["identifier"],"deny":[]}},"allow-name":{"identifier":"allow-name","description":"Enables the name command without any pre-configured scope.","commands":{"allow":["name"],"deny":[]}},"allow-register-listener":{"identifier":"allow-register-listener","description":"Enables the register_listener command without any pre-configured scope.","commands":{"allow":["register_listener"],"deny":[]}},"allow-remove-data-store":{"identifier":"allow-remove-data-store","description":"Enables the remove_data_store command without any pre-configured scope.","commands":{"allow":["remove_data_store"],"deny":[]}},"allow-remove-listener":{"identifier":"allow-remove-listener","description":"Enables the remove_listener command without any pre-configured scope.","commands":{"allow":["remove_listener"],"deny":[]}},"allow-set-app-theme":{"identifier":"allow-set-app-theme","description":"Enables the set_app_theme command without any pre-configured scope.","commands":{"allow":["set_app_theme"],"deny":[]}},"allow-set-dock-visibility":{"identifier":"allow-set-dock-visibility","description":"Enables the set_dock_visibility command without any pre-configured scope.","commands":{"allow":["set_dock_visibility"],"deny":[]}},"allow-supports-multiple-windows":{"identifier":"allow-supports-multiple-windows","description":"Enables the supports_multiple_windows command without any pre-configured scope.","commands":{"allow":["supports_multiple_windows"],"deny":[]}},"allow-tauri-version":{"identifier":"allow-tauri-version","description":"Enables the tauri_version command without any pre-configured scope.","commands":{"allow":["tauri_version"],"deny":[]}},"allow-version":{"identifier":"allow-version","description":"Enables the version command without any pre-configured scope.","commands":{"allow":["version"],"deny":[]}},"deny-app-hide":{"identifier":"deny-app-hide","description":"Denies the app_hide command without any pre-configured scope.","commands":{"allow":[],"deny":["app_hide"]}},"deny-app-show":{"identifier":"deny-app-show","description":"Denies the app_show command without any pre-configured scope.","commands":{"allow":[],"deny":["app_show"]}},"deny-bundle-type":{"identifier":"deny-bundle-type","description":"Denies the bundle_type command without any pre-configured scope.","commands":{"allow":[],"deny":["bundle_type"]}},"deny-default-window-icon":{"identifier":"deny-default-window-icon","description":"Denies the default_window_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["default_window_icon"]}},"deny-exit":{"identifier":"deny-exit","description":"Denies the exit command without any pre-configured scope.","commands":{"allow":[],"deny":["exit"]}},"deny-fetch-data-store-identifiers":{"identifier":"deny-fetch-data-store-identifiers","description":"Denies the fetch_data_store_identifiers command without any pre-configured scope.","commands":{"allow":[],"deny":["fetch_data_store_identifiers"]}},"deny-identifier":{"identifier":"deny-identifier","description":"DenLine truncated
|
||||
@@ -0,0 +1 @@
|
||||
{"default":{"identifier":"default","description":"Default capabilities for the OpsxDB main window","local":true,"windows":["main"],"permissions":["core:default","window-state:default","opener:default"]}}
|
||||
|
After Width: | Height: | Size: 7.2 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 1.5 KiB |
|
After Width: | Height: | Size: 3.4 KiB |
|
After Width: | Height: | Size: 6.0 KiB |
|
After Width: | Height: | Size: 8.1 KiB |
|
After Width: | Height: | Size: 8.5 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 1.4 KiB |
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 2.1 KiB |
|
After Width: | Height: | Size: 3.7 KiB |
|
After Width: | Height: | Size: 4.9 KiB |
|
After Width: | Height: | Size: 2.5 KiB |
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
|
||||
<background android:drawable="@color/ic_launcher_background"/>
|
||||
</adaptive-icon>
|
||||
|
After Width: | Height: | Size: 2.3 KiB |
|
After Width: | Height: | Size: 9.3 KiB |
|
After Width: | Height: | Size: 2.1 KiB |
|
After Width: | Height: | Size: 2.2 KiB |
|
After Width: | Height: | Size: 6.1 KiB |
|
After Width: | Height: | Size: 2.0 KiB |
|
After Width: | Height: | Size: 5.0 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 4.7 KiB |
|
After Width: | Height: | Size: 8.1 KiB |
|
After Width: | Height: | Size: 21 KiB |
|
After Width: | Height: | Size: 7.4 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 31 KiB |
|
After Width: | Height: | Size: 9.8 KiB |
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<color name="ic_launcher_background">#fff</color>
|
||||
</resources>
|
||||
|
After Width: | Height: | Size: 25 KiB |
|
After Width: | Height: | Size: 37 KiB |
@@ -0,0 +1,7 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512">
|
||||
<rect width="512" height="512" rx="112" fill="#E11D2E"/>
|
||||
<g transform="rotate(-20 256 256)">
|
||||
<path d="M256 108 L290 216 L404 216 L312 286 L344 398 L256 332 L168 398 L200 286 L108 216 L222 216 Z"
|
||||
fill="none" stroke="#FFFFFF" stroke-width="30" stroke-linejoin="round" stroke-linecap="round"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 411 B |
|
After Width: | Height: | Size: 898 B |
|
After Width: | Height: | Size: 1.9 KiB |
|
After Width: | Height: | Size: 1.9 KiB |
|
After Width: | Height: | Size: 3.1 KiB |
|
After Width: | Height: | Size: 1.3 KiB |
|
After Width: | Height: | Size: 3.0 KiB |
|
After Width: | Height: | Size: 3.0 KiB |
|
After Width: | Height: | Size: 4.8 KiB |
|
After Width: | Height: | Size: 1.9 KiB |
|
After Width: | Height: | Size: 4.4 KiB |
|
After Width: | Height: | Size: 4.4 KiB |
|
After Width: | Height: | Size: 6.8 KiB |
|
After Width: | Height: | Size: 112 KiB |
|
After Width: | Height: | Size: 6.8 KiB |
|
After Width: | Height: | Size: 10 KiB |
|
After Width: | Height: | Size: 4.1 KiB |
|
After Width: | Height: | Size: 8.7 KiB |
|
After Width: | Height: | Size: 9.4 KiB |
|
After Width: | Height: | Size: 13 KiB |
@@ -0,0 +1,10 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512">
|
||||
<rect width="512" height="512" rx="112" fill="#0B182C"/>
|
||||
<ellipse cx="256" cy="156" rx="128" ry="40" fill="#60A5FA"/>
|
||||
<path d="M128 156v64c0 22 57 40 128 40s128-18 128-40v-64" fill="#3B82F6"/>
|
||||
<ellipse cx="256" cy="220" rx="128" ry="40" fill="#93C5FD"/>
|
||||
<path d="M128 220v64c0 22 57 40 128 40s128-18 128-40v-64" fill="#3B82F6"/>
|
||||
<ellipse cx="256" cy="284" rx="128" ry="40" fill="#BFDBFE"/>
|
||||
<path d="M128 284v88c0 22 57 40 128 40s128-18 128-40v-88" fill="#2563EB"/>
|
||||
<ellipse cx="256" cy="372" rx="128" ry="40" fill="#3B82F6"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 637 B |
|
After Width: | Height: | Size: 18 KiB |
@@ -0,0 +1,7 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512">
|
||||
<rect width="512" height="512" rx="112" fill="#EF4444"/>
|
||||
<g transform="rotate(8 256 256)">
|
||||
<path d="M256 88 L298 214 L432 214 L324 292 L364 420 L256 344 L148 420 L188 292 L80 214 L214 214 Z"
|
||||
fill="none" stroke="#FFFFFF" stroke-width="36" stroke-linejoin="round" stroke-linecap="round"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 407 B |
|
After Width: | Height: | Size: 17 KiB |
@@ -0,0 +1,7 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512">
|
||||
<rect width="512" height="512" rx="112" fill="#EF4444"/>
|
||||
<g transform="rotate(12 256 256)">
|
||||
<path d="M256 96 L294 214 L420 214 L318 288 L354 408 L256 336 L158 408 L194 288 L92 214 L218 214 Z"
|
||||
fill="none" stroke="#FFFFFF" stroke-width="34" stroke-linejoin="round" stroke-linecap="round"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 408 B |
@@ -0,0 +1,171 @@
|
||||
mod sidecar;
|
||||
|
||||
use tauri::Manager;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct BodySpec {
|
||||
mode: String,
|
||||
raw: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct HttpSpec {
|
||||
method: String,
|
||||
url: String,
|
||||
#[serde(default)]
|
||||
headers: HashMap<String, String>,
|
||||
query: Option<HashMap<String, String>>,
|
||||
body: Option<BodySpec>,
|
||||
timeout_ms: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct HttpResult {
|
||||
status: u16,
|
||||
headers: HashMap<String, String>,
|
||||
body: String,
|
||||
time_ms: u128,
|
||||
size: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct WsSpec {
|
||||
url: String,
|
||||
protocols: Option<Vec<String>>,
|
||||
headers: Option<HashMap<String, String>>,
|
||||
}
|
||||
|
||||
fn validate_http_url(raw: &str) -> Result<url::Url, String> {
|
||||
let parsed = url::Url::parse(raw).map_err(|e| format!("invalid URL: {e}"))?;
|
||||
match parsed.scheme() {
|
||||
"http" | "https" => {}
|
||||
_ => return Err("only http/https schemes are allowed".into()),
|
||||
}
|
||||
match parsed.host_str().unwrap_or("").to_ascii_lowercase().as_str() {
|
||||
"169.254.169.254" | "metadata.google.internal" => {
|
||||
return Err("blocked metadata host".into())
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(parsed)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn http_send(spec: HttpSpec) -> Result<HttpResult, String> {
|
||||
let mut url = validate_http_url(&spec.url)?;
|
||||
if let Some(query) = &spec.query {
|
||||
let mut pairs = url.query_pairs_mut();
|
||||
for (key, value) in query {
|
||||
pairs.append_pair(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
let method = reqwest::Method::from_bytes(spec.method.as_bytes())
|
||||
.map_err(|e| format!("invalid method: {e}"))?;
|
||||
let timeout = Duration::from_millis(spec.timeout_ms.unwrap_or(30_000));
|
||||
let client = reqwest::Client::builder()
|
||||
.timeout(timeout)
|
||||
.build()
|
||||
.map_err(|e| e.to_string())?;
|
||||
let mut request = client.request(method, url);
|
||||
for (key, value) in spec.headers {
|
||||
request = request.header(&key, &value);
|
||||
}
|
||||
if let Some(body) = spec.body {
|
||||
if body.mode != "none" {
|
||||
request = request.body(body.raw.unwrap_or_default());
|
||||
}
|
||||
}
|
||||
|
||||
let started = Instant::now();
|
||||
let response = request.send().await.map_err(|e| e.to_string())?;
|
||||
let status = response.status().as_u16();
|
||||
let headers = response
|
||||
.headers()
|
||||
.iter()
|
||||
.map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string()))
|
||||
.collect();
|
||||
let bytes = response.bytes().await.map_err(|e| e.to_string())?;
|
||||
let size = bytes.len();
|
||||
let body = String::from_utf8_lossy(&bytes).into_owned();
|
||||
Ok(HttpResult {
|
||||
status,
|
||||
headers,
|
||||
body,
|
||||
time_ms: started.elapsed().as_millis(),
|
||||
size,
|
||||
})
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn ws_connect(spec: WsSpec) -> Result<String, String> {
|
||||
let _ = (&spec.protocols, &spec.headers);
|
||||
// TODO(week2): hold WebSocket sessions in managed state and emit messages.
|
||||
Err(format!(
|
||||
"WebSocket native tunnel is not implemented yet for {} (use browser WS in MVP)",
|
||||
spec.url
|
||||
))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn ws_send(session_id: String, data: String) -> Result<(), String> {
|
||||
let _ = (session_id, data);
|
||||
Err("WebSocket native send is a Week 2 stub".into())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn ws_close(session_id: String) -> Result<(), String> {
|
||||
let _ = session_id;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 前端启动时拉取后端地址与 token(注入 window.__OPSXDB_API__/__OPSXDB_TOKEN__)。
|
||||
#[tauri::command]
|
||||
fn get_backend_config(
|
||||
state: tauri::State<'_, sidecar::SidecarState>,
|
||||
) -> Result<sidecar::BackendConfig, String> {
|
||||
state
|
||||
.backend_config()
|
||||
.ok_or_else(|| "后端尚未就绪".to_string())
|
||||
}
|
||||
|
||||
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
||||
pub fn run() {
|
||||
tauri::Builder::default()
|
||||
.plugin(tauri_plugin_opener::init())
|
||||
.plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| {
|
||||
// 二次启动聚焦已有窗口
|
||||
if let Some(w) = app.get_webview_window("main") {
|
||||
let _ = w.show();
|
||||
let _ = w.unminimize();
|
||||
let _ = w.set_focus();
|
||||
}
|
||||
}))
|
||||
.plugin(tauri_plugin_window_state::Builder::default().build())
|
||||
.manage(sidecar::SidecarState::default())
|
||||
.setup(|app| {
|
||||
let state = app.state::<sidecar::SidecarState>();
|
||||
sidecar::ensure_backend(app.handle(), &state);
|
||||
Ok(())
|
||||
})
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
http_send,
|
||||
ws_connect,
|
||||
ws_send,
|
||||
ws_close,
|
||||
get_backend_config
|
||||
])
|
||||
.build(tauri::generate_context!())
|
||||
.expect("error while building OpsxDB desktop")
|
||||
.run(|app, event| {
|
||||
let state = app.state::<sidecar::SidecarState>();
|
||||
sidecar::on_run_event(app, &event, &state);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() {
|
||||
opsxdb_desktop_lib::run();
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
//! 桌面启动时拉起本机 OpsxDB Gin 后端。
|
||||
//! - 动态端口:TcpListener 绑 127.0.0.1:0 选空闲端口,OPSXDB_ADDR 传子进程;
|
||||
//! - 每次自起生成随机 token,OPSXDB_TOKEN 传子进程,与 addr 一起经 get_backend_config 注入前端;
|
||||
//! - 复用 8788 上已运行后端前先比对 /health 版本主版本,不匹配则换端口自起;
|
||||
//! - 失败时 emit "opsxdb://backend-failed",后端 stdout/stderr 重定向到 app_log_dir/opsxdb-server.log。
|
||||
use std::path::PathBuf;
|
||||
use std::process::{Child, Command, Stdio};
|
||||
use std::sync::Mutex;
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
use tauri::{AppHandle, Emitter, Manager, RunEvent};
|
||||
|
||||
const DEFAULT_ADDR: &str = "127.0.0.1:8788";
|
||||
/// 与服务端 cmd/opsxdb main.go Version 保持一致,复用前比对主版本。
|
||||
const BACKEND_VERSION: &str = "0.1.0";
|
||||
const EVENT_BACKEND_FAILED: &str = "opsxdb://backend-failed";
|
||||
|
||||
#[derive(Clone, serde::Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct BackendConfig {
|
||||
pub addr: String,
|
||||
pub token: String,
|
||||
}
|
||||
|
||||
pub struct SidecarState {
|
||||
child: Mutex<Option<Child>>,
|
||||
config: Mutex<Option<BackendConfig>>,
|
||||
}
|
||||
|
||||
impl Default for SidecarState {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
child: Mutex::new(None),
|
||||
config: Mutex::new(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SidecarState {
|
||||
fn set_config(&self, cfg: BackendConfig) {
|
||||
if let Ok(mut g) = self.config.lock() {
|
||||
*g = Some(cfg);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn backend_config(&self) -> Option<BackendConfig> {
|
||||
self.config.lock().ok().and_then(|g| g.clone())
|
||||
}
|
||||
}
|
||||
|
||||
fn version_major(v: &str) -> &str {
|
||||
v.split('.').next().unwrap_or("")
|
||||
}
|
||||
|
||||
/// GET /health 并解析版本;失败或非 200 返回 None。
|
||||
fn health_version(addr: &str) -> Option<String> {
|
||||
let resp = reqwest::blocking::Client::builder()
|
||||
.timeout(Duration::from_secs(1))
|
||||
.build()
|
||||
.ok()?
|
||||
.get(format!("http://{addr}/health"))
|
||||
.send()
|
||||
.ok()?;
|
||||
if !resp.status().is_success() {
|
||||
return None;
|
||||
}
|
||||
let v: serde_json::Value = resp.json().ok()?;
|
||||
v.get("version")?.as_str().map(|s| s.to_string())
|
||||
}
|
||||
|
||||
fn health_ok(addr: &str) -> bool {
|
||||
health_version(addr).is_some()
|
||||
}
|
||||
|
||||
/// 尝试复用 8788 上已在运行的后端:仅当主版本一致才复用,
|
||||
/// 否则换端口自起而非静默连上旧版本。
|
||||
fn try_reuse_existing(state: &SidecarState) -> bool {
|
||||
match health_version(DEFAULT_ADDR) {
|
||||
Some(v) if version_major(&v) == version_major(BACKEND_VERSION) => {
|
||||
// 复用路径拿不到对方 token,按本机 dev 无鉴权处理
|
||||
state.set_config(BackendConfig {
|
||||
addr: format!("http://{DEFAULT_ADDR}"),
|
||||
token: String::new(),
|
||||
});
|
||||
true
|
||||
}
|
||||
Some(v) => {
|
||||
eprintln!(
|
||||
"opsxdb: 已有后端版本 {v} 与期望 {BACKEND_VERSION} 主版本不匹配,改自动态端口自起"
|
||||
);
|
||||
false
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// 绑 127.0.0.1:0 选一个空闲端口(立即释放,交给子进程绑定)。
|
||||
fn pick_free_port() -> Option<u16> {
|
||||
let ln = std::net::TcpListener::bind("127.0.0.1:0").ok()?;
|
||||
ln.local_addr().ok().map(|a| a.port())
|
||||
}
|
||||
|
||||
fn gen_token() -> String {
|
||||
use rand::RngCore;
|
||||
let mut b = [0u8; 32];
|
||||
rand::thread_rng().fill_bytes(&mut b);
|
||||
b.iter().map(|x| format!("{x:02x}")).collect()
|
||||
}
|
||||
|
||||
fn candidate_bins(app: &AppHandle) -> Vec<PathBuf> {
|
||||
// Windows 产物为 opsxdb-server.exe
|
||||
let bin = format!("opsxdb-server{}", std::env::consts::EXE_EXTENSION);
|
||||
let mut out = Vec::new();
|
||||
// 打包资源:externalBin → 与可执行文件同级的 binaries 或 resource
|
||||
if let Ok(dir) = app.path().resource_dir() {
|
||||
out.push(dir.join(&bin));
|
||||
out.push(dir.join("binaries").join(&bin));
|
||||
}
|
||||
if let Ok(exe) = app.path().executable_dir() {
|
||||
out.push(exe.join(&bin));
|
||||
out.push(exe.join("binaries").join(&bin));
|
||||
}
|
||||
// 开发态:仓库 apps/server/bin
|
||||
out.push(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../server/bin").join(&bin));
|
||||
out.push(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../../apps/server/bin").join(&bin));
|
||||
out
|
||||
}
|
||||
|
||||
/// 后端 stdout/stderr 重定向到 app_log_dir/opsxdb-server.log。
|
||||
fn server_log_file(app: &AppHandle) -> Option<std::fs::File> {
|
||||
let dir = app.path().app_log_dir().ok()?;
|
||||
std::fs::create_dir_all(&dir).ok()?;
|
||||
std::fs::File::create(dir.join("opsxdb-server.log")).ok()
|
||||
}
|
||||
|
||||
fn spawn_server(
|
||||
bin: &PathBuf,
|
||||
addr: &str,
|
||||
token: &str,
|
||||
log_file: Option<&std::fs::File>,
|
||||
) -> std::io::Result<Child> {
|
||||
let mut cmd = Command::new(bin);
|
||||
cmd.env("OPSXDB_ADDR", addr)
|
||||
.env("OPSXDB_TOKEN", token)
|
||||
.env("GIN_MODE", "release");
|
||||
match log_file {
|
||||
Some(f) => {
|
||||
let err_f = f.try_clone()?;
|
||||
cmd.stdout(Stdio::from(f.try_clone()?)).stderr(Stdio::from(err_f));
|
||||
}
|
||||
None => {
|
||||
cmd.stdout(Stdio::null()).stderr(Stdio::null());
|
||||
}
|
||||
}
|
||||
cmd.spawn()
|
||||
}
|
||||
|
||||
pub fn ensure_backend(app: &AppHandle, state: &SidecarState) {
|
||||
if try_reuse_existing(state) {
|
||||
return;
|
||||
}
|
||||
let Some(port) = pick_free_port() else {
|
||||
let _ = app.emit(EVENT_BACKEND_FAILED, "无法分配空闲端口");
|
||||
return;
|
||||
};
|
||||
let addr = format!("127.0.0.1:{port}");
|
||||
let token = gen_token();
|
||||
let log_file = server_log_file(app);
|
||||
let mut last_err = String::from("未找到后端二进制");
|
||||
for bin in candidate_bins(app) {
|
||||
if !bin.exists() {
|
||||
continue;
|
||||
}
|
||||
match spawn_server(&bin, &addr, &token, log_file.as_ref()) {
|
||||
Ok(child) => {
|
||||
*state.child.lock().unwrap() = Some(child);
|
||||
for _ in 0..30 {
|
||||
if health_ok(&addr) {
|
||||
state.set_config(BackendConfig {
|
||||
addr: format!("http://{addr}"),
|
||||
token: token.clone(),
|
||||
});
|
||||
return;
|
||||
}
|
||||
thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
last_err = format!("后端启动后健康检查超时({})", bin.display());
|
||||
}
|
||||
Err(e) => {
|
||||
last_err = format!("启动 {} 失败: {e}", bin.display());
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
let _ = app.emit(EVENT_BACKEND_FAILED, last_err);
|
||||
}
|
||||
|
||||
pub fn stop_backend(state: &SidecarState) {
|
||||
if let Ok(mut g) = state.child.lock() {
|
||||
if let Some(mut child) = g.take() {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn on_run_event(app: &AppHandle, event: &RunEvent, state: &SidecarState) {
|
||||
if matches!(event, RunEvent::Exit | RunEvent::ExitRequested { .. }) {
|
||||
stop_backend(state);
|
||||
let _ = app;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "OpsxDB",
|
||||
"version": "0.1.0",
|
||||
"identifier": "com.opsx.db",
|
||||
"build": {
|
||||
"beforeDevCommand": "bash -lc 'curl -fsS http://127.0.0.1:5174 >/dev/null 2>&1 || npm run dev'",
|
||||
"devUrl": "http://127.0.0.1:5174",
|
||||
"beforeBuildCommand": "bash -lc 'npm run build'",
|
||||
"frontendDist": "../dist"
|
||||
},
|
||||
"app": {
|
||||
"windows": [
|
||||
{
|
||||
"title": "OpsxDB",
|
||||
"width": 1280,
|
||||
"height": 800,
|
||||
"minWidth": 960,
|
||||
"minHeight": 640,
|
||||
"resizable": true,
|
||||
"fullscreen": false,
|
||||
"label": "main"
|
||||
}
|
||||
],
|
||||
"security": {
|
||||
"csp": "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'self' http://localhost:* http://127.0.0.1:* ws://localhost:* ws://127.0.0.1:* ipc://localhost; object-src 'none'; base-uri 'self'"
|
||||
}
|
||||
},
|
||||
"bundle": {
|
||||
"active": true,
|
||||
"targets": "all",
|
||||
"icon": [
|
||||
"icons/32x32.png",
|
||||
"icons/128x128.png",
|
||||
"icons/128x128@2x.png",
|
||||
"icons/icon.icns",
|
||||
"icons/icon.ico"
|
||||
],
|
||||
"externalBin": [
|
||||
"binaries/opsxdb-server"
|
||||
]
|
||||
}
|
||||
}
|
||||