fix: 推送按序号只保留最新一帧,倒计时改用剩余秒数
This commit is contained in:
+1
-10
@@ -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")
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -23,6 +23,8 @@ interface StudyWorker {
|
||||
progress: number;
|
||||
interval: number;
|
||||
heartbeat_at: number;
|
||||
heartbeat_in: number;
|
||||
seen_at: number;
|
||||
sent: number;
|
||||
total: number;
|
||||
ok: boolean;
|
||||
@@ -184,6 +186,8 @@ function asWorkers(value: unknown): StudyWorker[] {
|
||||
progress: typeof row.progress === "number" ? row.progress : 0,
|
||||
interval: typeof row.interval === "number" ? row.interval : 0,
|
||||
heartbeat_at: typeof row.heartbeat_at === "number" ? row.heartbeat_at : 0,
|
||||
heartbeat_in: typeof row.heartbeat_in === "number" ? row.heartbeat_in : 0,
|
||||
seen_at: Date.now(),
|
||||
sent: typeof row.sent === "number" ? row.sent : 0,
|
||||
total: typeof row.total === "number" ? row.total : 0,
|
||||
ok: row.ok !== false,
|
||||
@@ -209,7 +213,7 @@ function workerTitle(row: StudyWorker) {
|
||||
}
|
||||
|
||||
function showHeartbeat(row: StudyWorker) {
|
||||
return row.interval > 0 && row.heartbeat_at > 0;
|
||||
return row.heartbeat_in > 0 || (row.interval > 0 && row.heartbeat_at > 0);
|
||||
}
|
||||
|
||||
function workerCount(row: StudyWorker) {
|
||||
@@ -220,6 +224,12 @@ function workerCount(row: StudyWorker) {
|
||||
|
||||
function heartbeatLeft(row: StudyWorker) {
|
||||
void nowTick.value;
|
||||
if (row.heartbeat_in > 0) {
|
||||
const elapsed = (Date.now() - row.seen_at) / 1000;
|
||||
const cap = row.interval > 0 ? row.interval : row.heartbeat_in;
|
||||
const left = Math.max(0, Math.min(cap, row.heartbeat_in - elapsed));
|
||||
return `${Math.ceil(left)}s`;
|
||||
}
|
||||
const now = Date.now() / 1000;
|
||||
const cycle = Math.max(0, row.interval);
|
||||
let left = row.heartbeat_at - now;
|
||||
@@ -500,7 +510,12 @@ async function saveProxy() {
|
||||
}
|
||||
}
|
||||
|
||||
let lastStudySeq = 0;
|
||||
|
||||
function applyStudyControl(payload: Record<string, unknown>) {
|
||||
const seq = typeof payload.seq === "number" ? payload.seq : 0;
|
||||
if (seq > 0 && seq < lastStudySeq) return;
|
||||
if (seq > 0) lastStudySeq = seq;
|
||||
studyControl.value = {
|
||||
started: payload.started === true,
|
||||
paused: payload.paused === true,
|
||||
|
||||
Reference in New Issue
Block a user