fix: 切换或退出登录前先暂停任务,重新登录后继续失效任务

This commit is contained in:
2026-10-25 07:12:35 +08:00
parent cd1aeb1d0f
commit 81f7f16712
2 changed files with 65 additions and 9 deletions
+32 -9
View File
@@ -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: async def purge_expired_flows(now: float | None = None) -> None:
"""关掉超过 10 分钟的登录流程,并清掉内存里的密码。""" """关掉超过 10 分钟的登录流程,并清掉内存里的密码。"""
moment = time.monotonic() if now is None else now 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 raise HTTPException(status_code=400, detail=message) from exc
challenge.password = "" challenge.password = ""
await remember_account(user, client.export_cookies()) await remember_account(user, client.export_cookies())
state.flows.pop(session_id, None) if state.client is not client:
if state.client is not None and state.client is not client: await _pause_and_close_client("switch")
await state.client.aclose()
state.client = client state.client = client
state.user = user state.user = user
state.flows.pop(session_id, None)
_accept_login()
return {"status": "ok", "user": user} return {"status": "ok", "user": user}
@@ -152,10 +175,11 @@ async def resume_saved(body: dict) -> dict:
client, user = await resume(login_id) client, user = await resume(login_id)
except NqiError as exc: except NqiError as exc:
raise _bad(str(exc)) from exc raise _bad(str(exc)) from exc
if state.client is not None and state.client is not client: if state.client is not client:
await state.client.aclose() await _pause_and_close_client("switch")
state.client = client state.client = client
state.user = user state.user = user
_accept_login()
return {"status": "ok", "user": user} return {"status": "ok", "user": user}
@@ -167,8 +191,7 @@ async def me() -> dict:
@router.post("/logout") @router.post("/logout")
async def logout() -> dict: async def logout() -> dict:
if state.client is not None: paused = await _pause_and_close_client("logout")
await state.client.aclose()
state.client = None
state.user = None state.user = None
return {"ok": True} state.expired = False
return {"ok": True, "paused": paused}
+33
View File
@@ -7,6 +7,7 @@ import base64
import calendar import calendar
import json import json
import re import re
import time
from collections import deque from collections import deque
from collections.abc import AsyncIterator from collections.abc import AsyncIterator
from dataclasses import dataclass, field from dataclasses import dataclass, field
@@ -126,6 +127,9 @@ class NqiClient:
client: httpx.AsyncClient = field(init=False) client: httpx.AsyncClient = field(init=False)
def __post_init__(self) -> None: def __post_init__(self) -> None:
self._inflight = 0
self._idle = asyncio.Event()
self._idle.set()
self.client = httpx.AsyncClient( self.client = httpx.AsyncClient(
headers={ headers={
"User-Agent": USER_AGENT, "User-Agent": USER_AGENT,
@@ -140,10 +144,39 @@ class NqiClient:
max_keepalive_connections=POOL_CONNECTIONS, 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: async def aclose(self) -> None:
await self.client.aclose() 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]]: def export_cookies(self) -> list[dict[str, str]]:
exported: list[dict[str, str]] = [] exported: list[dict[str, str]] = []
for cookie in self.client.cookies.jar: for cookie in self.client.cookies.jar: