diff --git a/backend/app/platform/auth.py b/backend/app/platform/auth.py index f21668c..f41155d 100644 --- a/backend/app/platform/auth.py +++ b/backend/app/platform/auth.py @@ -31,6 +31,28 @@ def _captcha_payload(session_id: str, challenge, **extra) -> dict: } +async def _pause_and_close_client(mark: str) -> int: + """先暂停进行中的任务,等在途请求结束,再关闭当前客户端。""" + paused = sum(1 for job in state.jobs.jobs.values() if job.status in {"running", "queued"}) + state.jobs.suspend_all("已暂停", mark) + client = state.client + state.client = None + if client is not None: + wait_idle = getattr(client, "wait_idle", None) + if wait_idle is not None: + await wait_idle(5) + await client.aclose() + return paused + + +def _accept_login() -> None: + state.expired = False + state.jobs.resume_marked("expired") + from app.features.download.router import fill_slots + + fill_slots() + + async def purge_expired_flows(now: float | None = None) -> None: """关掉超过 10 分钟的登录流程,并清掉内存里的密码。""" moment = time.monotonic() if now is None else now @@ -130,11 +152,12 @@ async def login(body: dict) -> dict: raise HTTPException(status_code=400, detail=message) from exc challenge.password = "" await remember_account(user, client.export_cookies()) - state.flows.pop(session_id, None) - if state.client is not None and state.client is not client: - await state.client.aclose() + if state.client is not client: + await _pause_and_close_client("switch") state.client = client state.user = user + state.flows.pop(session_id, None) + _accept_login() return {"status": "ok", "user": user} @@ -152,10 +175,11 @@ async def resume_saved(body: dict) -> dict: client, user = await resume(login_id) except NqiError as exc: raise _bad(str(exc)) from exc - if state.client is not None and state.client is not client: - await state.client.aclose() + if state.client is not client: + await _pause_and_close_client("switch") state.client = client state.user = user + _accept_login() return {"status": "ok", "user": user} @@ -167,8 +191,7 @@ async def me() -> dict: @router.post("/logout") async def logout() -> dict: - if state.client is not None: - await state.client.aclose() - state.client = None + paused = await _pause_and_close_client("logout") state.user = None - return {"ok": True} + state.expired = False + return {"ok": True, "paused": paused} diff --git a/backend/app/platform/client.py b/backend/app/platform/client.py index a2b412f..d3f71c6 100644 --- a/backend/app/platform/client.py +++ b/backend/app/platform/client.py @@ -7,6 +7,7 @@ import base64 import calendar import json import re +import time from collections import deque from collections.abc import AsyncIterator from dataclasses import dataclass, field @@ -126,6 +127,9 @@ class NqiClient: client: httpx.AsyncClient = field(init=False) def __post_init__(self) -> None: + self._inflight = 0 + self._idle = asyncio.Event() + self._idle.set() self.client = httpx.AsyncClient( headers={ "User-Agent": USER_AGENT, @@ -140,10 +144,39 @@ class NqiClient: max_keepalive_connections=POOL_CONNECTIONS, ), ) + raw_send = self.client.send + + async def send(request, *args, **kwargs): + self._inflight += 1 + self._idle.clear() + try: + return await raw_send(request, *args, **kwargs) + finally: + self._inflight = max(0, self._inflight - 1) + if self._inflight == 0: + self._idle.set() + + self.client.send = send async def aclose(self) -> None: await self.client.aclose() + async def wait_idle(self, timeout: float = 5.0) -> None: + """等在途请求结束。到时仍未结束也返回,调用方再关闭客户端。""" + deadline = time.monotonic() + timeout + while True: + if self._inflight == 0: + await asyncio.sleep(0) + if self._inflight == 0: + return + remaining = deadline - time.monotonic() + if remaining <= 0: + return + try: + await asyncio.wait_for(self._idle.wait(), min(0.2, remaining)) + except TimeoutError: + continue + def export_cookies(self) -> list[dict[str, str]]: exported: list[dict[str, str]] = [] for cookie in self.client.cookies.jar: