feat: 改为安装包分发并使用动态端口
@@ -9,6 +9,7 @@ aidocs/
|
||||
|
||||
# Python
|
||||
backend/.venv/
|
||||
backend/build/
|
||||
.venv/
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
|
||||
@@ -45,6 +45,16 @@ async def health() -> dict:
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import os
|
||||
import socket
|
||||
|
||||
import uvicorn
|
||||
|
||||
uvicorn.run("app.main:app", host="127.0.0.1", port=8765)
|
||||
chosen = os.environ.get("NQI_PORT")
|
||||
if chosen:
|
||||
port = int(chosen)
|
||||
else:
|
||||
with socket.socket() as sock:
|
||||
sock.bind(("127.0.0.1", 0))
|
||||
port = sock.getsockname()[1]
|
||||
uvicorn.run("app.main:app", host="127.0.0.1", port=port)
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[3]
|
||||
DATA_ROOT = REPO_ROOT / "data"
|
||||
|
||||
def _data_root() -> Path:
|
||||
override = os.environ.get("NQI_DATA_DIR")
|
||||
if override:
|
||||
return Path(override)
|
||||
return Path(__file__).resolve().parents[3] / "data"
|
||||
|
||||
|
||||
DATA_ROOT = _data_root()
|
||||
DOWNLOAD_DIR = DATA_ROOT / "jobs"
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
"""安装包中的后端入口。端口由启动程序通过 NQI_PORT 传入。"""
|
||||
|
||||
import os
|
||||
|
||||
import uvicorn
|
||||
|
||||
from app.main import app
|
||||
|
||||
|
||||
def main() -> None:
|
||||
port = int(os.environ["NQI_PORT"])
|
||||
uvicorn.run(app, host="127.0.0.1", port=port, log_level="info")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -13,7 +13,7 @@ dependencies = [
|
||||
]
|
||||
|
||||
[dependency-groups]
|
||||
dev = ["pytest>=8.3"]
|
||||
dev = ["pyinstaller>=6.22.3", "pytest>=8.3"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
pythonpath = ["."]
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
"""把后端冻成目录形式,供安装包直接启动,不在第一次打开时解压。"""
|
||||
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
DIST = ROOT / "build"
|
||||
|
||||
|
||||
def main() -> None:
|
||||
DIST.mkdir(parents=True, exist_ok=True)
|
||||
subprocess.check_call(
|
||||
[
|
||||
sys.executable,
|
||||
"-m",
|
||||
"PyInstaller",
|
||||
"--noconfirm",
|
||||
"--clean",
|
||||
"--onedir",
|
||||
"--name",
|
||||
"nqi-backend",
|
||||
"--distpath",
|
||||
str(DIST),
|
||||
"--workpath",
|
||||
str(DIST / "pyinstaller"),
|
||||
"--specpath",
|
||||
str(DIST),
|
||||
"--collect-submodules",
|
||||
"app",
|
||||
"--collect-all",
|
||||
"uvicorn",
|
||||
"--collect-all",
|
||||
"openpyxl",
|
||||
"--collect-all",
|
||||
"cryptography",
|
||||
"--collect-all",
|
||||
"certifi",
|
||||
"--hidden-import",
|
||||
"multipart",
|
||||
str(ROOT / "nqi_backend.py"),
|
||||
],
|
||||
cwd=ROOT,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -2,6 +2,15 @@ version = 1
|
||||
revision = 3
|
||||
requires-python = ">=3.11"
|
||||
|
||||
[[package]]
|
||||
name = "altgraph"
|
||||
version = "0.17.5"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/7e/f8/97fdf103f38fed6792a1601dbc16cc8aac56e7459a9fff08c812d8ae177a/altgraph-0.17.5.tar.gz", hash = "sha256:c87b395dd12fabde9c99573a9749d67da8d29ef9de0125c7f536699b4a9bc9e7", size = 48428, upload-time = "2025-11-21T20:35:50.583Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/a9/ba/000a1996d4308bc65120167c21241a3b205464a2e0b58deda26ae8ac21d1/altgraph-0.17.5-py2.py3-none-any.whl", hash = "sha256:f3a22400bce1b0c701683820ac4f3b159cd301acab067c51c653e06961600597", size = 21228, upload-time = "2025-11-21T20:35:49.444Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "annotated-doc"
|
||||
version = "0.0.5"
|
||||
@@ -308,6 +317,18 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/56/43/4ca9e49d27a1fcf6bece6f6aec0ea46bb9112489b93d4b688fb415457bdb/iniconfig-2.3.1-py3-none-any.whl", hash = "sha256:9121e2c1fdb355232495be3194c8dfe87ccc2d5dee45947b78e68f499790d7a7", size = 7552, upload-time = "2026-10-06T22:48:36.959Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "macholib"
|
||||
version = "1.16.4"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "altgraph" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/10/2f/97589876ea967487978071c9042518d28b958d87b17dceb7cdc1d881f963/macholib-1.16.4.tar.gz", hash = "sha256:f408c93ab2e995cd2c46e34fe328b130404be143469e41bc366c807448979362", size = 59427, upload-time = "2025-11-22T08:28:38.373Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/c7/d1/a9f36f8ecdf0fb7c9b1e78c8d7af12b8c8754e74851ac7b94a8305540fc7/macholib-1.16.4-py2.py3-none-any.whl", hash = "sha256:da1a3fa8266e30f0ce7e97c6a54eefaae8edd1e5f86f3eb8b95457cae90265ea", size = 38117, upload-time = "2025-11-22T08:28:36.939Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nqi-backend"
|
||||
version = "0.1.0"
|
||||
@@ -323,6 +344,7 @@ dependencies = [
|
||||
|
||||
[package.dev-dependencies]
|
||||
dev = [
|
||||
{ name = "pyinstaller" },
|
||||
{ name = "pytest" },
|
||||
]
|
||||
|
||||
@@ -337,7 +359,10 @@ requires-dist = [
|
||||
]
|
||||
|
||||
[package.metadata.requires-dev]
|
||||
dev = [{ name = "pytest", specifier = ">=8.3" }]
|
||||
dev = [
|
||||
{ name = "pyinstaller", specifier = ">=6.22.3" },
|
||||
{ name = "pytest", specifier = ">=8.3" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "openpyxl"
|
||||
@@ -372,6 +397,15 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/63/34/ba1c580383c9eada3711951fef0795c80b829a078d72188184bcab9dd527/packaging-26.3-py3-none-any.whl", hash = "sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c", size = 129956, upload-time = "2026-08-04T18:15:27.159Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pefile"
|
||||
version = "2024.8.26"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/03/4f/2750f7f6f025a1507cd3b7218691671eecfd0bbebebe8b39aa0fe1d360b8/pefile-2024.8.26.tar.gz", hash = "sha256:3ff6c5d8b43e8c37bb6e6dd5085658d658a7a0bdcd20b6a07b1fcfc1c4e9d632", size = 76008, upload-time = "2024-08-26T20:58:38.155Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/54/16/12b82f791c7f50ddec566873d5bdd245baa1491bac11d15ffb98aecc8f8b/pefile-2024.8.26-py3-none-any.whl", hash = "sha256:76f8b485dcd3b1bb8166f1128d395fa3d87af26360c2358fb75b80019b957c6f", size = 74766, upload-time = "2024-08-26T21:01:02.632Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pluggy"
|
||||
version = "1.7.0"
|
||||
@@ -547,6 +581,46 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/71/46/17f022dd3e953bf20a04a028a21ec746d942f8d2af30fa0f124fa0e6a684/pygments-2.21.0-py3-none-any.whl", hash = "sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9", size = 1250147, upload-time = "2026-08-17T08:02:44.912Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pyinstaller"
|
||||
version = "6.22.3"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "altgraph" },
|
||||
{ name = "macholib", marker = "sys_platform == 'darwin'" },
|
||||
{ name = "packaging" },
|
||||
{ name = "pefile", marker = "sys_platform == 'win32'" },
|
||||
{ name = "pyinstaller-hooks-contrib" },
|
||||
{ name = "pywin32-ctypes", marker = "sys_platform == 'win32'" },
|
||||
{ name = "setuptools" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/63/41/f90302845945abd4ed647933ff5ee7c6ac93983187be67f897b6cb613331/pyinstaller-6.22.3.tar.gz", hash = "sha256:05eb2f5615503e72939a7224d68b4aff572c6b0438ee4a17d0a4b481f399362d", size = 4437180, upload-time = "2026-09-12T21:54:09.669Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/ec/af/898f70947e27f8e65d55183c780e77112e023c0b4a6fba6255d4d563a27d/pyinstaller-6.22.3-py3-none-macosx_10_13_universal2.whl", hash = "sha256:052f4a1cd4f81092ccb7a18fe8ebc9ecf832a5917317e39fb3775af4e959b253", size = 1071847, upload-time = "2026-09-12T21:53:01.711Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c4/96/99f5184985141c2b024bfa61335e9142ae444555224f303186e59b7bb438/pyinstaller-6.22.3-py3-none-manylinux2014_aarch64.whl", hash = "sha256:312da84b4b31ab9750066a823734c11b7c68757fdd67c9f038bf19c330a954e4", size = 758172, upload-time = "2026-09-12T21:53:06.171Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/69/9f/9ccb12cc1e6617042cb028fe79f0a756f5f03305bd14b584a4e043fe3844/pyinstaller-6.22.3-py3-none-manylinux2014_i686.whl", hash = "sha256:020d4fe0627f5c73dfbcfad1a6578ef354d5fe4bdccd9d8e5a615528f5a45d2b", size = 772135, upload-time = "2026-09-12T21:53:10.291Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c1/43/4b1d5193a88628c052db89f064433681076959a9f41d0d9f660001b49079/pyinstaller-6.22.3-py3-none-manylinux2014_ppc64le.whl", hash = "sha256:9e4f7bd64b2103f14b4a6240fb9155e9fe7bc61391b4043bbddb7d3ebc8ab0fa", size = 770461, upload-time = "2026-09-12T21:53:14.592Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/cb/83/f173f8757c618d83e116fa2b8e57c5cd796e5ad09792e664eabd6ac5edae/pyinstaller-6.22.3-py3-none-manylinux2014_s390x.whl", hash = "sha256:f82d0fb89f21c3ed6f482ee16f341bc59e8a31dbabb9bae9ef04e53ade4dc0d9", size = 764997, upload-time = "2026-09-12T21:53:19.079Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/7b/b6/dd21d61fc5e25377be24eabf13e99e4e46548a5abe2bf7b15d8b3d9cc74a/pyinstaller-6.22.3-py3-none-manylinux2014_x86_64.whl", hash = "sha256:451a4ae14b719365bf1a2f0a99dae7b3463060061c3a394c70d5264cfb439528", size = 764974, upload-time = "2026-09-12T21:53:23.176Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/6c/fd/d9590942972b1fc205519f7ccffb0d5cd8eb1d6fa61edad319c71d25baed/pyinstaller-6.22.3-py3-none-musllinux_1_1_aarch64.whl", hash = "sha256:ea240b5dfa831ff673c97505eee0ec24670bccf71396c83109440348944c83d0", size = 764450, upload-time = "2026-09-12T21:53:27.419Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/72/d6/f22c55d1768433b65c460b19a3136dd9769b6c74b786149b829344654c7d/pyinstaller-6.22.3-py3-none-musllinux_1_1_x86_64.whl", hash = "sha256:a2b6fc26601e8c2596c3d54981566934a3382e85d05d0fe91b55b6a8dcc6b282", size = 763863, upload-time = "2026-09-12T21:53:31.609Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c5/87/cf28cfd42ceca889171e6dd5e7f1553d4372db83d047049ffb7cf95fcbd4/pyinstaller-6.22.3-py3-none-win32.whl", hash = "sha256:46a3e30a118341a1ec20667a5a95aa7e0aa8c4fa129893c0151b3eb3f801a722", size = 1390905, upload-time = "2026-09-12T21:53:38.133Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/24/83/c5422204772a27aef643280fdc887b7ef55679989096b21dceb1b9625fc4/pyinstaller-6.22.3-py3-none-win_amd64.whl", hash = "sha256:500bd58c7bf7e584a8435adccbd763a0b918d5c12b08d74ff50fd79b2915458b", size = 1454907, upload-time = "2026-09-12T21:53:44.812Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/67/2e/ebc93968bf63f81b122e205da116b16036b653b7ce2cc8ad86e3ddd19586/pyinstaller-6.22.3-py3-none-win_arm64.whl", hash = "sha256:31df3cc4261e804a53d358b7897c293ec8b88b167a7cca06c78018085c855f97", size = 1402956, upload-time = "2026-09-12T21:53:51.369Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pyinstaller-hooks-contrib"
|
||||
version = "2026.9"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "packaging" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/96/25/e47c6188228281372be7e9911a93931e01ec8798c02c93abd680b9b9521f/pyinstaller_hooks_contrib-2026.9.tar.gz", hash = "sha256:2748767901acb5cecd1304652b6c7add5bffcff1d71d01207fe24a5d42942a56", size = 180783, upload-time = "2026-10-20T15:43:54Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/93/fe/ded0e20de0580257d97dbabb4db7ab4d96ad8ade7d41149e66308057cf52/pyinstaller_hooks_contrib-2026.9-py3-none-any.whl", hash = "sha256:fb3e67dd64122561724c48ad0366ac9e8c16e638b63bf7d85de03bf3fdbf06c3", size = 462931, upload-time = "2026-10-20T15:43:52.632Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pytest"
|
||||
version = "9.1.1"
|
||||
@@ -572,6 +646,24 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/e1/04/e8135ebd1ad02c56ec633277529b2602ff99ff634be76cdba5744cf554fd/python_multipart-0.0.32-py3-none-any.whl", hash = "sha256:ff6d3f776f16878c894e52e107296ffc890e913c611b1a4ec6c44e2821fe2e23", size = 30042, upload-time = "2026-06-04T16:18:57.319Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pywin32-ctypes"
|
||||
version = "0.2.3"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/85/9f/01a1a99704853cb63f253eea009390c88e7131c67e66a0a02099a8c917cb/pywin32-ctypes-0.2.3.tar.gz", hash = "sha256:d162dc04946d704503b2edc4d55f3dba5c1d539ead017afa00142c38b9885755", size = 29471, upload-time = "2024-08-14T10:15:34.626Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/de/3d/8161f7711c017e01ac9f008dfddd9410dff3674334c233bde66e7ba65bbf/pywin32_ctypes-0.2.3-py3-none-any.whl", hash = "sha256:8a1513379d709975552d202d942d9837758905c8d01eb82b8bcc30918929e7b8", size = 30756, upload-time = "2024-08-14T10:15:33.187Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "setuptools"
|
||||
version = "84.2.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/70/b3/c19426f783614d625699a4b247faf628ea9ab1db228674491767b417f9e1/setuptools-84.2.1.tar.gz", hash = "sha256:3ff8b3b5492a0aa66960f4419365a86b84e013070d4313e4d4a6894f5d64d6bc", size = 1230289, upload-time = "2026-10-20T19:01:37.742Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/ef/55/6dc6d6bb953bdfc52519a0059592c52b6e3b8ad51cf8256dffceb55b0610/setuptools-84.2.1-py3-none-any.whl", hash = "sha256:ca140b45d5325a9478f880e351484f62fef15f336462e449ca0c03c873d589c2", size = 876263, upload-time = "2026-10-20T19:01:35.678Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "starlette"
|
||||
version = "1.10.0"
|
||||
|
||||
@@ -7,9 +7,8 @@
|
||||
"dev": "vite",
|
||||
"build": "vue-tsc --noEmit && vite build",
|
||||
"preview": "vite preview",
|
||||
"tauri": "tauri",
|
||||
"tauri:dev": "tauri dev",
|
||||
"exe": "tauri build -- --bundles none"
|
||||
"tauri": "node scripts/tauri.mjs",
|
||||
"backend:freeze": "..\\backend\\.venv\\Scripts\\python.exe ..\\backend\\scripts\\freeze.py"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tauri-apps/api": "^2",
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const desktop = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const cli = path.join(desktop, "node_modules", "@tauri-apps", "cli", "tauri.js");
|
||||
const args = process.argv.slice(2);
|
||||
|
||||
if (args[0] === "build" || args[0] === "bundle") {
|
||||
if (args[0] === "build") {
|
||||
const freeze = spawnSync("npm", ["run", "backend:freeze"], {
|
||||
cwd: desktop,
|
||||
stdio: "inherit",
|
||||
shell: true,
|
||||
});
|
||||
if ((freeze.status ?? 1) !== 0) process.exit(freeze.status ?? 1);
|
||||
}
|
||||
args.push("--config", path.join("src-tauri", "tauri.release.conf.json"));
|
||||
}
|
||||
|
||||
const result = spawnSync(process.execPath, [cli, ...args], {
|
||||
cwd: desktop,
|
||||
stdio: "inherit",
|
||||
});
|
||||
process.exit(result.status ?? 1);
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
|
Before Width: | Height: | Size: 1.6 KiB After Width: | Height: | Size: 4.9 KiB |
|
Before Width: | Height: | Size: 2.8 KiB After Width: | Height: | Size: 9.6 KiB |
|
Before Width: | Height: | Size: 567 B After Width: | Height: | Size: 1.1 KiB |
|
After Width: | Height: | Size: 2.4 KiB |
|
Before Width: | Height: | Size: 1.3 KiB After Width: | Height: | Size: 4.2 KiB |
|
Before Width: | Height: | Size: 1.7 KiB After Width: | Height: | Size: 5.5 KiB |
|
Before Width: | Height: | Size: 1.7 KiB After Width: | Height: | Size: 5.6 KiB |
|
Before Width: | Height: | Size: 3.0 KiB After Width: | Height: | Size: 11 KiB |
|
Before Width: | Height: | Size: 536 B After Width: | Height: | Size: 1.0 KiB |
|
Before Width: | Height: | Size: 3.4 KiB After Width: | Height: | Size: 12 KiB |
|
Before Width: | Height: | Size: 777 B After Width: | Height: | Size: 1.6 KiB |
|
Before Width: | Height: | Size: 1020 B After Width: | Height: | Size: 2.6 KiB |
|
Before Width: | Height: | Size: 1.2 KiB After Width: | Height: | Size: 3.3 KiB |
|
Before Width: | Height: | Size: 848 B After Width: | Height: | Size: 1.8 KiB |
|
Before Width: | Height: | Size: 37 KiB After Width: | Height: | Size: 17 KiB |
|
Before Width: | Height: | Size: 5.5 KiB After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 22 KiB |
@@ -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| {
|
||||
|
||||
@@ -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/"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -31,7 +31,7 @@ onMounted(() => {
|
||||
async function connect() {
|
||||
offline.value = "";
|
||||
ready.value = false;
|
||||
for (let attempt = 0; attempt < 20; attempt += 1) {
|
||||
for (let attempt = 0; attempt < 40; attempt += 1) {
|
||||
try {
|
||||
const result = await loadCaptcha();
|
||||
sessionId.value = result.sessionId;
|
||||
|
||||
@@ -1,4 +1,27 @@
|
||||
export const API_BASE = import.meta.env.DEV ? "" : "http://127.0.0.1:8765";
|
||||
let apiBase = "";
|
||||
let preparing: Promise<void> | null = null;
|
||||
|
||||
export function initApi(): Promise<void> {
|
||||
preparing ??= resolveApiBase();
|
||||
return preparing;
|
||||
}
|
||||
|
||||
async function resolveApiBase(): Promise<void> {
|
||||
if (!("__TAURI_INTERNALS__" in window)) return;
|
||||
const { invoke } = await import("@tauri-apps/api/core");
|
||||
for (let attempt = 0; attempt < 50; attempt += 1) {
|
||||
try {
|
||||
const port = await invoke<number>("backend_port");
|
||||
if (port > 0) {
|
||||
apiBase = `http://127.0.0.1:${port}`;
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
// 窗口可能比端口命令更早就绪。
|
||||
}
|
||||
await new Promise((resolve) => window.setTimeout(resolve, 100));
|
||||
}
|
||||
}
|
||||
|
||||
export class ApiError extends Error {
|
||||
status: number;
|
||||
@@ -10,13 +33,14 @@ export class ApiError extends Error {
|
||||
}
|
||||
|
||||
export async function api<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
await initApi();
|
||||
let response: Response;
|
||||
try {
|
||||
const headers = new Headers(init?.headers);
|
||||
if (init?.body && !(init.body instanceof FormData) && !headers.has("Content-Type")) {
|
||||
headers.set("Content-Type", "application/json");
|
||||
}
|
||||
response = await fetch(`${API_BASE}${path}`, { ...init, headers });
|
||||
response = await fetch(`${apiBase}${path}`, { ...init, headers });
|
||||
} catch {
|
||||
throw new ApiError(0, "连接失败");
|
||||
}
|
||||
|
||||
@@ -17,12 +17,6 @@ export default defineConfig(() => ({
|
||||
port: 1420,
|
||||
strictPort: true,
|
||||
host: host || false,
|
||||
proxy: {
|
||||
"/api": {
|
||||
target: "http://127.0.0.1:8765",
|
||||
changeOrigin: true,
|
||||
},
|
||||
},
|
||||
hmr: host
|
||||
? {
|
||||
protocol: "ws",
|
||||
|
||||