From 0d7bc8ed2209efbe4b51a901939daeb4ea458b77 Mon Sep 17 00:00:00 2001 From: Nixevol Date: Sun, 25 Oct 2026 07:14:01 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E7=88=B6=E8=BF=9B=E7=A8=8B=E9=80=80?= =?UTF-8?q?=E5=87=BA=E6=88=96=E6=95=B0=E6=8D=AE=E7=9B=AE=E5=BD=95=E8=A2=AB?= =?UTF-8?q?=E5=8D=A0=E7=94=A8=E6=97=B6=E7=BB=93=E6=9D=9F=E5=90=8E=E5=8F=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/app/main.py | 103 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 103 insertions(+) diff --git a/backend/app/main.py b/backend/app/main.py index b8f06ff..a438ded 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -1,9 +1,13 @@ """本机接口。只监听 127.0.0.1。功能路由按目录挂上。""" import asyncio +import ctypes import logging +import msvcrt +import os import sys from contextlib import asynccontextmanager, suppress +from ctypes import wintypes from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware @@ -11,8 +15,11 @@ from fastapi.middleware.cors import CORSMiddleware from app.features.download.router import router as download_router from app.platform.auth import router as auth_router from app.platform.keepalive import session_keepalive +from app.shared.paths import DATA_ROOT from app.shared.state import state +logger = logging.getLogger("nqi.backend") + ORIGINS = [ "http://localhost:1420", "http://127.0.0.1:1420", @@ -20,6 +27,9 @@ ORIGINS = [ "http://tauri.localhost", "https://tauri.localhost", ] +PARENT_CHECK_SECONDS = 2 +_LOCK_BYTES = 1 +_lock_file = None def configure_logging() -> None: @@ -34,20 +44,113 @@ def configure_logging() -> None: nqi.propagate = False +def _parent_pid() -> int | None: + raw = os.environ.get("NQI_PARENT_PID", "").strip() + if not raw: + return None + try: + pid = int(raw) + except ValueError: + logger.error("NQI_PARENT_PID 不是有效的进程号") + return None + if pid <= 0: + logger.error("NQI_PARENT_PID 不是有效的进程号") + return None + return pid + + +def _parent_running(pid: int) -> bool: + """父进程还在就返回 True。不用 os.kill,避免在 Windows 上把目标进程结束掉。""" + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + kernel32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD] + kernel32.OpenProcess.restype = wintypes.HANDLE + kernel32.WaitForSingleObject.argtypes = [wintypes.HANDLE, wintypes.DWORD] + kernel32.WaitForSingleObject.restype = wintypes.DWORD + kernel32.CloseHandle.argtypes = [wintypes.HANDLE] + kernel32.CloseHandle.restype = wintypes.BOOL + + synchronize = 0x00100000 + handle = kernel32.OpenProcess(synchronize, False, pid) + if not handle: + # 拒绝访问说明进程还在,只是没有等待它的权限。 + if ctypes.get_last_error() == 5: + return True + return False + try: + # 超时 0:已退出返回 WAIT_OBJECT_0,仍在运行返回 WAIT_TIMEOUT。 + waited = kernel32.WaitForSingleObject(handle, 0) + return waited == 0x00000102 + finally: + kernel32.CloseHandle(handle) + + +async def _watch_parent(pid: int) -> None: + while True: + await asyncio.sleep(PARENT_CHECK_SECONDS) + if _parent_running(pid): + continue + logger.info("父进程已退出,后台结束") + os._exit(0) + + +def _acquire_data_lock() -> None: + global _lock_file + if _lock_file is not None: + return + DATA_ROOT.mkdir(parents=True, exist_ok=True) + handle = open(DATA_ROOT / "backend.lock", "a+b") + try: + handle.seek(0, os.SEEK_END) + if handle.tell() < _LOCK_BYTES: + handle.write(b"\0") + handle.flush() + handle.seek(0) + msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, _LOCK_BYTES) + except OSError: + handle.close() + logger.error("数据目录已被其他后台占用,本进程退出") + os._exit(1) + _lock_file = handle + + +def _release_data_lock() -> None: + global _lock_file + handle = _lock_file + _lock_file = None + if handle is None: + return + try: + handle.seek(0) + msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, _LOCK_BYTES) + except OSError: + pass + finally: + handle.close() + + @asynccontextmanager async def lifespan(_app: FastAPI): configure_logging() + _acquire_data_lock() keepalive = asyncio.create_task(session_keepalive()) + parent = _parent_pid() + watcher = asyncio.create_task(_watch_parent(parent)) if parent is not None else None try: yield finally: keepalive.cancel() + if watcher is not None: + watcher.cancel() with suppress(asyncio.CancelledError): await keepalive + if watcher is not None: + with suppress(asyncio.CancelledError): + await watcher if state.client is not None: await state.client.aclose() for client, _challenge in state.flows.values(): await client.aclose() + _release_data_lock() app = FastAPI(title="NqiTools", lifespan=lifespan)