refactor: 重构为可部署到服务器的模块化结构(v5.0.0)
- 拆包 fengxiang/:config/client/store/notify/monitor/admin/tts,统一入口 order_monitor.py - 服务器形态:Docker 常驻,Cookie 由本机登录后 POST 上传并热加载,不再依赖桌面弹窗 - 修复:首次启动重推历史订单、speak() 阻塞主循环、夜间 sleep 10h 不可中断 - 修复:test_push.py 残留 miservice 依赖(小爱已移除)、run_monitor.bat 写死盘符 - 配置化:webhook/shopId 移出源码(环境变量 > config.yaml > 默认值) - 可观测:滚动文件日志 + /healthz + Docker HEALTHCHECK + 告警冷却 - 飞书通道保留配置位,默认关闭(原 token 已失效 code=19001) - 新增 22 项单元测试(不联网)
This commit is contained in:
1 parent
ab6a2bb7ea
commit
4ee30399bf
30 files changed
+2410
-825
No files matched your search
@@ -0,0 +1,103 @@
|
||||
"""通知通道。
|
||||
|
||||
设计要点:
|
||||
- 通道可插拔(企业微信 / 飞书),单个通道失败不影响其他通道,也不影响主循环
|
||||
- 告警(Cookie 失效、登录提示)带冷却,避免每 5 秒往群里刷一条
|
||||
- 所有 webhook 从配置读取,源码里不再出现密钥
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import time
|
||||
from typing import Dict, List, Protocol, Tuple
|
||||
|
||||
import requests
|
||||
|
||||
from .config import Config
|
||||
|
||||
log = logging.getLogger("fengxiang.notify")
|
||||
|
||||
|
||||
class Channel(Protocol):
|
||||
name: str
|
||||
|
||||
def send(self, text: str) -> None: # pragma: no cover - 协议声明
|
||||
...
|
||||
|
||||
|
||||
class WecomChannel:
|
||||
name = "wecom"
|
||||
|
||||
def __init__(self, webhook: str, timeout: int = 10):
|
||||
self.webhook = webhook
|
||||
self.timeout = timeout
|
||||
|
||||
def send(self, text: str) -> None:
|
||||
payload = {"msgtype": "text", "text": {"content": text}}
|
||||
resp = requests.post(self.webhook, json=payload, timeout=self.timeout)
|
||||
data = resp.json()
|
||||
if data.get("errcode") != 0:
|
||||
raise RuntimeError(f"企业微信返回错误: {data}")
|
||||
|
||||
|
||||
class FeishuChannel:
|
||||
name = "feishu"
|
||||
|
||||
def __init__(self, webhook: str, timeout: int = 10):
|
||||
self.webhook = webhook
|
||||
self.timeout = timeout
|
||||
|
||||
def send(self, text: str) -> None:
|
||||
payload = {"msg_type": "text", "content": {"text": text}}
|
||||
resp = requests.post(self.webhook, json=payload, timeout=self.timeout)
|
||||
data = resp.json()
|
||||
# 飞书新老版本返回结构不同,统一取出成功标志
|
||||
code = data.get("code", data.get("StatusCode"))
|
||||
if code != 0:
|
||||
raise RuntimeError(f"飞书返回错误: {data}")
|
||||
|
||||
|
||||
def build_channels(cfg: Config) -> List[Channel]:
|
||||
channels: List[Channel] = []
|
||||
for name in cfg.notify.channels:
|
||||
if name == "wecom" and cfg.notify.wecom_webhook:
|
||||
channels.append(WecomChannel(cfg.notify.wecom_webhook))
|
||||
elif name == "feishu" and cfg.notify.feishu_enabled and cfg.notify.feishu_webhook:
|
||||
channels.append(FeishuChannel(cfg.notify.feishu_webhook))
|
||||
else:
|
||||
log.warning("通道 %s 已配置但缺少 webhook/token,跳过", name)
|
||||
return channels
|
||||
|
||||
|
||||
class Dispatcher:
|
||||
def __init__(self, channels: List[Channel], alert_cooldown_sec: int = 1800):
|
||||
self.channels = channels
|
||||
self.alert_cooldown_sec = alert_cooldown_sec
|
||||
self._last_alert: Dict[str, float] = {}
|
||||
|
||||
def notify(self, text: str) -> Dict[str, bool]:
|
||||
"""广播一条消息,返回各通道成功与否。异常不外抛。"""
|
||||
result: Dict[str, bool] = {}
|
||||
for ch in self.channels:
|
||||
try:
|
||||
ch.send(text)
|
||||
result[ch.name] = True
|
||||
log.info("推送成功 [%s] %s", ch.name, text.replace("\n", " ")[:80])
|
||||
except Exception as exc: # noqa: BLE001 - 推送失败绝不能让监控挂掉
|
||||
result[ch.name] = False
|
||||
log.error("推送失败 [%s]: %s", ch.name, exc)
|
||||
if not self.channels:
|
||||
log.warning("未配置任何推送通道,消息未发出: %s", text)
|
||||
return result
|
||||
|
||||
def alert(self, key: str, text: str) -> Tuple[bool, str]:
|
||||
"""带冷却的告警。同一 key 在冷却期内不重复发送。"""
|
||||
now = time.time()
|
||||
last = self._last_alert.get(key, 0)
|
||||
if now - last < self.alert_cooldown_sec:
|
||||
log.debug("告警 %s 处于冷却期,跳过", key)
|
||||
return False, "cooldown"
|
||||
self._last_alert[key] = now
|
||||
self.notify(text)
|
||||
return True, "sent"
|
||||
Reference in new issue
Block a user