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