feat: 学习状态改为内存快照,页面连接每秒自取并自动重连
This commit is contained in:
+9
-16
@@ -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
@@ -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
|
||||
|
||||
@@ -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
@@ -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
@@ -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
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user