# -*- coding: utf-8 -*- """客户端通知:HTTP 拉取(兜底)+ WebSocket 实时推送(管理端下发即推,秒达)。""" from __future__ import annotations import asyncio from fastapi import APIRouter, Header, HTTPException, Query, WebSocket, WebSocketDisconnect from controlplane import config from controlplane.core.auth import _check_token, _cloud_account from controlplane.core.db import _db router = APIRouter(tags=["notifications"]) # WebSocket 连接注册表:account -> set[WebSocket] # 说明:控制面单 worker 部署时进程内共享,管理端创建/停用通知时据此即时推送在线客户端; # 即使推送失败/客户端离线,客户端 60s 轮询兜底保证最终送达。 _WS_CLIENTS: dict[str, set] = {} @router.get("/api/notifications") def notifications(account: str = Query(default=""), x_api_token: str = Header(default="", alias="X-API-Token"), authorization: str = Header(default="", alias="Authorization")) -> dict: """客户端拉取通知:优先云会话 token 解工号;兜底 account + X-API-Token。 返回 target=all 与 target=该账号 的启用且未过期通知(按创建时间倒序)。""" acct = _cloud_account(authorization) if not acct: _check_token(x_api_token) acct = (account or "").strip() if not acct: raise HTTPException(400, "缺少有效会话或 account") with _db() as conn: rows = conn.execute( """ SELECT id, title, content, level, target, account, created_at, expires_at FROM notifications WHERE active = 1 AND (target = 'all' OR (target = 'account' AND account = %s)) AND (expires_at IS NULL OR expires_at > NOW()) ORDER BY created_at DESC LIMIT 50 """, (acct,), ).fetchall() return {"notifications": [dict(r) for r in rows]} @router.websocket("/ws/notifications") async def ws_notifications(websocket: WebSocket, account: str = Query(default="")): """客户端长连接:管理端下发通知时即时推送(秒达)。鉴权用 X-API-Token 请求头。""" token = (websocket.headers.get("x-api-token") or "").strip() if config.CONTROLPLANE_TOKEN and token != config.CONTROLPLANE_TOKEN: await websocket.close(code=4401) return acct = (account or "").strip() if not acct: await websocket.close(code=4400) return await websocket.accept() _WS_CLIENTS.setdefault(acct, set()).add(websocket) try: await websocket.send_json({"type": "hello", "account": acct}) # 保持连接:接收客户端心跳/占位帧;断开(含网络异常)自动清理 while True: await websocket.receive_text() except WebSocketDisconnect: pass except Exception: # noqa: BLE001 pass finally: ws_set = _WS_CLIENTS.get(acct) if ws_set: ws_set.discard(websocket) if not ws_set: _WS_CLIENTS.pop(acct, None) async def _send_ws(ws_set: set, payload: dict) -> None: for ws in list(ws_set): try: await ws.send_json(payload) except Exception: # noqa: BLE001 ws_set.discard(ws) async def push_all(payload: dict) -> int: """推送给全部在线客户端,返回目标连接数。""" n = 0 for ws_set in _WS_CLIENTS.values(): n += len(ws_set) await _send_ws(ws_set, payload) return n async def push_account(account: str, payload: dict) -> int: """推送给指定账号的在线客户端,返回目标连接数。""" ws_set = _WS_CLIENTS.get(account) if not ws_set: return 0 await _send_ws(ws_set, payload) return len(ws_set)