fix: 并发确认已保存账号,写回前重新读取再合并
This commit is contained in:
@@ -2,7 +2,9 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
from datetime import datetime
|
||||
|
||||
import httpx
|
||||
@@ -10,7 +12,10 @@ import httpx
|
||||
from app.platform.client import NqiAuthError, NqiClient, NqiError
|
||||
from app.shared.paths import DATA_ROOT
|
||||
|
||||
logger = logging.getLogger("nqi.auth")
|
||||
STORE = DATA_ROOT / "sessions.json"
|
||||
PROBE_TIMEOUT_SECONDS = 8
|
||||
_write_lock = asyncio.Lock()
|
||||
|
||||
|
||||
def _read() -> list[dict]:
|
||||
@@ -34,7 +39,7 @@ def _write(accounts: list[dict]) -> None:
|
||||
temporary.replace(STORE)
|
||||
|
||||
|
||||
def remember(user: dict, cookies: list[dict]) -> None:
|
||||
def _upsert(user: dict, cookies: list[dict]) -> None:
|
||||
login_id = str(user.get("loginId") or "").strip()
|
||||
if not login_id or not cookies:
|
||||
return
|
||||
@@ -53,10 +58,25 @@ def remember(user: dict, cookies: list[dict]) -> None:
|
||||
_write(accounts)
|
||||
|
||||
|
||||
def remember(user: dict, cookies: list[dict]) -> None:
|
||||
"""同步写入。并发路径使用 remember_account,写前会重新读取。"""
|
||||
_upsert(user, cookies)
|
||||
|
||||
|
||||
async def remember_account(user: dict, cookies: list[dict]) -> None:
|
||||
async with _write_lock:
|
||||
_upsert(user, cookies)
|
||||
|
||||
|
||||
def forget(login_id: str) -> None:
|
||||
_write([item for item in _read() if item.get("loginId") != login_id])
|
||||
|
||||
|
||||
async def forget_account(login_id: str) -> None:
|
||||
async with _write_lock:
|
||||
forget(login_id)
|
||||
|
||||
|
||||
def public_view(item: dict) -> dict:
|
||||
return {
|
||||
"loginId": item.get("loginId") or "",
|
||||
@@ -66,34 +86,74 @@ def public_view(item: dict) -> dict:
|
||||
}
|
||||
|
||||
|
||||
async def _probe(item: dict) -> tuple[str, dict | None]:
|
||||
"""返回 drop、keep 或 ok。只有确认登录失效才 drop。"""
|
||||
client = NqiClient()
|
||||
try:
|
||||
client.import_cookies(item.get("cookies") or [])
|
||||
user = await asyncio.wait_for(client.current_user(), PROBE_TIMEOUT_SECONDS)
|
||||
except NqiAuthError:
|
||||
return "drop", None
|
||||
except (NqiError, httpx.TimeoutException, httpx.RequestError, TimeoutError) as exc:
|
||||
logger.info("暂时无法确认已保存账号: %s", exc)
|
||||
return "keep", None
|
||||
except Exception as exc:
|
||||
logger.info("暂时无法确认已保存账号: %s", exc)
|
||||
return "keep", None
|
||||
else:
|
||||
cookies = client.export_cookies() or list(item.get("cookies") or [])
|
||||
login_id = str(user.get("loginId") or item.get("loginId") or "").strip()
|
||||
if not login_id or not cookies:
|
||||
return "keep", None
|
||||
return "ok", {
|
||||
"loginId": login_id,
|
||||
"userName": user.get("userName") or "",
|
||||
"cityName": user.get("cityName") or "",
|
||||
"orgName": user.get("orgName") or "",
|
||||
"savedAt": datetime.now().isoformat(timespec="seconds"),
|
||||
"cookies": cookies,
|
||||
}
|
||||
finally:
|
||||
await client.aclose()
|
||||
|
||||
|
||||
async def _merge(changes: list[tuple[str, str, dict | None]]) -> None:
|
||||
"""重新读文件再合并,避免覆盖这段时间里别的写入。"""
|
||||
async with _write_lock:
|
||||
current = _read()
|
||||
by_id: dict[str, dict] = {}
|
||||
order: list[str] = []
|
||||
for item in current:
|
||||
login_id = str(item.get("loginId") or "")
|
||||
if not login_id or login_id in by_id:
|
||||
continue
|
||||
by_id[login_id] = item
|
||||
order.append(login_id)
|
||||
for login_id, status, record in changes:
|
||||
if status == "drop":
|
||||
by_id.pop(login_id, None)
|
||||
if login_id in order:
|
||||
order.remove(login_id)
|
||||
continue
|
||||
if status == "ok" and record is not None:
|
||||
by_id[login_id] = record
|
||||
if login_id not in order:
|
||||
order.insert(0, login_id)
|
||||
_write([by_id[key] for key in order if key in by_id])
|
||||
|
||||
|
||||
async def available_accounts() -> list[dict]:
|
||||
"""向平台确认每条凭证。失效的删掉,暂时连不上的先留着但不显示。"""
|
||||
kept: list[dict] = []
|
||||
"""并发向平台确认每条凭证。失效的删掉,暂时连不上的留着但不显示。"""
|
||||
items = _read()
|
||||
probed = await asyncio.gather(*(_probe(item) for item in items))
|
||||
changes: list[tuple[str, str, dict | None]] = []
|
||||
visible: list[dict] = []
|
||||
for item in _read():
|
||||
client = NqiClient()
|
||||
try:
|
||||
client.import_cookies(item.get("cookies") or [])
|
||||
user = await client.current_user()
|
||||
except NqiAuthError:
|
||||
continue
|
||||
except (NqiError, httpx.TimeoutException, httpx.RequestError, TimeoutError):
|
||||
kept.append(item)
|
||||
continue
|
||||
else:
|
||||
item.update(
|
||||
{
|
||||
"loginId": user["loginId"] or item.get("loginId"),
|
||||
"userName": user["userName"],
|
||||
"cityName": user["cityName"],
|
||||
"orgName": user["orgName"],
|
||||
}
|
||||
)
|
||||
kept.append(item)
|
||||
visible.append(public_view(item))
|
||||
finally:
|
||||
await client.aclose()
|
||||
_write(kept)
|
||||
for item, (status, record) in zip(items, probed):
|
||||
login_id = str(item.get("loginId") or "")
|
||||
changes.append((login_id, status, record))
|
||||
if status == "ok" and record is not None:
|
||||
visible.append(public_view(record))
|
||||
await _merge(changes)
|
||||
return visible
|
||||
|
||||
|
||||
@@ -107,7 +167,7 @@ async def resume(login_id: str) -> tuple[NqiClient, dict]:
|
||||
user = await client.current_user()
|
||||
except NqiAuthError:
|
||||
await client.aclose()
|
||||
forget(login_id)
|
||||
await forget_account(login_id)
|
||||
raise NqiError("这个账号的登录已失效") from None
|
||||
except NqiError:
|
||||
await client.aclose()
|
||||
@@ -115,5 +175,5 @@ async def resume(login_id: str) -> tuple[NqiClient, dict]:
|
||||
except (httpx.TimeoutException, httpx.RequestError, TimeoutError):
|
||||
await client.aclose()
|
||||
raise NqiError("连接失败,请稍后重试") from None
|
||||
remember(user, client.export_cookies())
|
||||
await remember_account(user, client.export_cookies())
|
||||
return client, user
|
||||
|
||||
Reference in New Issue
Block a user