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(功能/设置表/告警负载/技术说明)
This commit is contained in:
+26
@@ -0,0 +1,26 @@
|
||||
package run.halo.operationaudit.alert;
|
||||
|
||||
/**
|
||||
* Webhook 推送结果(功能评审 P0-2)。
|
||||
*
|
||||
* <p>{@code success} 为 true 表示接收方返回 2xx(送达);false 表示失败,
|
||||
* {@code message} 携带原因摘要(异常类名 + 消息或 HTTP 状态),供发送方记日志、
|
||||
* 供测试告警端点({@link AlertTestEndpoint})反馈到设置页提示。
|
||||
*
|
||||
* @param success 是否送达(接收方 2xx)
|
||||
* @param message 成功时为响应状态摘要(如 "HTTP 200"),失败时为原因摘要
|
||||
*/
|
||||
public record AlertSendResult(boolean success, String message) {
|
||||
|
||||
public static AlertSendResult ok(int statusCode) {
|
||||
return new AlertSendResult(true, "HTTP " + statusCode);
|
||||
}
|
||||
|
||||
public static AlertSendResult failure(Throwable cause) {
|
||||
var message = cause.getMessage();
|
||||
var summary = message != null && !message.isBlank()
|
||||
? cause.getClass().getSimpleName() + ": " + message
|
||||
: cause.getClass().getSimpleName();
|
||||
return new AlertSendResult(false, summary);
|
||||
}
|
||||
}
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
package run.halo.operationaudit.alert;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.reactive.function.server.RouterFunction;
|
||||
import org.springframework.web.reactive.function.server.ServerRequest;
|
||||
import org.springframework.web.reactive.function.server.ServerResponse;
|
||||
import reactor.core.publisher.Mono;
|
||||
import run.halo.app.core.extension.endpoint.CustomEndpoint;
|
||||
import run.halo.app.extension.GroupVersion;
|
||||
import run.halo.operationaudit.audit.AuditLog;
|
||||
|
||||
/**
|
||||
* 告警测试端点(功能评审 P0-2):验证 Webhook 配置是否可用——以当前配置地址推送一条
|
||||
* {@code type: "test"} 测试消息(与 login-failure 区分,接收方可识别为测试消息),
|
||||
* 同步等待推送结果并返回,供插件设置「告警通知」区的「发送测试告警」入口直接提示。
|
||||
*
|
||||
* <p>路径 {@code POST /apis/{group}/v1alpha1/alerts/-/test}。RBAC 资源组合为
|
||||
* {@code alerts + 子资源 test}(POST → create 动词):只读角色模板
|
||||
* (auditlogs get/list)未授权该资源,仅超级管理员等管理角色可调用——与
|
||||
* "验证告警配置"的管理动作语义一致。
|
||||
*
|
||||
* <p>Webhook 地址未配置或非法(非 http(s))返回 400;推送失败不抛出——以 200 +
|
||||
* {@code success=false} 返回原因摘要(fire-and-forget 语义不变:真实告警路径仍异步
|
||||
* 不等待)。推送结果同时反馈到运行日志,任何异常不影响主流程。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class AlertTestEndpoint implements CustomEndpoint {
|
||||
|
||||
private final AlertSettingProvider settingProvider;
|
||||
private final AlertWebhookSender sender;
|
||||
|
||||
@Override
|
||||
public GroupVersion groupVersion() {
|
||||
return GroupVersion.parseAPIVersion(AuditLog.GROUP + "/v1alpha1");
|
||||
}
|
||||
|
||||
@Override
|
||||
public RouterFunction<ServerResponse> endpoint() {
|
||||
return org.springdoc.webflux.core.fn.SpringdocRouteBuilder.route()
|
||||
.POST("alerts/-/test", this::test, builder -> builder
|
||||
.operationId("TestAlertWebhook")
|
||||
.description("向当前配置的 Webhook 地址推送一条测试告警(type=test)并返回"
|
||||
+ "推送结果:success 为是否送达(接收方 2xx),message 为状态/原因摘要;"
|
||||
+ "Webhook 未配置或非法时返回 400")
|
||||
.build())
|
||||
.build();
|
||||
}
|
||||
|
||||
private Mono<ServerResponse> test(ServerRequest request) {
|
||||
return settingProvider.get()
|
||||
.flatMap(settings -> {
|
||||
var url = settings.webhookUrlOrDefault();
|
||||
if (url == null) {
|
||||
return ServerResponse.badRequest().bodyValue(Map.of("message",
|
||||
"Webhook 地址未配置或非法(需以 http(s) 开头),请先保存设置"));
|
||||
}
|
||||
return sender.sendForResult(url, buildTestPayload(Instant.now()))
|
||||
.doOnNext(result -> {
|
||||
if (result.success()) {
|
||||
log.info("Test alert sent to {}: {}", url, result.message());
|
||||
} else {
|
||||
log.warn("Failed to send test alert to {}: {}", url,
|
||||
result.message());
|
||||
}
|
||||
})
|
||||
.flatMap(result -> ServerResponse.ok().bodyValue(Map.of(
|
||||
"success", result.success(),
|
||||
"message", result.message())));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 组装测试告警负载:与真实告警同结构(type/title/content/timestamp/data),
|
||||
* {@code type} 为独立的 {@value #TEST_TYPE},接收方可识别为测试消息。
|
||||
*/
|
||||
static Map<String, Object> buildTestPayload(Instant timestamp) {
|
||||
var payload = new LinkedHashMap<String, Object>();
|
||||
payload.put("type", TEST_TYPE);
|
||||
payload.put("title", "操作审计告警:测试消息");
|
||||
payload.put("content", "这是一条测试告警:收到即表示 Webhook 配置可用,"
|
||||
+ "真实告警(登录失败达到阈值)将以相同结构推送。");
|
||||
payload.put("timestamp", timestamp.toString());
|
||||
payload.put("data", Map.of("test", true));
|
||||
return payload;
|
||||
}
|
||||
|
||||
/** 测试告警的类型标识(与 login-failure 区分)。 */
|
||||
static final String TEST_TYPE = "test";
|
||||
}
|
||||
+25
-9
@@ -6,6 +6,7 @@ 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 负载。
|
||||
@@ -15,6 +16,10 @@ import org.springframework.web.reactive.function.client.WebClient;
|
||||
*
|
||||
* <p>负载为通用 JSON 结构(type/title/content/timestamp/data),不内置钉钉、企业微信、
|
||||
* 飞书等平台的专属消息格式适配,需要时可在中转服务侧转换。
|
||||
*
|
||||
* <p>功能评审 P0-2:新增 {@link #sendForResult(String, Map)}——返回推送结果
|
||||
* (送达与否 + 原因摘要)供测试告警端点同步反馈到设置页;登录失败告警路径
|
||||
* 仍走 {@link #send(String, Map)}(fire-and-forget 语义不变)。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@@ -31,18 +36,29 @@ public class AlertWebhookSender {
|
||||
|
||||
/** 异步推送 JSON 负载;任何失败仅记 warn 日志,不影响调用方。 */
|
||||
public void send(String url, Map<String, Object> payload) {
|
||||
try {
|
||||
webClient.post()
|
||||
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)
|
||||
.subscribe(null, e -> log.warn("Failed to send alert webhook to {}", url, e));
|
||||
} catch (Exception e) {
|
||||
// URL 非法等同步异常同样静默降级,绝不影响调用方
|
||||
log.warn("Failed to initiate alert webhook to {}", url, e);
|
||||
}
|
||||
.toBodilessEntity())
|
||||
.timeout(TIMEOUT)
|
||||
.map(response -> AlertSendResult.ok(response.getStatusCode().value()))
|
||||
.onErrorResume(e -> Mono.just(AlertSendResult.failure(e)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,6 +42,11 @@ spec:
|
||||
name: webhookUrl
|
||||
value: ""
|
||||
help: 接收告警的 http(s) 地址,告警以 JSON POST 异步推送(失败不重试,仅记日志)
|
||||
- $formkit: operationAuditTestAlert
|
||||
name: testAlert
|
||||
label: 测试告警
|
||||
ignore: true
|
||||
help: 向已保存的 Webhook 地址推送一条测试消息并直接反馈发送结果,用于验证配置是否可用(不保存任何配置值)
|
||||
- $formkit: number
|
||||
label: 触发阈值(次)
|
||||
name: thresholdCount
|
||||
|
||||
Reference in New Issue
Block a user