feat: Console 查看页与自有查询端点(里程碑 4)
- 服务端 AuditQueryEndpoint(CustomEndpoint,group=audit.example.com):
GET /apis/audit.example.com/v1alpha1/auditlogs/-/query
- 等值筛选(fieldSelector 白名单)、关键字(resourceName/path contains OR)、
结果(success 2xx-3xx / failure 4xx+)、时间区间(含边界 ISO-8601)
- 全部走索引 Query + PageRequestImpl,无内存分页;页大小上限 100
- 风险项 #2 源码级证实并按预案落地:原生 fieldSelector 仅支持 =/!=/IN
- API 使用 2.22+ 新 Queries/Condition 体系(QueryFactory 已 @Deprecated)
- Console 页面:列表(VEntity 行:操作者/动作徽标/资源/路径/状态码/IP)+
七维筛选栏 + 分页(10/20/50)+ 只读详情抽屉(完整字段 + 原始 JSON)
- 端点测试 10 例(默认值/筛选组合/参数校验/排序收敛),UI 类型检查通过
This commit is contained in:
+179
@@ -0,0 +1,179 @@
|
||||
package run.halo.operationaudit.audit;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.util.StringUtils;
|
||||
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 org.springframework.stereotype.Component;
|
||||
import reactor.core.publisher.Mono;
|
||||
import run.halo.app.core.extension.endpoint.CustomEndpoint;
|
||||
import run.halo.app.extension.GroupVersion;
|
||||
import run.halo.app.extension.ListOptions;
|
||||
import run.halo.app.extension.PageRequestImpl;
|
||||
import run.halo.app.extension.ReactiveExtensionClient;
|
||||
import run.halo.app.extension.router.selector.FieldSelector;
|
||||
import run.halo.app.extension.index.query.Condition;
|
||||
import run.halo.app.extension.index.query.Queries;
|
||||
import run.halo.operationaudit.audit.AuditLog;
|
||||
|
||||
/**
|
||||
* 自有查询端点(技术方案 5.3 / 风险项 #2):
|
||||
*
|
||||
* <p>经源码级验证(v2.26.1 FieldSelectorConverter),Halo 原生列表 API 的 fieldSelector
|
||||
* 仅支持 =/!=/IN 等值操作符,不支持时间区间与模糊匹配,因此按技术方案预案启用插件自有
|
||||
* 查询端点,内部走索引 Query 实现(无内存分页),UI 调用方式不变。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class AuditQueryEndpoint implements CustomEndpoint {
|
||||
|
||||
/** fieldSelector 支持等值筛选的字段白名单(与已注册索引一一对应)。 */
|
||||
private static final Set<String> FILTERABLE_FIELDS =
|
||||
Set.of("spec.username", "spec.resourceType", "spec.method", "spec.statusCode");
|
||||
|
||||
/** 每页大小上限,防止误用拖垮查询。 */
|
||||
static final int MAX_PAGE_SIZE = 100;
|
||||
|
||||
private final ReactiveExtensionClient client;
|
||||
|
||||
@Override
|
||||
public GroupVersion groupVersion() {
|
||||
return GroupVersion.parseAPIVersion(AuditLog.GROUP + "/v1alpha1");
|
||||
}
|
||||
|
||||
@Override
|
||||
public RouterFunction<ServerResponse> endpoint() {
|
||||
return org.springdoc.webflux.core.fn.SpringdocRouteBuilder.route()
|
||||
.GET("auditlogs/-/query", this::query, builder -> builder
|
||||
.operationId("ListAuditLogs")
|
||||
.description("分页查询审计日志:支持等值筛选(fieldSelector)、"
|
||||
+ "关键字(resourceName/path 模糊)、结果(success/failure)、"
|
||||
+ "时间区间(含边界)")
|
||||
.build())
|
||||
.build();
|
||||
}
|
||||
|
||||
private Mono<ServerResponse> query(ServerRequest request) {
|
||||
var params = request.queryParams();
|
||||
|
||||
var page = Math.max(parseInt(params.getFirst("page"), 1), 1);
|
||||
var size = Math.min(Math.max(parseInt(params.getFirst("size"), 20), 1), MAX_PAGE_SIZE);
|
||||
var sort = parseSort(params.getFirst("sort"));
|
||||
|
||||
var conditions = new ArrayList<Condition>();
|
||||
|
||||
// fieldSelector 等值筛选:field=value(多个 fieldSelector 参数叠加 AND)
|
||||
for (var term : params.getOrDefault("fieldSelector", List.of())) {
|
||||
var idx = term.indexOf('=');
|
||||
if (idx <= 0) {
|
||||
return badRequest("Invalid fieldSelector term, expect field=value: " + term);
|
||||
}
|
||||
var field = term.substring(0, idx).trim();
|
||||
var value = term.substring(idx + 1).trim();
|
||||
if (!FILTERABLE_FIELDS.contains(field)) {
|
||||
return badRequest("Field not filterable: " + field);
|
||||
}
|
||||
conditions.add(Queries.equal(field, value));
|
||||
}
|
||||
|
||||
// 关键字:资源名称 / 完整路径 模糊匹配(OR)
|
||||
var keyword = params.getFirst("keyword");
|
||||
if (StringUtils.hasText(keyword)) {
|
||||
var kw = keyword.trim();
|
||||
conditions.add(Queries.or(
|
||||
Queries.contains("spec.resourceName", kw),
|
||||
Queries.contains("spec.path", kw)));
|
||||
}
|
||||
|
||||
// 结果筛选:success = 2xx/3xx,failure = 4xx/5xx
|
||||
var resultFilter = params.getFirst("result");
|
||||
if (StringUtils.hasText(resultFilter)) {
|
||||
switch (resultFilter.trim().toLowerCase()) {
|
||||
case "success" -> {
|
||||
conditions.add(Queries.greaterThan("spec.statusCode", "200", true));
|
||||
conditions.add(Queries.lessThan("spec.statusCode", "400", true));
|
||||
}
|
||||
case "failure" -> conditions.add(Queries.greaterThan("spec.statusCode", "400", true));
|
||||
default -> {
|
||||
return badRequest("Invalid result, expect success or failure: "
|
||||
+ resultFilter);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 时间区间(含边界,ISO-8601 Instant)
|
||||
try {
|
||||
var start = parseInstant(params.getFirst("startTime"));
|
||||
var end = parseInstant(params.getFirst("endTime"));
|
||||
if (start != null) {
|
||||
conditions.add(Queries.greaterThan("metadata.creationTimestamp",
|
||||
start.toString(), true));
|
||||
}
|
||||
if (end != null) {
|
||||
conditions.add(Queries.lessThan("metadata.creationTimestamp",
|
||||
end.toString(), true));
|
||||
}
|
||||
} catch (DateTimeParseException e) {
|
||||
return badRequest("Invalid time format, expect ISO-8601 instant: "
|
||||
+ e.getMessage());
|
||||
}
|
||||
|
||||
var options = conditions.isEmpty()
|
||||
? new ListOptions().setFieldSelector(FieldSelector.all())
|
||||
: new ListOptions().setFieldSelector(
|
||||
FieldSelector.of(conditions.size() == 1 ? conditions.get(0)
|
||||
: Queries.and(conditions.get(0),
|
||||
conditions.subList(1, conditions.size())
|
||||
.toArray(Condition[]::new))));
|
||||
|
||||
var pageable = PageRequestImpl.of(page, size, sort);
|
||||
return client.listBy(AuditLog.class, options, pageable)
|
||||
.flatMap(result -> ServerResponse.ok().bodyValue(result));
|
||||
}
|
||||
|
||||
private static Mono<ServerResponse> badRequest(String message) {
|
||||
return ServerResponse.badRequest().bodyValue(java.util.Map.of("message", message));
|
||||
}
|
||||
|
||||
private static int parseInt(String value, int fallback) {
|
||||
if (!StringUtils.hasText(value)) {
|
||||
return fallback;
|
||||
}
|
||||
try {
|
||||
return Integer.parseInt(value.trim());
|
||||
} catch (NumberFormatException e) {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
/** 解析 sort 参数:{@code field,(asc|desc)},默认 creationTimestamp 降序。 */
|
||||
static Sort parseSort(String sortParam) {
|
||||
if (!StringUtils.hasText(sortParam)) {
|
||||
return Sort.by(Sort.Order.desc("metadata.creationTimestamp"));
|
||||
}
|
||||
var parts = sortParam.split(",");
|
||||
var field = parts[0].trim();
|
||||
if (!"metadata.creationTimestamp".equals(field)) {
|
||||
// MVP 仅开放时间排序,避免未排序索引上的全量内存排序
|
||||
field = "metadata.creationTimestamp";
|
||||
}
|
||||
var descending = parts.length < 2 || !"asc".equalsIgnoreCase(parts[1].trim());
|
||||
return Sort.by(descending ? Sort.Order.desc(field) : Sort.Order.asc(field));
|
||||
}
|
||||
|
||||
private static Instant parseInstant(String value) {
|
||||
if (!StringUtils.hasText(value)) {
|
||||
return null;
|
||||
}
|
||||
return Instant.parse(value.trim());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user