154 lines
4.5 KiB
Python
154 lines
4.5 KiB
Python
"""首页学习状态连接。https 页面自动走 wss。
|
|
|
|
每条连接自己每秒从内存取一次当前状态,有变化才发;状态没变时每 5 秒发一帧,让页面知道连接还通。
|
|
开始、停止这类变化会立刻叫醒这个账号的连接。学习线程只改内存,不用为每一拍去通知页面。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import logging
|
|
from collections import defaultdict
|
|
|
|
from fastapi import WebSocket
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
_TICK_SECONDS = 1.0
|
|
_KEEPALIVE_SECONDS = 5.0
|
|
_SEND_TIMEOUT = 5.0
|
|
|
|
_loop: asyncio.AbstractEventLoop | None = None
|
|
_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
|
|
_links.clear()
|
|
_loop = loop
|
|
|
|
|
|
def register(employee_id: str, ws: WebSocket) -> Link:
|
|
link = Link(ws)
|
|
key = (employee_id or "").strip()
|
|
if key:
|
|
_links[key].add(link)
|
|
return link
|
|
|
|
|
|
def unregister(employee_id: str, link: Link) -> None:
|
|
key = (employee_id or "").strip()
|
|
group = _links.get(key)
|
|
if not group:
|
|
return
|
|
group.discard(link)
|
|
if not group:
|
|
_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:
|
|
"""注销或删除后关掉这个账号已经打开的学习状态连接。"""
|
|
key = (employee_id or "").strip()
|
|
if not key:
|
|
return
|
|
loop = _loop
|
|
if loop is None or not loop.is_running():
|
|
_links.pop(key, None)
|
|
return
|
|
loop.call_soon_threadsafe(_drop_account, key)
|
|
|
|
|
|
def _drop_account(key: str) -> None:
|
|
for link in list(_links.pop(key, ())):
|
|
try:
|
|
asyncio.get_running_loop().create_task(link.ws.close(code=4401))
|
|
except RuntimeError:
|
|
pass
|
|
|
|
|
|
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
|
|
|
|
|
|
async def pump(employee_id: str, link: Link) -> None:
|
|
"""一直给这条连接发状态,直到发不出去或任务被取消。
|
|
|
|
某一次状态没取到只记一条日志,下一秒再取,不因此断开连接。
|
|
"""
|
|
from euniv.study_control import stamp_frame
|
|
|
|
loop = asyncio.get_running_loop()
|
|
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:
|
|
await asyncio.wait_for(link.ws.send_json(stamp_frame(employee_id, payload)), timeout=_SEND_TIMEOUT)
|
|
except Exception:
|
|
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
|