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
+9 -16
View File
@@ -537,17 +537,9 @@ def put_proxy(body: ProxyBody, request: Request, db: Session = Depends(get_db))
@app.get("/api/settings/study-control")
def get_study_control(request: Request, db: Session = Depends(get_db)) -> dict:
from euniv.autostudy import account_status
from euniv.study_control import assemble, settle, stamp_frame
from euniv.study_control import payload_for
employee_id = _signed_in(request, db)
account = db.get(Account, employee_id)
if account is None:
raise HTTPException(status_code=401, detail="未登录")
live = account_status(employee_id)
if settle(account, live):
db.commit()
return stamp_frame(employee_id, assemble(account, live))
return payload_for(_signed_in(request, db))
@app.post("/api/settings/study-control")
@@ -623,8 +615,7 @@ def _ws_gate(cookies: dict) -> tuple[int, str]:
@app.websocket("/api/settings/study-control/ws")
async def study_control_ws(websocket: WebSocket):
from euniv.study_control import payload_for
from euniv.study_push import register, unregister
from euniv.study_push import pump, register, unregister
if not _same_origin(websocket):
await websocket.close(code=4403)
@@ -634,10 +625,10 @@ async def study_control_ws(websocket: WebSocket):
if code:
await websocket.close(code=code)
return
register(employee_id, websocket)
link = register(employee_id, websocket)
sender = asyncio.create_task(pump(employee_id, link))
last_message = 0.0
try:
await websocket.send_json(await asyncio.to_thread(payload_for, employee_id))
while True:
message = await websocket.receive()
if message.get("type") == "websocket.disconnect":
@@ -648,11 +639,13 @@ async def study_control_ws(websocket: WebSocket):
if now - last_message < 1:
continue
last_message = now
await websocket.send_json(await asyncio.to_thread(payload_for, employee_id))
link.wake.set()
except WebSocketDisconnect:
pass
finally:
unregister(employee_id, websocket)
unregister(employee_id, link)
sender.cancel()
await asyncio.gather(sender, return_exceptions=True)
@app.get("/api/home/history")
+60 -18
View File
@@ -21,6 +21,7 @@ import re
import threading
import time
from collections.abc import Callable
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timezone
import httpx
@@ -110,11 +111,15 @@ def account_status(employee_id: str) -> dict:
return info
def _notify(employee_id: str = "", urgent: bool = False) -> None:
def _wake_pages(employee_id: str) -> None:
"""开始、停止这类变化立刻叫醒这个账号打开的页面。
学习进度只写在内存里,页面连接每秒自己取一次,不用每一拍都通知。
"""
try:
from euniv.study_push import notify
notify(employee_id or None, urgent=urgent)
notify(employee_id or None, urgent=True)
except Exception:
return
@@ -123,7 +128,6 @@ def _set_status(**kw: object) -> None:
with _lock:
_status.update(kw)
_status["updated_at"] = datetime.now(timezone.utc).isoformat()
_notify()
def _set_user_status(employee_id: str, **kw: object) -> None:
@@ -137,13 +141,11 @@ def _set_user_status(employee_id: str, **kw: object) -> None:
info.pop("hours_refresh_at", None)
info["month"] = str(kw["month"]) if "month" in kw else month_key()
_status["updated_at"] = datetime.now(timezone.utc).isoformat()
_notify(employee_id)
def _clear_user_status(employee_id: str) -> None:
with _lock:
_status.get("users", {}).pop(employee_id, None)
_notify(employee_id)
def _drop_live_hours(employee_id: str) -> None:
@@ -184,7 +186,6 @@ def _set_worker_status(employee_id: str, worker_id: int, **kw: object) -> None:
if isinstance(course, str) and course:
info["course"] = course
_status["updated_at"] = datetime.now(timezone.utc).isoformat()
_notify(employee_id)
class WorkerView:
@@ -476,7 +477,7 @@ def halt_work(employee_id: str) -> None:
_running.discard(key)
event = _user_halts.get(key)
_signal_stop(event)
_notify(key, urgent=True)
_wake_pages(key)
def stop_account(employee_id: str) -> None:
@@ -541,7 +542,7 @@ def want_work(employee_id: str) -> None:
if key not in _wanted:
_wanted_seq += 1
_wanted[key] = _wanted_seq
_notify(key, urgent=True)
_wake_pages(key)
def drop_work(employee_id: str) -> None:
@@ -550,7 +551,7 @@ def drop_work(employee_id: str) -> None:
return
with _halt_lock:
_wanted.pop(key, None)
_notify(key, urgent=True)
_wake_pages(key)
def is_wanted(employee_id: str) -> bool:
@@ -601,6 +602,32 @@ def restart_work(employee_id: str) -> None:
_KIND_RANK = {"视频": 0, "文档": 1, "课程包": 2, "课程": 3}
_course_lock = threading.Lock()
_course_list: tuple[tuple[str, str, str], ...] | None = None
_course_mark = 0
def forget_courses() -> None:
"""课程表有写入后调用,下次启动学习时重新读库。"""
global _course_list, _course_mark
with _course_lock:
_course_list = None
_course_mark += 1
def shared_courses(db) -> tuple[tuple[str, str, str], ...]:
"""排好序的课程清单。所有账号共用内存里的同一份,课程表没变就不再读库。"""
global _course_list
with _course_lock:
held = _course_list
mark = _course_mark
if held is not None:
return held
fresh = tuple(snapshot_courses(db.scalars(select(Course)).all()))
with _course_lock:
if _course_mark == mark:
_course_list = fresh
return fresh
def snapshot_courses(rows) -> list[tuple[str, str, str]]:
@@ -1314,8 +1341,8 @@ def _halted(global_stop: asyncio.Event, hours: HoursWatcher) -> bool:
class CourseCursor:
"""多协程顺着同一份课程表往下领,每门课只被领取一次。"""
def __init__(self, courses: list) -> None:
self._courses = list(courses)
def __init__(self, courses) -> None:
self._courses = tuple(courses)
self._index = 0
self._lock = asyncio.Lock()
@@ -1742,6 +1769,21 @@ def _prepare_session(employee_id: str, password: str,
return "", "", "", [], current, last_reason
_PREPARE_WORKERS = 4
_prepare_executor: ThreadPoolExecutor | None = None
def _prepare_pool() -> ThreadPoolExecutor:
"""登录学习平台要等网络,单独用几条线程。
很多账号同时启动时,不会占满默认线程池,正在学的账号写库和取代理不用排在它们后面。
"""
global _prepare_executor
if _prepare_executor is None:
_prepare_executor = ThreadPoolExecutor(max_workers=_PREPARE_WORKERS, thread_name_prefix="euniv-prepare")
return _prepare_executor
# ── 启动器 + 按账号 Work ──
class AutoStudyWorker:
@@ -1826,14 +1868,14 @@ class AutoStudyWorker:
return True
return is_studying(employee_id)
def _collect(self) -> tuple[list, list, float, str]:
def _collect(self) -> tuple[list, tuple, float, str]:
from euniv.db import SessionLocal
from euniv.study_window import CN_TZ, month_key
now = as_cn()
soonest = next_month_start(now)
jobs: list[tuple] = []
course_list: list[tuple[str, str, str]] = []
course_list: tuple[tuple[str, str, str], ...] = ()
with SessionLocal() as db:
users = db.scalars(
select(Account)
@@ -1877,7 +1919,7 @@ class AutoStudyWorker:
except Exception:
log.exception("调度账号 %s 失败", getattr(row, "employee_id", ""))
if jobs:
course_list = snapshot_courses(db.scalars(select(Course)).all())
course_list = shared_courses(db)
if expired:
db.commit()
queried = {row.employee_id for row in users}
@@ -1901,7 +1943,7 @@ class AutoStudyWorker:
_set_status(running=False, message=idle)
return delay
def _launch(self, job: tuple, course_list: list[tuple[str, str, str]]) -> bool:
def _launch(self, job: tuple, course_list) -> bool:
eid = job[0]
if self._busy(eid):
return False
@@ -1915,11 +1957,11 @@ class AutoStudyWorker:
with _halt_lock:
generation = _wanted.get(eid, 0)
assert self._loop is not None
self._tasks[eid] = self._loop.create_task(self._run_account(job, list(course_list), generation))
self._tasks[eid] = self._loop.create_task(self._run_account(job, course_list, generation))
log.info("启动账号 %s 的学习任务", eid)
return True
async def _run_account(self, job: tuple, course_list: list[tuple[str, str, str]], generation: int) -> None:
async def _run_account(self, job: tuple, course_list, generation: int) -> None:
emp_id, target, pw, cred, proxy, workers, use_pool = job
try:
from admin.settings import hours_source_of
@@ -1987,7 +2029,7 @@ class AutoStudyWorker:
_set_user_status(employee_id, state="准备", course="", workers={})
loop = asyncio.get_running_loop()
token, user_id, org_id, cookies, proxy, reason = await loop.run_in_executor(
None, _prepare_session, employee_id, password, credential, proxy, use_pool)
_prepare_pool(), _prepare_session, employee_id, password, credential, proxy, use_pool)
if user_stop.is_set():
_set_user_status(employee_id, state="已停止")
return
+33
View File
@@ -28,6 +28,39 @@ def _enable_wal(dbapi_connection, _connection_record) -> None:
cursor.close()
@event.listens_for(SessionLocal, "after_flush")
def _note_cached_rows(session, _flush_context) -> None:
"""记下这次写了哪些账号、有没有动课程表。提交后让内存里的那份失效。"""
from euniv.models import Account, Course
for item in (*session.new, *session.dirty, *session.deleted):
if isinstance(item, Account):
session.info.setdefault("accounts_written", set()).add(str(item.employee_id))
elif isinstance(item, Course):
session.info["courses_written"] = True
@event.listens_for(SessionLocal, "after_commit")
def _drop_cached_rows(session) -> None:
accounts = session.info.pop("accounts_written", None)
courses = session.info.pop("courses_written", False)
if accounts:
from euniv.study_control import forget
for employee_id in accounts:
forget(employee_id)
if courses:
from euniv.autostudy import forget_courses
forget_courses()
@event.listens_for(SessionLocal, "after_rollback")
def _keep_cached_rows(session) -> None:
session.info.pop("accounts_written", None)
session.info.pop("courses_written", None)
def init_db() -> None:
from alembic import command
from alembic.config import Config
+23 -2
View File
@@ -5,10 +5,29 @@ from __future__ import annotations
import ipaddress
import re
import socket
import ssl
import threading
from urllib.parse import quote, urlparse
import httpx
_tls_lock = threading.Lock()
_tls_context: ssl.SSLContext | None = None
def shared_tls() -> ssl.SSLContext:
"""所有客户端共用一份证书校验配置。
每建一个客户端都重读一遍证书库,要多花十几毫秒和几百 KB 内存;账号多、代理探测频繁时很明显。
"""
global _tls_context
if _tls_context is None:
with _tls_lock:
if _tls_context is None:
_tls_context = httpx.create_ssl_context(trust_env=False)
return _tls_context
SCHEMES = ("http", "https", "socks4", "socks5")
SOCKS_SCHEMES = ("socks4", "socks5")
OFF_SCHEMES = ("", "off", "none", "direct", "close")
@@ -304,21 +323,23 @@ def client_proxy_args(proxy: str | None, *, asynchronous: bool = False) -> dict:
if asynchronous:
from httpx_socks import AsyncProxyTransport
return {"transport": AsyncProxyTransport.from_url(url)}
return {"transport": AsyncProxyTransport.from_url(url, verify=shared_tls())}
from httpx_socks import SyncProxyTransport
return {"transport": SyncProxyTransport.from_url(url)}
return {"transport": SyncProxyTransport.from_url(url, verify=shared_tls())}
return {"proxy": url}
def sync_httpx_client(proxy: str | None = None, **kwargs) -> httpx.Client:
kwargs.setdefault("trust_env", False)
kwargs.setdefault("verify", shared_tls())
kwargs.update(client_proxy_args(proxy))
return httpx.Client(**kwargs)
def async_httpx_client(proxy: str | None = None, **kwargs) -> httpx.AsyncClient:
kwargs.setdefault("trust_env", False)
kwargs.setdefault("verify", shared_tls())
kwargs.update(client_proxy_args(proxy, asynchronous=True))
return httpx.AsyncClient(**kwargs)
+106 -15
View File
@@ -2,12 +2,14 @@
from __future__ import annotations
import copy
import math
import re
import secrets
import threading
import time
from datetime import datetime
from types import SimpleNamespace
from euniv.study_window import month_key, window_open
@@ -15,6 +17,64 @@ from euniv.study_window import month_key, window_open
_frame_lock = threading.Lock()
_frames: dict[str, int] = {}
_BOOT = secrets.token_hex(8)
_SECRET_COLUMNS = frozenset({"password_cipher", "credential_cipher", "proxy_password_cipher"})
_SNAP_SECONDS = 30.0
_snap_lock = threading.Lock()
_snaps: dict[str, tuple[float, SimpleNamespace]] = {}
_snap_marks: dict[str, int] = {}
_EMPTY = {
"started": False,
"paused": True,
"hours_met": False,
"schedule_enabled": True,
"workers": [],
"active": False,
"message": "",
}
def remember(account, mark: int | None = None) -> SimpleNamespace:
"""把首页学习状态要用的账号字段抄到内存,不含任何密文。账号一有写入就会失效。
mark 是读库之前取的写入记号。读库期间这个账号又被写过,就不把这份旧值留在内存里。
"""
from euniv.models import Account
fields = {
column.key: getattr(account, column.key, None)
for column in Account.__table__.columns
if column.key not in _SECRET_COLUMNS
}
snap = SimpleNamespace(**fields)
key = str(fields.get("employee_id") or "").strip()
if key:
with _snap_lock:
if mark is None or _snap_marks.get(key, 0) == mark:
_snaps[key] = (time.monotonic() + _SNAP_SECONDS, snap)
return snap
def forget(employee_id: str) -> None:
key = (employee_id or "").strip()
with _snap_lock:
_snaps.pop(key, None)
_snap_marks[key] = _snap_marks.get(key, 0) + 1
def _write_mark(employee_id: str) -> int:
with _snap_lock:
return _snap_marks.get(employee_id, 0)
def _remembered(employee_id: str) -> SimpleNamespace | None:
with _snap_lock:
held = _snaps.get(employee_id)
if held is None:
return None
if held[0] < time.monotonic():
_snaps.pop(employee_id, None)
return None
return held[1]
def stamp_frame(employee_id: str, payload: dict) -> dict:
@@ -185,38 +245,69 @@ def assemble(account, live: dict | None = None, now: datetime | None = None) ->
return payload
def _release_due(account, payload: dict) -> bool:
return bool(payload["hours_met"]) and ignores_window(account) and not payload["active"]
def settle(account, live: dict | None = None, now: datetime | None = None) -> bool:
"""跨月恢复定时;达标且当前没在学时,收回立即开始标记。"""
changed = expire_pause(account, now)
payload = assemble(account, live, now)
if payload["hours_met"] and ignores_window(account) and not payload["active"]:
if _release_due(account, assemble(account, live, now)):
account.study_ignore_window = False
changed = True
return changed
def payload_for(employee_id: str) -> dict:
def quick_state(employee_id: str) -> dict | None:
"""只用内存拼出首页学习状态,不读库。
内存里没有这个账号,或者有状态要写回库(跨月、达标后收回立即开始),返回 None,
调用方改用 load_state。
"""
from euniv.autostudy import account_status
key = (employee_id or "").strip()
held = _remembered(key) if key else None
if held is None:
return None
live = account_status(key)
probe = copy.copy(held)
changed = expire_pause(probe)
payload = assemble(probe, live)
if changed or _release_due(probe, payload):
return None
return payload
def load_state(employee_id: str) -> dict:
"""读库拼出首页学习状态,把该写回的写回,并把账号字段记到内存供之后直接用。"""
from euniv.autostudy import account_status
from euniv.db import SessionLocal
from euniv.models import Account
key = (employee_id or "").strip()
empty = {
"started": False,
"paused": True,
"hours_met": False,
"schedule_enabled": True,
"workers": [],
"active": False,
"message": "",
}
if not key:
return empty
return dict(_EMPTY)
with SessionLocal() as db:
mark = _write_mark(key)
account = db.get(Account, key)
if account is None:
return empty
forget(key)
return dict(_EMPTY)
live = account_status(key)
if settle(account, live):
db.commit()
return stamp_frame(key, assemble(account, live))
mark = _write_mark(key)
return assemble(remember(account, mark), live)
def state_for(employee_id: str) -> dict:
payload = quick_state(employee_id)
return payload if payload is not None else load_state(employee_id)
def payload_for(employee_id: str) -> dict:
key = (employee_id or "").strip()
if not key:
return dict(_EMPTY)
return stamp_frame(key, state_for(key))
+98 -115
View File
@@ -1,7 +1,7 @@
"""把自动学习状态推到首页 WebSocket。https 页面自动走 wss。
"""首页学习状态连接。https 页面自动走 wss。
心跳等高频更新最多每 1 秒发一帧,只发当前最新快照。
开始/停止等控制变化立刻推。
每条连接自己每秒从内存取一次当前状态,有变化才发;状态没变时每 5 秒发一帧,让页面知道连接还通。
开始、停止这类变化会立刻叫醒这个账号的连接。学习线程只改内存,不用为每一拍去通知页面。
"""
from __future__ import annotations
@@ -11,52 +11,75 @@ import logging
from collections import defaultdict
from fastapi import WebSocket
from starlette.websockets import WebSocketState
log = logging.getLogger(__name__)
_PUSH_SECONDS = 1.0
_TICK_SECONDS = 1.0
_KEEPALIVE_SECONDS = 5.0
_SEND_TIMEOUT = 5.0
_loop: asyncio.AbstractEventLoop | None = None
_clients: dict[str, set[WebSocket]] = defaultdict(set)
_pending: dict[str, asyncio.TimerHandle] = {}
_inflight: set[str] = set()
_dirty: set[str] = set()
_urgent: set[str] = set()
_last_flush: dict[str, float] = {}
_links: dict[str, set["Link"]] = defaultdict(set)
class Link:
"""一条页面连接。wake 被置位时立刻发一帧,不等下一秒。"""
__slots__ = ("ws", "wake")
def __init__(self, ws: WebSocket) -> None:
self.ws = ws
self.wake = asyncio.Event()
def attach_loop(loop: asyncio.AbstractEventLoop) -> None:
global _loop
if _loop is loop:
return
for handle in list(_pending.values()):
handle.cancel()
_pending.clear()
_inflight.clear()
_dirty.clear()
_urgent.clear()
_last_flush.clear()
_clients.clear()
_links.clear()
_loop = loop
def register(employee_id: str, ws: WebSocket) -> None:
def register(employee_id: str, ws: WebSocket) -> Link:
link = Link(ws)
key = (employee_id or "").strip()
if not key:
return
_clients[key].add(ws)
if key:
_links[key].add(link)
return link
def unregister(employee_id: str, ws: WebSocket) -> None:
def unregister(employee_id: str, link: Link) -> None:
key = (employee_id or "").strip()
group = _clients.get(key)
group = _links.get(key)
if not group:
return
group.discard(ws)
group.discard(link)
if not group:
_clients.pop(key, None)
_last_flush.pop(key, None)
_links.pop(key, None)
def connections() -> int:
return sum(len(group) for group in _links.values())
def notify(employee_id: str | None = None, urgent: bool = False) -> None:
"""开始、停止这类变化立刻叫醒连接。普通进度不用通知,连接每秒自己取。"""
if not urgent:
return
loop = _loop
if loop is None or not loop.is_running():
return
key = (employee_id or "").strip() if employee_id is not None else None
if key is not None and not _links.get(key):
return
loop.call_soon_threadsafe(_wake, key)
def _wake(employee_id: str | None) -> None:
groups = _links.values() if employee_id is None else (_links.get(employee_id) or (),)
for group in list(groups):
for link in list(group):
link.wake.set()
def close_account(employee_id: str) -> None:
@@ -66,105 +89,65 @@ def close_account(employee_id: str) -> None:
return
loop = _loop
if loop is None or not loop.is_running():
_drop_account(key)
_links.pop(key, None)
return
loop.call_soon_threadsafe(_drop_account, key)
def _drop_account(key: str) -> None:
handle = _pending.pop(key, None)
if handle is not None:
handle.cancel()
_dirty.discard(key)
_urgent.discard(key)
_inflight.discard(key)
_last_flush.pop(key, None)
sockets = list(_clients.pop(key, ()))
for ws in sockets:
for link in list(_links.pop(key, ())):
try:
asyncio.get_running_loop().create_task(ws.close(code=4401))
asyncio.get_running_loop().create_task(link.ws.close(code=4401))
except RuntimeError:
pass
def notify(employee_id: str | None = None, urgent: bool = False) -> None:
loop = _loop
if loop is None or not loop.is_running():
return
if employee_id is not None:
key = employee_id.strip()
if not key or not _clients.get(key):
return
loop.call_soon_threadsafe(_mark, key, urgent)
return
for key in list(_clients):
if key and _clients.get(key):
loop.call_soon_threadsafe(_mark, key, urgent)
async def _current_state(employee_id: str) -> dict:
from euniv.study_control import load_state, quick_state
payload = quick_state(employee_id)
if payload is None:
payload = await asyncio.to_thread(load_state, employee_id)
return payload
def _mark(employee_id: str, urgent: bool) -> None:
if not _clients.get(employee_id):
return
_dirty.add(employee_id)
if urgent:
_urgent.add(employee_id)
_arm(employee_id, 0.0)
return
if employee_id in _pending or employee_id in _inflight:
return
async def pump(employee_id: str, link: Link) -> None:
"""一直给这条连接发状态,直到发不出去或任务被取消。
某一次状态没取到只记一条日志,下一秒再取,不因此断开连接。
"""
from euniv.study_control import stamp_frame
loop = asyncio.get_running_loop()
wait = max(0.0, _PUSH_SECONDS - (loop.time() - _last_flush.get(employee_id, 0.0)))
_arm(employee_id, wait)
def _arm(employee_id: str, delay: float) -> None:
old = _pending.pop(employee_id, None)
if old is not None:
old.cancel()
loop = asyncio.get_running_loop()
if delay <= 0:
if employee_id in _inflight:
return
_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, armed: bool = False) -> None:
_pending.pop(employee_id, None)
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
payload = await asyncio.to_thread(payload_for, employee_id)
_last_flush[employee_id] = asyncio.get_running_loop().time()
dead: list[WebSocket] = []
for ws in sockets:
last: dict | None = None
sent_at = 0.0
failing = False
while True:
forced = link.wake.is_set()
link.wake.clear()
try:
payload = await _current_state(employee_id)
except Exception:
payload = None
if not failing:
failing = True
log.warning("账号 %s 的学习状态没有取到", employee_id, exc_info=True)
else:
failing = False
now = loop.time()
if payload is not None and (forced or payload != last or now - sent_at >= _KEEPALIVE_SECONDS):
try:
if ws.client_state != WebSocketState.CONNECTED:
dead.append(ws)
continue
await asyncio.wait_for(ws.send_json(payload), timeout=5)
await asyncio.wait_for(link.ws.send_json(stamp_frame(employee_id, payload)), timeout=_SEND_TIMEOUT)
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:
delay = 0.0 if employee_id in _urgent else _PUSH_SECONDS
_arm(employee_id, delay)
log.debug("学习状态连接已断开", exc_info=True)
try:
await link.ws.close(code=1011)
except Exception:
pass
return
last = payload
sent_at = now
try:
await asyncio.wait_for(link.wake.wait(), timeout=_TICK_SECONDS)
except asyncio.TimeoutError:
pass
+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())
+99 -37
View File
@@ -689,45 +689,92 @@ function startStudyFallback() {
type PingSocket = WebSocket & { ping?: number };
// 状态没变时服务器也会每 5 秒发一帧。超过 15 秒一帧都没有,说明连接其实已经断了。
const STUDY_STALE_MS = 15000;
const STUDY_CONNECT_MS = 8000;
const STUDY_RETRY_MAX_MS = 10000;
let studyFrameAt = 0;
let studyDialAt = 0;
let studyWatch = 0;
function clearSocketPing(ws: PingSocket) {
if (!ws.ping) return;
window.clearInterval(ws.ping);
ws.ping = 0;
}
function releaseStudySocket() {
const ws = studySocket;
studySocket = null;
if (!ws) return;
clearSocketPing(ws);
ws.onopen = null;
ws.onclose = null;
ws.onerror = null;
ws.onmessage = null;
try {
ws.close();
} catch { /* 已经关了 */ }
}
function stopStudySocket() {
studyClosed = true;
if (studyReconnect) {
window.clearTimeout(studyReconnect);
studyReconnect = 0;
}
stopStudyFallback();
const ws = studySocket;
studySocket = null;
if (ws) {
clearSocketPing(ws);
ws.onclose = null;
ws.onerror = null;
ws.onmessage = null;
ws.close();
if (studyWatch) {
window.clearInterval(studyWatch);
studyWatch = 0;
}
stopStudyFallback();
releaseStudySocket();
}
function scheduleStudyReconnect() {
if (studyClosed || studyReconnect) return;
const delay = studyBackoff;
studyBackoff = Math.min(10000, delay * 2);
const delay = Math.round(studyBackoff * (0.8 + Math.random() * 0.4));
studyBackoff = Math.min(STUDY_RETRY_MAX_MS, studyBackoff * 2);
studyReconnect = window.setTimeout(() => {
studyReconnect = 0;
connectStudySocket();
}, delay);
}
// 连接没了:先每 3 秒查一次顶着,同时按 1、2、4 秒直到 10 秒的间隔一直重连,连上为止。
function retryStudySocket() {
releaseStudySocket();
if (studyClosed) return;
startStudyFallback();
scheduleStudyReconnect();
}
function watchStudySocket() {
if (studyClosed) return;
const ws = studySocket;
if (!ws) {
scheduleStudyReconnect();
return;
}
const now = Date.now();
if (ws.readyState === WebSocket.CONNECTING) {
if (now - studyDialAt > STUDY_CONNECT_MS) retryStudySocket();
return;
}
if (ws.readyState === WebSocket.OPEN) {
if (now - studyFrameAt > STUDY_STALE_MS) retryStudySocket();
return;
}
retryStudySocket();
}
function connectStudySocket() {
if (studyClosed) return;
if (!studyWatch) studyWatch = window.setInterval(watchStudySocket, 3000);
if (studySocket && (studySocket.readyState === WebSocket.OPEN || studySocket.readyState === WebSocket.CONNECTING)) {
return;
}
releaseStudySocket();
let ws: WebSocket;
try {
ws = new WebSocket(studySocketUrl());
@@ -738,41 +785,37 @@ function connectStudySocket() {
}
const socket = ws as PingSocket;
studySocket = socket;
let welcomed = false;
studyDialAt = Date.now();
studyFrameAt = studyDialAt;
socket.onmessage = (event) => {
if (!welcomed) {
welcomed = true;
studyBackoff = 1000;
}
studyFrameAt = Date.now();
studyBackoff = 1000;
try {
const data = JSON.parse(String(event.data));
if (data && typeof data === "object") applyStudyControl(data as Record<string, unknown>);
} catch { /* ignore */ }
};
socket.onopen = () => {
studyFrameAt = Date.now();
stopStudyFallback();
void loadStudyControl();
clearSocketPing(socket);
socket.ping = window.setInterval(() => {
if (socket.readyState === WebSocket.OPEN) socket.send("ping");
if (socket.readyState !== WebSocket.OPEN) return;
try {
socket.send("ping");
} catch { /* 下一轮检查会重连 */ }
}, 8000);
};
socket.onclose = (event) => {
clearSocketPing(socket);
if (studySocket !== socket) return;
studySocket = null;
if (event.code === 4401 || event.code === 4403) {
studyClosed = true;
stopStudyFallback();
stopStudySocket();
return;
}
if (!studyClosed) {
startStudyFallback();
scheduleStudyReconnect();
}
retryStudySocket();
};
socket.onerror = () => {
socket.close();
if (studySocket === socket) retryStudySocket();
};
}
@@ -797,21 +840,40 @@ watch(proxyOpen, (open, wasOpen) => {
let lastWake = 0;
function reconnectStudyNow() {
if (studyClosed) return;
if (studyReconnect) {
window.clearTimeout(studyReconnect);
studyReconnect = 0;
}
studyBackoff = 1000;
releaseStudySocket();
void loadStudyControl();
connectStudySocket();
}
// 回到页面时:连接还在就要一帧最新的,不在就不等重连间隔,马上连。
function studyWake() {
const now = Date.now();
if (now - lastWake < 800) return;
lastWake = now;
if (studyClosed) return;
void loadStudyControl();
if (!studySocket || studySocket.readyState === WebSocket.CLOSING || studySocket.readyState === WebSocket.CLOSED) {
connectStudySocket();
const ws = studySocket;
if (ws && ws.readyState === WebSocket.OPEN) {
try {
ws.send("ping");
return;
} catch { /* 发不出去,按断开处理 */ }
} else if (ws && ws.readyState === WebSocket.CONNECTING) {
return;
}
if (studySocket.readyState === WebSocket.OPEN) {
try {
studySocket.send("ping");
} catch { /* ignore */ }
}
reconnectStudyNow();
}
// 网络从断开恢复后,原来的连接多半已经失效,直接换一条新的。
function studyOnline() {
lastWake = Date.now();
reconnectStudyNow();
}
function onStudyVisible() {
@@ -859,14 +921,14 @@ onMounted(() => {
connectStudySocket();
document.addEventListener("visibilitychange", onStudyVisible);
window.addEventListener("focus", studyWake);
window.addEventListener("online", studyWake);
window.addEventListener("online", studyOnline);
window.addEventListener("pageshow", studyWake);
});
onUnmounted(() => {
document.removeEventListener("visibilitychange", onStudyVisible);
window.removeEventListener("focus", studyWake);
window.removeEventListener("online", studyWake);
window.removeEventListener("online", studyOnline);
window.removeEventListener("pageshow", studyWake);
stopStudySocket();
stopStudyTick();