Files
halo-ops-audit/plugin-operation-audit/src/main/java/run/halo/operationaudit/alert/AlertWebhookSender.java
T
836061373 3269bafbc4 feat: Webhook「发送测试告警」(P0-2,设置页入口+结果化推送)
- AlertWebhookSender 新增 sendForResult:结果化推送(送达与否 + 原因摘要),
  超时/网络错误/非 2xx/URL 非法一律归一为失败结果,永不抛出;
  send(fire-and-forget)复用同一实现,真实告警路径语义不变
- 新增 AlertTestEndpoint:POST /apis/.../alerts/-/test 以 type=test 测试消息
  推送到已保存的 Webhook 地址并同步等待结果返回;Webhook 未配置/非法返回 400;
  RBAC 资源组合 alerts + alerts/test(create 动词)不在只读角色模板授权内
- 设置页「告警通知」区新增「发送测试告警」自定义 FormKit 输入
  (Halo 2.25+ formkit.inputs,@formkit/vue 为宿主共享外部模块),
  推送结果以设置页提示 + 运行日志反馈,ignore:true 不新增设置项
- 更新 README(功能/设置表/告警负载/技术说明)
2026-11-22 00:11:24 +08:00

65 lines
2.7 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package run.halo.operationaudit.alert;
import java.time.Duration;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
/**
* 告警 Webhook 推送器:向配置地址异步 POST JSON 负载。
*
* <p>fire-and-forget(产品设计原则 4):超时 10 秒后放弃,失败(网络错误、非 2xx 响应、
* URL 非法)仅记 warn 日志,不重试、不抛出,绝不影响登录与审计主流程。
*
* <p>负载为通用 JSON 结构(type/title/content/timestamp/data),不内置钉钉、企业微信、
* 飞书等平台的专属消息格式适配,需要时可在中转服务侧转换。
*
* <p>功能评审 P0-2:新增 {@link #sendForResult(String, Map)}——返回推送结果
* (送达与否 + 原因摘要)供测试告警端点同步反馈到设置页;登录失败告警路径
* 仍走 {@link #send(String, Map)}(fire-and-forget 语义不变)。
*/
@Slf4j
@Component
public class AlertWebhookSender {
/** 发送超时:告警为旁路功能,超时即放弃(不重试)。 */
private static final Duration TIMEOUT = Duration.ofSeconds(10);
private final WebClient webClient;
public AlertWebhookSender() {
this.webClient = WebClient.builder().build();
}
/** 异步推送 JSON 负载;任何失败仅记 warn 日志,不影响调用方。 */
public void send(String url, Map<String, Object> payload) {
sendForResult(url, payload).subscribe(result -> {
if (!result.success()) {
log.warn("Failed to send alert webhook to {}: {}", url, result.message());
}
});
}
/**
* 推送 JSON 负载并返回结果(功能评审 P0-2):成功为接收方 2xx;超时、网络错误、
* 非 2xx、URL 非法等任何失败均归一为失败结果,绝不抛出、绝不重试。
*
* <p>返回的 Mono 永不为空、永不报错,超时上限与 fire-and-forget 路径一致
* (10 秒)——测试告警端点同步等待该结果反馈到设置页。
*/
public Mono<AlertSendResult> sendForResult(String url, Map<String, Object> payload) {
return Mono.defer(() -> webClient.post()
.uri(url)
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(payload)
.retrieve()
.toBodilessEntity())
.timeout(TIMEOUT)
.map(response -> AlertSendResult.ok(response.getStatusCode().value()))
.onErrorResume(e -> Mono.just(AlertSendResult.failure(e)));
}
}