feat(通知): 系统级 Webhook 通知子系统(事件目录 + 可插拔适配器 + 防刷屏)

平台此前出了问题只能靠人盯页面。现在各组件统一走 `notifier.notify(事件, **字段)`,
推到企业微信 / 自建服务;**所有可通知点都登记进事件目录,默认全关,用户按 webhook 勾选**。

## 架构(`core/notifier.py` + `core/notify_events.py`)
业务线程调 `notify()` → 只做内存操作(读配置快照/匹配订阅/入队)→ 返回;
后台 1 个 dispatcher(聚合 + 每 hook 限流 + 折叠摘要)+ 3 个 sender(真实 HTTP、退避重试)
负责真正发出去。硬约束:**notify 零 DB、零 HTTP、零阻塞、异常不冒泡**——所以任务线程里
可以直接调(不用 app_context、不用 try/except),但**必须放在所有 `with self._lock` 之外**。

- **事件目录 36 条**(任务批次/单设备/设备/Worker/业务/安装/系统/AI),支持 `task.*` 通配订阅;
  语义分工避免重复告警:`worker.*` 是单次尝试级,`task.device.success/failed` 是唯一权威结论。
- **适配器可插拔**:`wecom`(markdown,按 4096 **字节**截断、超限不截半个汉字)+
  `json`(模板占位符,替换值按 JSON 转义,保存前干跑校验);钉钉/飞书留了插槽(前端置灰)。
- **防打爆四层**:聚合窗口(默认 30s,同批次合并成一条并带样本)→ 令牌桶限流(默认 18/分,
  对齐企微硬限 20)→ 被限流的**折叠成摘要不丢弃** → 有界队列背压。取舍:失败通知最多延迟
  一个窗口,换来群不被刷屏。

## 安全与存储
- 配置只落 `app_meta.notify_webhooks` 一个键(**不建表** → 不涉及备份覆盖红线)。
- URL 本身就是凭据(企微 `?key=`)→ 接口回显/发送记录/日志一律 `mask_url()/scrub()`;
  编辑时留空即不修改;secret 永不回显。DATA_MODEL 的明文凭据告警补上了这一条。
- 发送记录:内存环形缓冲 200 条(重启清空)+ 独立 `logs/notify.log`。

## 接入点(每个都放在锁外、不改 return 顺序)
task_manager(批次开始/结束用新增的 `_BatchTracker` 统一在 finally 计数、单设备成功/失败/
离线/重试/停止/抢占/归还/cron 停止)、device_worker 心跳看门狗、generic 任务选择器连续失效、
apk 安装开始/完成、设备上下线(**状态沿检测**,只报新变化)、备份导出/恢复、经验巡检、
用户登录、服务启停。

## 前端
系统 Tab 新增「通知 / Webhook」子分栏:多条 webhook 列表(URL 打码)+ 编辑弹窗(格式/URL/
密钥/事件勾选树带 ★建议/聚合/限流/自定义模板/预览)+ 发送测试 + 发送记录。

## 自测
- 进程内逻辑 10 组断言全绿:聚合合并、限流+折叠、无配置/全局关静默丢弃、未知事件、
  内部异常不外泄、JSON 转义(标题含引号换行仍合法)、URL/异常消息脱敏、配置校验。
- 端到端(假 webhook 接收端)17 项断言全绿:真实事件投递(user.login / task.batch.no_device)、
  企微请求体形状、**HTTP 200 + errcode 93000 判为失败**、500 重试 3 次、记录里 URL 打码。
- 韧性:webhook 指向黑洞地址时登录耗时 100~114ms(基线 107~133ms,**异步隔离生效**);
  配置写成坏 JSON 服务照常启动、通知静默不发、日志有 error(服务端实测后已复原)。
- 页面:系统 → 通知 面板/弹窗/36 个事件复选框/预览全部正常,无 JS 报错。
- 自测数据已清理(webhook、自建任务、写坏又复原的配置键)。

文档:新增 doc/NOTIFY.md(事件表/配置/格式约束/防刷屏/加事件三步骤/排障)并登记进 doc/README;
API.md §2.11;DATA_MODEL 的 app_meta 键表与明文凭据告警;ARCHITECTURE 线程表/分层/扩展点;
根 README 功能索引与日志表。
This commit is contained in:
2026-09-15 13:55:14 +08:00
parent 5e0a7d5556
commit 97cec6e211
23 changed files with 2075 additions and 15 deletions
+186
View File
@@ -0,0 +1,186 @@
"""通知 / Webhook 管理接口(系统级设置,全部 admin_required)。
配置读写统一走 `core/notifier`(它落 `app_meta.notify_webhooks` 一个键)——本模块
只做"取配置 → 改一处 → 存回去"的编排,**校验与持久化都在 notifier 里**,不在 web 层
重复实现(避免两份规则漂移)。
安全口径:
- URL 里有凭据(企微 `?key=`)→ 回显一律 `notifier.mask_url()`;
- 前端"留空不修改":提交上来的 url 若是打码值或空,`save_config` 会保留原值;
- `secret` 永不回显,只回 `secret_set`。
"""
import uuid
from flask import Blueprint, jsonify, request
from flask_login import current_user
from core import notify_events, notifier
from core.logger import get_logger
from web.auth import admin_required
_log = get_logger("web.notify")
bp = Blueprint("notify", __name__)
def _operator():
try:
return current_user.username or "admin"
except Exception:
return "admin"
def _formats():
"""可用格式(含未实现的,前端据此置灰)。"""
out = []
for name, cls in notifier.ADAPTERS.items():
out.append({"name": name, "label": cls.label, "implemented": True,
"byte_limit": cls.byte_limit, "limit_default": cls.limit_default})
for name, label in notifier.PLANNED_FORMATS.items():
out.append({"name": name, "label": label + "(未实现)", "implemented": False,
"byte_limit": 0, "limit_default": 20})
return out
@bp.route("/api/notify/webhooks")
@admin_required
def api_notify_webhooks():
"""全部 webhook 配置(url 打码、secret 只回是否配置过)+ 格式清单 + 事件目录。"""
cfg = notifier.get_public_config()
return jsonify({"ok": True, "webhooks": cfg["webhooks"], "settings": cfg["settings"],
"formats": _formats(), "meta_key": notifier.META_KEY,
"max_hooks": notifier.MAX_HOOKS,
"planned": list(notifier.PLANNED_FORMATS)})
@bp.route("/api/notify/webhooks", methods=["POST"])
@admin_required
def api_notify_webhook_create():
"""新建一条 webhook。body 即该条配置(见 doc/NOTIFY.md 的字段表)。"""
data = request.json or {}
cfg = notifier.get_config()
if len(cfg["webhooks"]) >= notifier.MAX_HOOKS:
return jsonify({"ok": False, "error": f"最多 {notifier.MAX_HOOKS} 条"}), 400
new_id = "wh_" + uuid.uuid4().hex[:8]
hook = dict(data)
hook["id"] = new_id
cfg["webhooks"].append(hook)
ok, msg = notifier.save_config(cfg)
if not ok:
return jsonify({"ok": False, "error": msg, "errors": msg
if isinstance(msg, list) else None}), 400
_log.info("新增通知 webhook: %s(%s)by %s", hook.get("name"), new_id, _operator())
return jsonify({"ok": True, "msg": "已创建", "id": new_id})
@bp.route("/api/notify/webhooks/<hook_id>", methods=["PUT"])
@admin_required
def api_notify_webhook_update(hook_id):
"""更新一条(部分字段;url/secret 省略或为打码值时保持原值)。"""
data = request.json or {}
cfg = notifier.get_config()
target = next((h for h in cfg["webhooks"] if h["id"] == hook_id), None)
if not target:
return jsonify({"ok": False, "error": "webhook 不存在"}), 404
for k, v in data.items():
if k in ("id", "created_at"):
continue
target[k] = v
ok, msg = notifier.save_config(cfg)
if not ok:
return jsonify({"ok": False, "error": msg, "errors": msg
if isinstance(msg, list) else None}), 400
_log.info("更新通知 webhook: %s by %s", hook_id, _operator())
return jsonify({"ok": True, "msg": "已保存"})
@bp.route("/api/notify/webhooks/<hook_id>", methods=["DELETE"])
@admin_required
def api_notify_webhook_delete(hook_id):
cfg = notifier.get_config()
before = len(cfg["webhooks"])
cfg["webhooks"] = [h for h in cfg["webhooks"] if h["id"] != hook_id]
if len(cfg["webhooks"]) == before:
return jsonify({"ok": False, "error": "webhook 不存在"}), 404
ok, msg = notifier.save_config(cfg)
if not ok:
return jsonify({"ok": False, "error": msg}), 400
_log.info("删除通知 webhook: %s by %s", hook_id, _operator())
return jsonify({"ok": True, "msg": "已删除"})
@bp.route("/api/notify/webhooks/<hook_id>/test", methods=["POST"])
@admin_required
def api_notify_webhook_test(hook_id):
"""同步发一条测试消息(用户等结果),返回真实 HTTP 状态与平台错误码。
⚠ 不占业务令牌桶:否则管理员点两下测试就把业务通知的配额吃掉了。
"""
cfg = notifier.get_config()
hook = next((h for h in cfg["webhooks"] if h["id"] == hook_id), None)
if not hook:
return jsonify({"ok": False, "error": "webhook 不存在"}), 404
event = ((request.json or {}).get("event") or "notify.test").strip()
rec = notifier.send_test(hook, event=event, operator=_operator())
return jsonify({"ok": bool(rec.get("ok")),
"msg": "测试消息已发出" if rec.get("ok") else "发送失败",
"http_status": rec.get("http_status"),
"errcode": rec.get("errcode"),
"elapsed_ms": rec.get("elapsed_ms"),
"attempts": rec.get("attempts"),
"error": rec.get("error") or "",
"url": notifier.mask_url(hook.get("url", ""))})
@bp.route("/api/notify/preview", methods=["POST"])
@admin_required
def api_notify_preview():
"""保存前预览:真实请求体 + UTF-8 字节数 + 是否会被截断。"""
data = request.json or {}
hook = data.get("hook") or {}
# 预览时 URL 可能还没填:给个占位,只关心渲染结果
hook = dict(hook)
hook.setdefault("url", "https://example.invalid/hook")
out = notifier.preview(hook, event=(data.get("event") or "notify.test"))
return jsonify({"ok": not out.get("error"), **out})
@bp.route("/api/notify/events")
@admin_required
def api_notify_events():
"""事件目录(前端画勾选树 / 模板占位符速查)。"""
rows = notify_events.list_events()
cats = []
for e in rows:
if e["category"] not in cats:
cats.append(e["category"])
return jsonify({"ok": True, "events": rows, "categories": cats})
@bp.route("/api/notify/logs")
@admin_required
def api_notify_logs():
"""最近发送记录(内存环形缓冲,重启清空;历史见 logs/notify.log)。"""
limit = request.args.get("limit", 50)
try:
limit = max(1, min(int(limit), 200))
except (TypeError, ValueError):
limit = 50
return jsonify({"ok": True, "logs": notifier.get_logs(limit),
"note": "仅显示本次运行期间记录;历史见 logs/notify.log"})
@bp.route("/api/notify/settings", methods=["POST"])
@admin_required
def api_notify_settings():
"""全局设置:global_enabled / default_agg_window / default_rate_limit / log_keep。"""
data = request.json or {}
cfg = notifier.get_config()
for k in ("global_enabled", "default_agg_window", "default_rate_limit",
"log_keep", "http_timeout"):
if k in data and data[k] is not None:
cfg["settings"][k] = data[k]
ok, msg = notifier.save_config(cfg)
if not ok:
return jsonify({"ok": False, "error": msg}), 400
_log.info("更新通知全局设置 by %s: %s", _operator(), data)
return jsonify({"ok": True, "msg": "已保存"})