171 lines
4.9 KiB
Python
171 lines
4.9 KiB
Python
"""把自动学习状态推到首页 WebSocket。https 页面自动走 wss。
|
|
|
|
心跳等高频更新最多每 1 秒发一帧,只发当前最新快照。
|
|
开始/停止等控制变化立刻推。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import logging
|
|
from collections import defaultdict
|
|
|
|
from fastapi import WebSocket
|
|
from starlette.websockets import WebSocketState
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
_PUSH_SECONDS = 1.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] = {}
|
|
|
|
|
|
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()
|
|
_loop = loop
|
|
|
|
|
|
def register(employee_id: str, ws: WebSocket) -> None:
|
|
key = (employee_id or "").strip()
|
|
if not key:
|
|
return
|
|
_clients[key].add(ws)
|
|
|
|
|
|
def unregister(employee_id: str, ws: WebSocket) -> None:
|
|
key = (employee_id or "").strip()
|
|
group = _clients.get(key)
|
|
if not group:
|
|
return
|
|
group.discard(ws)
|
|
if not group:
|
|
_clients.pop(key, None)
|
|
_last_flush.pop(key, None)
|
|
|
|
|
|
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():
|
|
_drop_account(key)
|
|
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:
|
|
try:
|
|
asyncio.get_running_loop().create_task(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)
|
|
|
|
|
|
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
|
|
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:
|
|
try:
|
|
if ws.client_state != WebSocketState.CONNECTED:
|
|
dead.append(ws)
|
|
continue
|
|
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:
|
|
delay = 0.0 if employee_id in _urgent else _PUSH_SECONDS
|
|
_arm(employee_id, delay)
|