diff --git a/backend/admin/routes.py b/backend/admin/routes.py index 29e9358..e42b534 100644 --- a/backend/admin/routes.py +++ b/backend/admin/routes.py @@ -11,6 +11,7 @@ from admin.session import admin_session_active, clear_admin_session, write_admin from admin.settings import SettingsError, load_config, login_config_view, save_settings, settings_view from admin.users import ( check_all, + check_state, check_employee, clear_proxy, delete_user, @@ -181,10 +182,15 @@ def get_users(db: Session = Depends(get_db), _: str = Depends(require_admin)) -> @admin_router.post("/users/check-all") -def post_check_all(db: Session = Depends(get_db), _: str = Depends(require_admin)) -> list[dict]: +def post_check_all(db: Session = Depends(get_db), _: str = Depends(require_admin)) -> list[dict] | dict: return check_all(db) +@admin_router.get("/users/check-all") +def get_check_all(_: str = Depends(require_admin)) -> dict: + return check_state() + + @admin_router.post("/users/{employee_id}/check") def post_check(employee_id: str, db: Session = Depends(get_db), _: str = Depends(require_admin)) -> dict: return check_employee(db, employee_id) diff --git a/backend/admin/users.py b/backend/admin/users.py index be74e08..cd3176d 100644 --- a/backend/admin/users.py +++ b/backend/admin/users.py @@ -3,6 +3,7 @@ from __future__ import annotations import json +import threading from datetime import datetime, timezone from fastapi import HTTPException @@ -159,7 +160,58 @@ def check_employee(db: Session, employee_id: str) -> dict: return payload -def check_all(db: Session) -> list[dict]: +def _check_saved(db: Session, employee_ids: list[str]) -> list[dict]: + results = [] + for employee_id in employee_ids: + try: + results.append(check_employee(db, employee_id)) + except HTTPException as exc: + if exc.status_code == 404: + continue + raise + except Exception: + results.append({"employee_id": employee_id, "result": "检查失败", "detail": "检查失败"}) + return results + + +_CHECK_INLINE = 8 +_check_guard = threading.Lock() +_check_running = False +_check_results: list[dict] = [] +_check_error = "" + + +def check_state() -> dict: + with _check_guard: + return {"running": _check_running, "results": list(_check_results), "error": _check_error} + + +def _run_check(employee_ids: list[str]) -> None: + global _check_running, _check_results, _check_error + from euniv.db import SessionLocal + + results: list[dict] = [] + error = "" + try: + for employee_id in employee_ids: + with SessionLocal() as db: + try: + results.append(check_employee(db, employee_id)) + except HTTPException as exc: + if exc.status_code != 404: + raise + except Exception: + results.append({"employee_id": employee_id, "result": "检查失败", "detail": "检查失败"}) + except Exception: + error = "检查失败" + with _check_guard: + _check_results = results + _check_error = error + _check_running = False + + +def check_all(db: Session) -> list[dict] | dict: + global _check_running employee_ids = list( db.scalars( select(Account.employee_id) @@ -167,15 +219,16 @@ def check_all(db: Session) -> list[dict]: .order_by(Account.employee_id) ) ) - results = [] - for employee_id in employee_ids: - try: - results.append(check_employee(db, employee_id)) - except HTTPException: - raise - except Exception: - results.append({"employee_id": employee_id, "result": "检查失败", "detail": "检查失败"}) - return results + if len(employee_ids) <= _CHECK_INLINE: + return _check_saved(db, employee_ids) + with _check_guard: + if _check_running: + return check_state() + _check_running = True + _check_results = [] + _check_error = "" + threading.Thread(target=_run_check, args=(employee_ids,), name="euniv-check-all", daemon=True).start() + return {"running": True, "results": [], "error": ""} def set_paused(db: Session, employee_id: str, paused: bool) -> dict: diff --git a/backend/euniv/api.py b/backend/euniv/api.py index 752cd01..77ff4f9 100644 --- a/backend/euniv/api.py +++ b/backend/euniv/api.py @@ -153,6 +153,15 @@ def reject_bad_body(_request: Request, exc: RequestValidationError) -> JSONRespo return JSONResponse(status_code=422, content={"detail": "请求格式不正确"}) +@app.exception_handler(Exception) +def reject_unexpected(_request: Request, exc: Exception) -> JSONResponse: + if isinstance(exc, HTTPException): + detail = exc.detail if isinstance(exc.detail, str) else "请求没有完成" + return JSONResponse(status_code=exc.status_code, content={"detail": detail}) + logging.getLogger("euniv.api").exception("请求没有完成") + return JSONResponse(status_code=500, content={"detail": "服务暂时不可用"}) + + class LoginBody(BaseModel): employee_id: str = Field(min_length=1, max_length=64) password: str = Field(min_length=1, max_length=128) diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 00e9cf2..4c48e0e 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -53,3 +53,36 @@ def fresh_database(): users = autostudy_mod._status.get("users") if isinstance(users, dict): users.clear() + from euniv import encrypt as encrypt_mod + from euniv import service as service_mod + from euniv import study_push + + for pending in list(service_mod._pending.values()) + list(service_mod._pending_qr.values()): + client = getattr(pending, "client", None) + if client is not None: + try: + client.close() + except Exception: + pass + service_mod._pending.clear() + service_mod._pending_qr.clear() + service_mod._pending_busy.clear() + for handle in list(study_push._pending.values()): + handle.cancel() + study_push._pending.clear() + study_push._inflight.clear() + study_push._dirty.clear() + study_push._urgent.clear() + study_push._last_flush.clear() + study_push._clients.clear() + study_push._loop = None + with encrypt_mod._lock: + encrypt_mod._config.clear() + encrypt_mod._config.update( + { + "path": encrypt_mod.DEFAULT_ENCRYPT_PATH, + "js_url": encrypt_mod.DEFAULT_JS_URL, + "loaded_at": 0.0, + "retry_at": 0.0, + } + ) diff --git a/web/src/features/admin/UsersView.vue b/web/src/features/admin/UsersView.vue index d2a5edd..1341917 100644 --- a/web/src/features/admin/UsersView.vue +++ b/web/src/features/admin/UsersView.vue @@ -297,6 +297,28 @@ async function checkOne(row: UserRow) { } } +async function applyCheckResults(payload: unknown) { + if (!Array.isArray(payload)) { + errorText.value = "检查失败"; + return; + } + const next = { ...liveResults.value }; + const notes: string[] = []; + for (const item of payload) { + if (!isRecord(item) || item.employee_id == null) continue; + const employeeId = String(item.employee_id); + const label = checkLabel(item); + next[employeeId] = label; + if (label === "检查失败") { + const detail = typeof item.detail === "string" ? item.detail : ""; + if (detail) notes.push(`${employeeId}:${detail}`); + } + } + liveResults.value = next; + errorText.value = notes.join(";"); + await load(); +} + async function checkAll() { if (checkingId.value || checkingAll.value || !users.value.length) return; checkingAll.value = true; @@ -308,25 +330,27 @@ async function checkAll() { errorText.value = detailOf(payload, "检查失败"); return; } - if (!Array.isArray(payload)) { - errorText.value = detailOf(payload, "检查失败"); + if (isRecord(payload) && payload.running === true) { + for (let attempt = 0; attempt < 120; attempt += 1) { + await new Promise((resolve) => window.setTimeout(resolve, 1000)); + const status = await apiFetch("/api/admin/users/check-all"); + const body: unknown = await status.json().catch(() => ({})); + if (!status.ok || !isRecord(body)) { + errorText.value = "检查失败"; + return; + } + if (body.running === true) continue; + if (typeof body.error === "string" && body.error) { + errorText.value = body.error; + return; + } + await applyCheckResults(body.results); + return; + } + errorText.value = "检查失败"; return; } - const next = { ...liveResults.value }; - const notes: string[] = []; - for (const item of payload) { - if (!isRecord(item) || item.employee_id == null) continue; - const employeeId = String(item.employee_id); - const label = checkLabel(item); - next[employeeId] = label; - if (label === "检查失败") { - const detail = typeof item.detail === "string" ? item.detail : ""; - if (detail) notes.push(`${employeeId}:${detail}`); - } - } - liveResults.value = next; - errorText.value = notes.join(";"); - await load(); + await applyCheckResults(payload); } catch { errorText.value = "检查失败"; } finally {