"""本机接口。只监听 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 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", "tauri://localhost", "http://tauri.localhost", "https://tauri.localhost", ] PARENT_CHECK_SECONDS = 2 _LOCK_BYTES = 1 _lock_file = None def configure_logging() -> None: """让 nqi.* 的 INFO 写到标准输出。uvicorn 默认不接管这个记录器。""" nqi = logging.getLogger("nqi") nqi.setLevel(logging.INFO) if not any(getattr(handler, "_nqi_stdout", False) for handler in nqi.handlers): handler = logging.StreamHandler(sys.stdout) handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(name)s: %(message)s")) handler._nqi_stdout = True nqi.addHandler(handler) 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) app.add_middleware( CORSMiddleware, allow_origins=ORIGINS, allow_credentials=False, allow_methods=["*"], allow_headers=["*"], ) app.include_router(auth_router) app.include_router(download_router) @app.get("/api/health") async def health() -> dict: return {"ok": True} if __name__ == "__main__": import os import socket import uvicorn configure_logging() 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)