feat: 学习状态改为内存快照,页面连接每秒自取并自动重连

This commit is contained in:
2026-11-17 17:36:22 +08:00
parent 42b29fb4d6
commit 4d1a90c321
11 changed files with 675 additions and 256 deletions
+6 -8
View File
@@ -68,15 +68,13 @@ def fresh_database():
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._links.clear()
study_push._loop = None
from euniv import study_control
study_control._snaps.clear()
study_control._snap_marks.clear()
autostudy_mod.forget_courses()
with encrypt_mod._lock:
encrypt_mod._config.clear()
encrypt_mod._config.update(
+49
View File
@@ -885,6 +885,55 @@ def test_start_saves_the_settings_sent_with_it(monkeypatch) -> None:
assert work_running("6650000146") is False
def test_study_state_is_served_from_memory_until_the_account_changes(monkeypatch) -> None:
import euniv.api as api_module
import euniv.service as service_module
import euniv.study_control as control
monkeypatch.setattr(
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
),
)
client = TestClient(api_module.app)
assert client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}).status_code == 200
loads: list[str] = []
original = control.load_state
def counted(employee_id: str) -> dict:
loads.append(employee_id)
return original(employee_id)
monkeypatch.setattr(control, "load_state", counted)
control.forget("6650000146")
first = control.state_for("6650000146")
assert loads == ["6650000146"]
assert first["monthly_target"] == 600
for _ in range(5):
assert control.state_for("6650000146") == first
assert loads == ["6650000146"]
held = control._snaps["6650000146"][1]
for secret in ("password_cipher", "credential_cipher", "proxy_password_cipher"):
assert not hasattr(held, secret)
with SessionLocal() as db:
account = db.get(Account, "6650000146")
assert account is not None
account.monthly_target = 100
db.flush()
db.rollback()
assert control.state_for("6650000146")["monthly_target"] == 600
assert loads == ["6650000146"]
saved = client.put("/api/settings/study", json=_study_body(monthly_target=900))
assert saved.status_code == 200
changed = control.state_for("6650000146")
assert changed["monthly_target"] == 900
assert loads == ["6650000146", "6650000146"]
assert client.get("/api/settings/study-control").json()["monthly_target"] == 900
assert loads == ["6650000146", "6650000146"]
def test_changing_the_course_count_restarts_a_running_study(monkeypatch) -> None:
import euniv.api as api_module
import euniv.autostudy as autostudy_module
+75
View File
@@ -106,6 +106,38 @@ def test_socks4_uses_socks_transport_instead_of_httpx_proxy() -> None:
assert "proxy" not in async_args
def test_clients_share_one_tls_setup(monkeypatch) -> None:
import ssl
from httpx_socks import AsyncProxyTransport, SyncProxyTransport
from euniv.proxy import async_httpx_client, shared_tls
context = shared_tls()
assert shared_tls() is context
assert isinstance(context, ssl.SSLContext)
assert context.verify_mode == ssl.CERT_REQUIRED
assert context.check_hostname is True
seen: list[dict] = []
class Capture:
def __init__(self, **kwargs) -> None:
seen.append(kwargs)
monkeypatch.setattr(httpx, "Client", Capture)
monkeypatch.setattr(httpx, "AsyncClient", Capture)
sync_httpx_client()
sync_httpx_client("http://127.0.0.1:8080")
async_httpx_client()
assert [kwargs["verify"] is context for kwargs in seen] == [True, True, True]
socks: list[object] = []
monkeypatch.setattr(SyncProxyTransport, "from_url", classmethod(lambda cls, url, **kw: socks.append(kw.get("verify"))))
monkeypatch.setattr(AsyncProxyTransport, "from_url", classmethod(lambda cls, url, **kw: socks.append(kw.get("verify"))))
client_proxy_args("socks5://127.0.0.1:1080")
client_proxy_args("socks5://127.0.0.1:1080", asynchronous=True)
assert socks == [context, context]
def test_parse_minutes() -> None:
assert _parse_minutes("") == 0
assert _parse_minutes("600") == 600
@@ -1416,3 +1448,46 @@ def test_saved_interval_is_kept_in_memory_for_running_courses() -> None:
assert _course_plan("video", intervals, auto, {"submitProTimes": 30})[:2] == (0, 30)
assert _course_plan("document", intervals, auto, {"validtimeSpan": 120, "submitIsOpen": "1"})[:2] == (4, 120)
assert _course_plan("document", intervals, True, {"submitProTimes": 30, "submitIsOpen": "1"})[:2] == (30, 30)
def test_course_list_is_shared_in_memory_until_the_table_changes() -> None:
from euniv.autostudy import shared_courses
from euniv.db import SessionLocal
from euniv.models import Course
with SessionLocal() as db:
db.add(Course(path="/kng/view/video/a.html", title="甲", kind="视频"))
db.commit()
with SessionLocal() as db:
first = shared_courses(db)
second = shared_courses(db)
assert first is second
assert [title for _path, title, _kind in first] == ["甲"]
with SessionLocal() as db:
db.add(Course(path="/kng/view/document/b.html", title="乙", kind="文档"))
db.flush()
db.rollback()
with SessionLocal() as db:
assert shared_courses(db) is first
db.add(Course(path="/kng/view/document/b.html", title="乙", kind="文档"))
db.commit()
with SessionLocal() as db:
third = shared_courses(db)
assert third is not first
assert [title for _path, title, _kind in third] == ["甲", "乙"]
def test_progress_updates_do_not_call_into_the_page_connections(monkeypatch) -> None:
from euniv.autostudy import WorkerView, halt_work
seen: list[tuple[str | None, bool]] = []
monkeypatch.setattr("euniv.study_push.notify", lambda eid=None, urgent=False: seen.append((eid, urgent)))
_clear_user_status("u-quiet")
view = WorkerView("u-quiet", 1)
view.update(course="甲", knowledge_id="k-quiet", progress=1)
view.adopt({"studyschedule": 5, "actualstudyhours": 1, "standardstudyhours": 20}, ok=True)
_set_user_status("u-quiet", state="学习中")
assert seen == []
halt_work("u-quiet")
assert seen == [("u-quiet", True)]
_clear_user_status("u-quiet")
+117 -45
View File
@@ -1,92 +1,164 @@
import asyncio
from starlette.websockets import WebSocketState
import euniv.study_push as study_push
class _Socket:
client_state = WebSocketState.CONNECTED
def __init__(self) -> None:
self.payloads: list[dict] = []
self.closed: list[int] = []
async def send_json(self, payload: dict) -> None:
self.payloads.append(payload)
async def close(self, code: int = 1000) -> None:
self.closed.append(code)
async def _until(done) -> None:
async def _until(done, seconds: float = 2.0) -> None:
loop = asyncio.get_running_loop()
deadline = loop.time() + 1
deadline = loop.time() + seconds
while not done():
if loop.time() >= deadline:
raise AssertionError("等待条件没有达成")
await asyncio.sleep(0)
await asyncio.sleep(0.01)
def test_study_push_throttles_and_only_sends_latest(monkeypatch) -> None:
socket = _Socket()
monkeypatch.setattr("euniv.study_control.payload_for", lambda eid: {"eid": eid, "n": len(socket.payloads)})
def test_connection_reads_memory_every_tick_and_only_sends_changes(monkeypatch) -> None:
state = {"n": 0}
reads: list[str] = []
def quick(employee_id: str) -> dict:
reads.append(employee_id)
return {"eid": employee_id, "n": state["n"]}
monkeypatch.setattr("euniv.study_control.quick_state", quick)
monkeypatch.setattr(study_push, "_TICK_SECONDS", 0.02)
monkeypatch.setattr(study_push, "_KEEPALIVE_SECONDS", 60.0)
async def main() -> None:
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.attach_loop(asyncio.get_running_loop())
study_push.register("u1", socket)
socket = _Socket()
link = study_push.register("u1", socket)
sender = asyncio.create_task(study_push.pump("u1", link))
try:
await _until(lambda: len(socket.payloads) == 1)
await _until(lambda: len(reads) >= 4)
assert len(socket.payloads) == 1
state["n"] = 7
await _until(lambda: len(socket.payloads) == 2)
assert socket.payloads[-1]["n"] == 7
assert socket.payloads[-1]["seq"] > socket.payloads[0]["seq"]
assert socket.payloads[-1]["boot"] == socket.payloads[0]["boot"]
finally:
sender.cancel()
await asyncio.gather(sender, return_exceptions=True)
study_push.unregister("u1", link)
assert study_push.connections() == 0
asyncio.run(main())
def test_urgent_notice_sends_at_once_and_plain_notice_does_nothing(monkeypatch) -> None:
monkeypatch.setattr("euniv.study_control.quick_state", lambda employee_id: {"eid": employee_id})
monkeypatch.setattr(study_push, "_TICK_SECONDS", 30.0)
monkeypatch.setattr(study_push, "_KEEPALIVE_SECONDS", 60.0)
async def main() -> None:
study_push.attach_loop(asyncio.get_running_loop())
socket = _Socket()
link = study_push.register("u1", socket)
sender = asyncio.create_task(study_push.pump("u1", link))
try:
study_push.notify("u1")
await _until(lambda: len(socket.payloads) == 1)
study_push.notify("u1")
await _until(lambda: "u1" in study_push._pending or len(socket.payloads) > 1)
await asyncio.sleep(0.1)
assert len(socket.payloads) == 1
assert "u1" in study_push._pending
study_push.notify("u1", urgent=True)
await _until(lambda: len(socket.payloads) == 2)
assert socket.payloads[-1]["eid"] == "u1"
study_push.notify("someone-else", urgent=True)
await asyncio.sleep(0.1)
assert len(socket.payloads) == 2
finally:
for handle in list(study_push._pending.values()):
handle.cancel()
study_push.unregister("u1", socket)
sender.cancel()
await asyncio.gather(sender, return_exceptions=True)
study_push.unregister("u1", link)
asyncio.run(main())
def test_unchanged_state_still_sends_a_keepalive(monkeypatch) -> None:
monkeypatch.setattr("euniv.study_control.quick_state", lambda employee_id: {"eid": employee_id})
monkeypatch.setattr(study_push, "_TICK_SECONDS", 0.02)
monkeypatch.setattr(study_push, "_KEEPALIVE_SECONDS", 0.1)
async def main() -> None:
study_push.attach_loop(asyncio.get_running_loop())
socket = _Socket()
link = study_push.register("u1", socket)
sender = asyncio.create_task(study_push.pump("u1", link))
try:
await _until(lambda: len(socket.payloads) >= 3)
finally:
sender.cancel()
await asyncio.gather(sender, return_exceptions=True)
study_push.unregister("u1", link)
asyncio.run(main())
def test_failed_send_closes_the_connection(monkeypatch) -> None:
monkeypatch.setattr("euniv.study_control.quick_state", lambda employee_id: {"eid": employee_id})
class Broken(_Socket):
async def send_json(self, payload: dict) -> None:
raise RuntimeError("连接已断开")
async def main() -> None:
study_push.attach_loop(asyncio.get_running_loop())
socket = Broken()
link = study_push.register("u1", socket)
await asyncio.wait_for(study_push.pump("u1", link), timeout=2)
assert socket.closed == [1011]
study_push.unregister("u1", link)
asyncio.run(main())
def test_state_falls_back_to_the_database_when_memory_has_nothing(monkeypatch) -> None:
loaded: list[str] = []
def load(employee_id: str) -> dict:
loaded.append(employee_id)
return {"eid": employee_id, "from": "db"}
monkeypatch.setattr("euniv.study_control.quick_state", lambda _employee_id: None)
monkeypatch.setattr("euniv.study_control.load_state", load)
async def main() -> None:
assert await study_push._current_state("u9") == {"eid": "u9", "from": "db"}
assert loaded == ["u9"]
asyncio.run(main())
def test_close_account_drops_open_socket() -> None:
closed: list[int] = []
class Socket(_Socket):
async def close(self, code: int = 1000) -> None:
closed.append(code)
socket = Socket()
async def main() -> None:
study_push._clients.clear()
study_push.attach_loop(asyncio.get_running_loop())
socket = _Socket()
study_push.register("gone", socket)
study_push.close_account("gone")
await _until(lambda: closed == [4401])
assert "gone" not in study_push._clients
await _until(lambda: socket.closed == [4401])
assert study_push.connections() == 0
asyncio.run(main())
def test_notify_without_a_socket_does_not_schedule_a_flush() -> None:
def test_notify_without_a_socket_does_nothing() -> None:
async def main() -> None:
study_push._pending.clear()
study_push._inflight.clear()
study_push._dirty.clear()
study_push._urgent.clear()
study_push._clients.clear()
study_push.attach_loop(asyncio.get_running_loop())
study_push.notify("nobody")
study_push.notify("nobody", urgent=True)
await asyncio.sleep(0)
assert study_push._pending == {}
assert study_push._inflight == set()
assert "nobody" not in study_push._dirty
assert study_push.connections() == 0
asyncio.run(main())