fix: 推送按序号只保留最新一帧,倒计时改用剩余秒数

This commit is contained in:
2026-11-16 09:38:07 +08:00
parent f20cf79e57
commit 556121a265
6 changed files with 57 additions and 30 deletions
+1 -10
View File
@@ -30,7 +30,6 @@ from euniv.models import Account
from euniv.login_limit import allow as login_allowed
from euniv.service import (
fetch_exam_detail,
fetch_home,
fetch_home_exams,
fetch_home_summary,
fetch_home_trainings,
@@ -287,14 +286,6 @@ def _signed_in(request: Request, db: Session) -> str:
return employee_id
@app.get("/api/home")
def home(request: Request, db: Session = Depends(get_db)) -> dict:
try:
return fetch_home(db, _signed_in(request, db))
except RuntimeError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@app.get("/api/home/summary")
def home_summary(request: Request, db: Session = Depends(get_db)) -> dict:
try:
@@ -455,7 +446,7 @@ def get_study_control(request: Request, db: Session = Depends(get_db)) -> dict:
live = dict((status.get("users") or {}).get(employee_id) or {})
if settle(account, live):
db.commit()
return assemble(account, live)
return stamp_frame(employee_id, assemble(account, live))
@app.post("/api/settings/study-control")
+14 -3
View File
@@ -3,13 +3,24 @@
from __future__ import annotations
import re
import threading
from datetime import datetime
from euniv.study_window import month_key, window_open
class StudyControlError(ValueError):
"""任务控制参数不符合要求。"""
_frame_lock = threading.Lock()
_frames: dict[str, int] = {}
def stamp_frame(employee_id: str, payload: dict) -> dict:
key = (employee_id or "").strip()
with _frame_lock:
number = _frames.get(key, 0) + 1
_frames[key] = number
stamped = dict(payload)
stamped["seq"] = number
return stamped
def start_now(account, now: datetime | None = None) -> None:
@@ -179,4 +190,4 @@ def payload_for(employee_id: str) -> dict:
live = dict((status.get("users") or {}).get(key) or {})
if settle(account, live):
db.commit()
return assemble(account, live)
return stamp_frame(key, assemble(account, live))
+14 -9
View File
@@ -86,20 +86,24 @@ def _arm(employee_id: str, delay: float) -> None:
if delay <= 0:
if employee_id in _inflight:
return
loop.create_task(_flush(employee_id))
_inflight.add(employee_id)
loop.create_task(_flush(employee_id, armed=True))
return
_pending[employee_id] = loop.call_later(delay, lambda: asyncio.create_task(_flush(employee_id)))
async def _flush(employee_id: str) -> None:
async def _flush(employee_id: str, armed: bool = False) -> None:
_pending.pop(employee_id, None)
sockets = list(_clients.get(employee_id) or ())
if not sockets:
_dirty.discard(employee_id)
_urgent.discard(employee_id)
return
_inflight.add(employee_id)
if not armed:
if employee_id in _inflight:
return
_inflight.add(employee_id)
try:
sockets = list(_clients.get(employee_id) or ())
if not sockets:
_dirty.discard(employee_id)
_urgent.discard(employee_id)
return
_dirty.discard(employee_id)
_urgent.discard(employee_id)
from euniv.study_control import payload_for
@@ -113,13 +117,14 @@ async def _flush(employee_id: str) -> None:
if ws.client_state != WebSocketState.CONNECTED:
dead.append(ws)
continue
await ws.send_json(payload)
await asyncio.wait_for(ws.send_json(payload), timeout=5)
except Exception:
dead.append(ws)
for ws in dead:
unregister(employee_id, ws)
except Exception:
log.debug("学习状态快照失败", exc_info=True)
_dirty.add(employee_id)
finally:
_inflight.discard(employee_id)
if employee_id in _dirty:
-1
View File
@@ -97,7 +97,6 @@ def test_admin_login_succeeds_and_wrong_password_skips_euniv() -> None:
assert "euniv_admin_session" in client.cookies
assert COOKIE_NAME not in client.cookies
assert client.get("/api/session").json() == {"role": "admin", "username": "admin"}
assert client.get("/api/home").status_code == 403
assert client.get("/api/home/summary").status_code == 403
assert client.get("/api/home/exams").status_code == 403
assert client.get("/api/home/trainings").status_code == 403
+12 -6
View File
@@ -113,10 +113,18 @@ def test_login_stores_password_and_credential_only() -> None:
import euniv.api as api_module
import euniv.service as service_module
class RefreshingClient(FakeClient):
def home_summary(self) -> dict:
if self._token == "yxt-1":
self._token = "yxt-2"
return super().home_summary()
api_module.login_and_store = lambda db, employee_id, password, manual=False, auto_attempts=3: service_module.login_and_store(
db, employee_id, password, FakeClient, manual=manual, auto_attempts=auto_attempts
)
api_module.fetch_home = lambda db, employee_id: service_module.fetch_home(db, employee_id, FakeClient)
api_module.fetch_home_summary = lambda db, employee_id: service_module.fetch_home_summary(
db, employee_id, RefreshingClient
)
client = TestClient(api_module.app)
response = client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"})
assert response.status_code == 200
@@ -157,11 +165,9 @@ def test_login_stores_password_and_credential_only() -> None:
"password_login_at",
}
home = client.get("/api/home")
assert home.status_code == 200
body = home.json()
assert body["name"] == "测试用户"
assert body["exams"] == [{"name": "安全考试", "status": "已完成", "start": "2026-05-20 00:01:00"}]
summary = client.get("/api/home/summary")
assert summary.status_code == 200
assert summary.json()["name"] == "测试用户"
with SessionLocal() as db:
account = db.get(Account, "6650000146")
assert account is not None