feat: 设置与保留期清理(里程碑 5)
- settings.yaml:审计开关(默认开)+ 保留天数(默认 90、最小 7),FormKit 声明式 - plugin.yaml 声明 settingName/configMapName(源码级核对 Plugin.spec 字段名) - AuditSettingProvider:60s TTL 缓存读取(D6),失败/缺省回退默认且默认值同样入缓存 - AuditRecorder 写入前检查开关;设置故障按默认配置继续记录(审计设置故障不影响捕获) - RetentionCleaner:Reactor 调度(风险项 #3 预案,未验证 @Scheduled 不赌插件上下文), 启动补跑一次 + 每日 03:00;按时间索引升序每批 200 循环至不足一批(D5) - 插件 start/stop 联动清理器生命周期 - 新增 17 个测试:TTL 命中/过期重取/降级、批量删除/边界/调度时机、开关跳过
This commit is contained in:
+10
-4
@@ -6,27 +6,31 @@ import run.halo.app.extension.Scheme;
|
||||
import run.halo.app.extension.SchemeManager;
|
||||
import run.halo.app.extension.index.IndexSpecs;
|
||||
import run.halo.operationaudit.audit.AuditLog;
|
||||
import run.halo.operationaudit.housekeeping.RetentionCleaner;
|
||||
import run.halo.app.plugin.BasePlugin;
|
||||
import run.halo.app.plugin.PluginContext;
|
||||
|
||||
/**
|
||||
* 操作审计插件入口。
|
||||
*
|
||||
* <p>负责插件生命周期(技术方案 D3):
|
||||
* <p>负责插件生命周期:
|
||||
* <ul>
|
||||
* <li>启动时注册 {@code AuditLog} 模型与索引(操作者/资源类型/动作/结果/资源名称/路径,
|
||||
* 时间索引由 Halo 为所有模型自动注册);</li>
|
||||
* <li>停止时注销模型。</li>
|
||||
* 时间索引由 Halo 为所有模型自动注册),并启动保留期清理调度;</li>
|
||||
* <li>停止时注销模型、取消清理调度。</li>
|
||||
* </ul>
|
||||
*/
|
||||
@Component
|
||||
public class OperationAuditPlugin extends BasePlugin {
|
||||
|
||||
private final SchemeManager schemeManager;
|
||||
private final RetentionCleaner retentionCleaner;
|
||||
|
||||
public OperationAuditPlugin(PluginContext pluginContext, SchemeManager schemeManager) {
|
||||
public OperationAuditPlugin(PluginContext pluginContext, SchemeManager schemeManager,
|
||||
RetentionCleaner retentionCleaner) {
|
||||
super(pluginContext);
|
||||
this.schemeManager = schemeManager;
|
||||
this.retentionCleaner = retentionCleaner;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -39,10 +43,12 @@ public class OperationAuditPlugin extends BasePlugin {
|
||||
addIndex(indexSpecs, "spec.resourceName", String.class, log -> log.getSpec().getResourceName());
|
||||
addIndex(indexSpecs, "spec.path", String.class, log -> log.getSpec().getPath());
|
||||
});
|
||||
retentionCleaner.start();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() {
|
||||
retentionCleaner.stop();
|
||||
var gvk = gvkOf();
|
||||
schemeManager.fetch(gvk).ifPresent(schemeManager::unregister);
|
||||
}
|
||||
|
||||
+25
-1
@@ -7,11 +7,14 @@ import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
import run.halo.app.extension.Metadata;
|
||||
import run.halo.app.extension.ReactiveExtensionClient;
|
||||
import run.halo.operationaudit.housekeeping.AuditSettingProvider;
|
||||
import run.halo.operationaudit.housekeeping.AuditSettings;
|
||||
|
||||
/**
|
||||
* 组装并直写审计记录(技术方案 D2:响应式直写,fire-and-forget)。
|
||||
*
|
||||
* <p>失败静默降级为 warn 日志:不重试、不阻塞、不抛出(产品设计原则 4)。
|
||||
* <p>写入前经设置缓存(60s TTL,D6)检查审计开关:关闭时静默跳过。
|
||||
* 失败静默降级为 warn 日志:不重试、不阻塞、不抛出(产品设计原则 4)。
|
||||
* 不引入内存队列:Extension 存储底层为响应式(R2DBC),连接池天然提供背压;
|
||||
* 若后续压测发现写入积压,在 Recorder 内部替换为有界队列 + worker,接口不变。
|
||||
*/
|
||||
@@ -21,11 +24,32 @@ import run.halo.app.extension.ReactiveExtensionClient;
|
||||
public class AuditRecorder {
|
||||
|
||||
private final ReactiveExtensionClient client;
|
||||
private final AuditSettingProvider settingProvider;
|
||||
|
||||
/**
|
||||
* 记录一次操作。任何失败仅记 warn 日志,不影响调用方。
|
||||
*
|
||||
* <p>设置读取失败按默认配置(开启)继续记录:Provider 内部已回退默认值,
|
||||
* 此处为防御性兜底,保证审计设置故障不影响捕获链路。
|
||||
*/
|
||||
public void record(RequestSnapshot snapshot, Integer statusCode, String username) {
|
||||
settingProvider.get().subscribe(
|
||||
settings -> {
|
||||
if (!settings.enabledOrDefault()) {
|
||||
log.debug("Audit disabled, skip recording {} {}",
|
||||
snapshot.getMethod(), snapshot.getFullPath());
|
||||
return;
|
||||
}
|
||||
write(snapshot, statusCode, username);
|
||||
},
|
||||
e -> {
|
||||
log.warn("Failed to load audit settings, record with defaults for {} {}",
|
||||
snapshot.getMethod(), snapshot.getFullPath(), e);
|
||||
write(snapshot, statusCode, username);
|
||||
});
|
||||
}
|
||||
|
||||
private void write(RequestSnapshot snapshot, Integer statusCode, String username) {
|
||||
try {
|
||||
var auditLog = assemble(snapshot, statusCode, username);
|
||||
client.create(auditLog)
|
||||
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
package run.halo.operationaudit.housekeeping;
|
||||
|
||||
import java.time.Duration;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
import reactor.core.publisher.Mono;
|
||||
import run.halo.app.plugin.ReactiveSettingFetcher;
|
||||
|
||||
/**
|
||||
* 审计设置的短 TTL 缓存读取(技术方案 D6)。
|
||||
*
|
||||
* <p>开关变更最多延迟 1 分钟生效——自用场景可接受,避免为实时生效引入 ConfigMap 监听器。
|
||||
* 读取失败或未配置时静默回退默认值(默认值同样进入缓存,避免配置持续损坏时
|
||||
* 每个请求都访问存储),绝不影响捕获与清理流程。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class AuditSettingProvider {
|
||||
|
||||
/** 缓存有效期。 */
|
||||
public static final Duration TTL = Duration.ofSeconds(60);
|
||||
|
||||
private final ReactiveSettingFetcher fetcher;
|
||||
|
||||
/** TTL 缓存条目;包内可见以便测试构造过期条目。 */
|
||||
record CacheEntry(AuditSettings value, long expireAtNanos) {
|
||||
boolean expiredAt(long nowNanos) {
|
||||
return nowNanos >= expireAtNanos;
|
||||
}
|
||||
}
|
||||
|
||||
volatile CacheEntry cache;
|
||||
|
||||
/**
|
||||
* 获取当前设置(TTL 内直接命中缓存)。
|
||||
*
|
||||
* <p>返回的 Mono 永不为空、永不报错:任何异常均回退默认值。
|
||||
*/
|
||||
public Mono<AuditSettings> get() {
|
||||
var entry = cache;
|
||||
if (entry != null && !entry.expiredAt(System.nanoTime())) {
|
||||
return Mono.just(entry.value());
|
||||
}
|
||||
return fetcher.fetch(AuditSettings.GROUP, AuditSettings.class)
|
||||
.onErrorResume(e -> {
|
||||
log.warn("Failed to load audit settings, fall back to defaults", e);
|
||||
return Mono.just(AuditSettings.defaults());
|
||||
})
|
||||
.defaultIfEmpty(AuditSettings.defaults())
|
||||
.doOnNext(value -> cache = new CacheEntry(value, System.nanoTime() + TTL.toNanos()));
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package run.halo.operationaudit.housekeeping;
|
||||
|
||||
/**
|
||||
* 审计设置(存储于插件 ConfigMap 的 {@code audit} 组,技术方案 D6)。
|
||||
*
|
||||
* <p>取值全部经 {@code xxxOrDefault()} 归一:缺省或非法值回退默认,保证调用方拿到合法值。
|
||||
*/
|
||||
public record AuditSettings(Boolean enabled, Integer retentionDays) {
|
||||
|
||||
/** ConfigMap 中的配置组名。 */
|
||||
public static final String GROUP = "audit";
|
||||
|
||||
/** 默认保留天数(产品设计 4.3)。 */
|
||||
public static final int DEFAULT_RETENTION_DAYS = 90;
|
||||
|
||||
/** 最小保留天数(技术方案 D6)。 */
|
||||
public static final int MIN_RETENTION_DAYS = 7;
|
||||
|
||||
/** 审计开关默认值。 */
|
||||
public static final boolean DEFAULT_ENABLED = true;
|
||||
|
||||
public boolean enabledOrDefault() {
|
||||
return enabled == null ? DEFAULT_ENABLED : enabled;
|
||||
}
|
||||
|
||||
public int retentionDaysOrDefault() {
|
||||
if (retentionDays == null || retentionDays < MIN_RETENTION_DAYS) {
|
||||
return DEFAULT_RETENTION_DAYS;
|
||||
}
|
||||
return retentionDays;
|
||||
}
|
||||
|
||||
public static AuditSettings defaults() {
|
||||
return new AuditSettings(DEFAULT_ENABLED, DEFAULT_RETENTION_DAYS);
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package run.halo.operationaudit.housekeeping;
|
||||
|
||||
import java.time.Clock;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import run.halo.app.extension.ReactiveExtensionClient;
|
||||
|
||||
/**
|
||||
* 清理任务装配:以固定系统时钟构建 {@link RetentionCleaner},便于测试时替换时钟。
|
||||
*/
|
||||
@Configuration
|
||||
public class HousekeepingConfiguration {
|
||||
|
||||
@Bean
|
||||
RetentionCleaner retentionCleaner(ReactiveExtensionClient client,
|
||||
AuditSettingProvider settingProvider) {
|
||||
return new RetentionCleaner(client, settingProvider, Clock.systemDefaultZone());
|
||||
}
|
||||
}
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
package run.halo.operationaudit.housekeeping;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import reactor.core.Disposable;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
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.Queries;
|
||||
import run.halo.operationaudit.audit.AuditLog;
|
||||
|
||||
/**
|
||||
* 保留期自动清理(技术方案 D5)。
|
||||
*
|
||||
* <p>调度采用 Reactor 方案(技术方案第 9 节风险项 #3 的预案):插件启动时补跑一次
|
||||
* 处理停机期间积压,之后每日凌晨 03:00(系统默认时区)执行。清理流程:按时间索引
|
||||
* 升序、每批 200 条查过期记录 → 逐条删除 → 循环至不足一批。不引入 Quartz 等调度组件。
|
||||
*/
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class RetentionCleaner {
|
||||
|
||||
/** 每批查询/删除条数(技术方案 D5)。 */
|
||||
static final int BATCH_SIZE = 200;
|
||||
|
||||
/** 每日执行时刻(时区取系统默认)。 */
|
||||
static final int RUN_HOUR = 3;
|
||||
|
||||
private final ReactiveExtensionClient client;
|
||||
private final AuditSettingProvider settingProvider;
|
||||
private final Clock clock;
|
||||
|
||||
private Disposable scheduleTask;
|
||||
|
||||
/** 插件启动时调用:补跑一次 + 注册每日调度。 */
|
||||
public void start() {
|
||||
// 补跑一次,处理停机期间积压的过期数据
|
||||
cleanOnce().subscribe(
|
||||
null, e -> log.warn("Initial audit log cleanup failed", e));
|
||||
scheduleTask = Mono.defer(() -> Mono.delay(delayUntilNextRun()))
|
||||
.repeat()
|
||||
.concatMap(tick -> cleanOnce()
|
||||
.doOnSuccess(unused -> log.debug("Scheduled audit log cleanup finished")))
|
||||
.subscribe(null, e -> log.warn("Scheduled audit log cleanup failed", e));
|
||||
log.info("Retention cleaner started, daily run at {}:00", RUN_HOUR);
|
||||
}
|
||||
|
||||
/** 插件停止时调用:取消调度。 */
|
||||
public void stop() {
|
||||
if (scheduleTask != null && !scheduleTask.isDisposed()) {
|
||||
scheduleTask.dispose();
|
||||
}
|
||||
log.info("Retention cleaner stopped");
|
||||
}
|
||||
|
||||
/** 距下一次执行(每日 RUN_HOUR 点)的时长。 */
|
||||
Duration delayUntilNextRun() {
|
||||
var now = LocalDateTime.now(clock);
|
||||
var nextRun = now.toLocalDate().atTime(RUN_HOUR, 0);
|
||||
if (!nextRun.isAfter(now)) {
|
||||
nextRun = nextRun.plusDays(1);
|
||||
}
|
||||
return Duration.between(now, nextRun);
|
||||
}
|
||||
|
||||
/**
|
||||
* 按当前设置执行一轮清理。
|
||||
*
|
||||
* @return 本轮删除的记录总数
|
||||
*/
|
||||
public Mono<Long> cleanOnce() {
|
||||
return settingProvider.get()
|
||||
.map(settings -> clock.instant()
|
||||
.minus(Duration.ofDays(settings.retentionDaysOrDefault())))
|
||||
.flatMap(this::deleteExpired);
|
||||
}
|
||||
|
||||
private Mono<Long> deleteExpired(Instant cutoff) {
|
||||
return deleteBatch(cutoff).flatMap(deleted -> deleted < BATCH_SIZE
|
||||
? Mono.just(deleted)
|
||||
: deleteExpired(cutoff).map(next -> next + deleted));
|
||||
}
|
||||
|
||||
private Mono<Long> deleteBatch(Instant cutoff) {
|
||||
var options = new ListOptions().setFieldSelector(FieldSelector.of(
|
||||
Queries.lessThan("metadata.creationTimestamp", cutoff.toString(), true)));
|
||||
var pageable = PageRequestImpl.of(1, BATCH_SIZE,
|
||||
Sort.by(Sort.Order.asc("metadata.creationTimestamp")));
|
||||
return client.listBy(AuditLog.class, options, pageable)
|
||||
.flatMapMany(result -> Flux.fromIterable(
|
||||
result.getItems() != null ? result.getItems() : List.of()))
|
||||
.flatMap(client::delete)
|
||||
.count();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
apiVersion: v1alpha1
|
||||
kind: Setting
|
||||
metadata:
|
||||
name: operation-audit-settings
|
||||
spec:
|
||||
forms:
|
||||
- group: audit
|
||||
label: 审计设置
|
||||
formSchema:
|
||||
- $formkit: checkbox
|
||||
label: 启用审计
|
||||
name: enabled
|
||||
value: true
|
||||
help: 关闭后不再记录新的操作审计日志,已有记录仍可查询
|
||||
- $formkit: number
|
||||
label: 保留天数
|
||||
name: retentionDays
|
||||
min: 7
|
||||
step: 1
|
||||
value: 90
|
||||
help: 超过保留期的审计记录将在每日自动清理(最小 7 天)
|
||||
@@ -9,5 +9,7 @@ spec:
|
||||
name: Guichumo
|
||||
displayName: "操作审计"
|
||||
description: "记录后台写操作与登录事件,回答谁、在什么时候、对什么资源、做了什么操作、结果如何。"
|
||||
settingName: operation-audit-settings
|
||||
configMapName: operation-audit-configmap
|
||||
license:
|
||||
- name: "GPL-3.0"
|
||||
|
||||
+7
-3
@@ -20,6 +20,7 @@ import run.halo.app.extension.index.IndexSpecs;
|
||||
import run.halo.app.extension.index.ValueIndexSpec;
|
||||
import run.halo.app.plugin.PluginContext;
|
||||
import run.halo.operationaudit.audit.AuditLog;
|
||||
import run.halo.operationaudit.housekeeping.RetentionCleaner;
|
||||
|
||||
/**
|
||||
* 插件生命周期测试:启动注册 {@link AuditLog} 模型与全部索引,停止注销。
|
||||
@@ -29,13 +30,14 @@ class OperationAuditPluginTest {
|
||||
@Test
|
||||
void shouldRegisterAuditLogWithExpectedIndexesOnStart() {
|
||||
var schemeManager = mock(SchemeManager.class);
|
||||
var cleaner = mock(RetentionCleaner.class);
|
||||
var registeredSpecs = new AtomicReference<Consumer<IndexSpecs<AuditLog>>>();
|
||||
doAnswer(invocation -> {
|
||||
registeredSpecs.set(invocation.getArgument(1));
|
||||
return null;
|
||||
}).when(schemeManager).register(eq(AuditLog.class), any());
|
||||
|
||||
var plugin = new OperationAuditPlugin(pluginContext(), schemeManager);
|
||||
var plugin = new OperationAuditPlugin(pluginContext(), schemeManager, cleaner);
|
||||
plugin.start();
|
||||
|
||||
var recordingSpecs = new RecordingIndexSpecs();
|
||||
@@ -51,16 +53,18 @@ class OperationAuditPluginTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldUnregisterSchemeOnStop() {
|
||||
void shouldStopCleanerAndUnregisterSchemeOnStop() {
|
||||
var schemeManager = mock(SchemeManager.class);
|
||||
var cleaner = mock(RetentionCleaner.class);
|
||||
var scheme = mock(Scheme.class);
|
||||
var gvk = new GroupVersionKind("audit.example.com", "v1alpha1", "AuditLog");
|
||||
org.mockito.Mockito.when(schemeManager.fetch(gvk))
|
||||
.thenReturn(java.util.Optional.of(scheme));
|
||||
|
||||
var plugin = new OperationAuditPlugin(pluginContext(), schemeManager);
|
||||
var plugin = new OperationAuditPlugin(pluginContext(), schemeManager, cleaner);
|
||||
plugin.stop();
|
||||
|
||||
verify(cleaner).stop();
|
||||
verify(schemeManager).unregister(scheme);
|
||||
}
|
||||
|
||||
|
||||
+50
-27
@@ -4,30 +4,51 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
|
||||
import reactor.core.publisher.Mono;
|
||||
import run.halo.app.extension.ReactiveExtensionClient;
|
||||
import run.halo.operationaudit.housekeeping.AuditSettingProvider;
|
||||
import run.halo.operationaudit.housekeeping.AuditSettings;
|
||||
|
||||
/**
|
||||
* 直写降级测试(技术方案 D2):成功直写、失败降级为 warn 且不抛出。
|
||||
* 直写降级测试(技术方案 D2):成功直写、失败降级为 warn 且不抛出、开关关闭跳过(D6)。
|
||||
*/
|
||||
class AuditRecorderTest {
|
||||
|
||||
private final ReactiveExtensionClient client = mock(ReactiveExtensionClient.class);
|
||||
private final AuditRecorder recorder = new AuditRecorder(client);
|
||||
private ReactiveExtensionClient client;
|
||||
private AuditSettingProvider settingProvider;
|
||||
private AuditRecorder recorder;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
client = mock(ReactiveExtensionClient.class);
|
||||
settingProvider = mock(AuditSettingProvider.class);
|
||||
recorder = new AuditRecorder(client, settingProvider);
|
||||
when(settingProvider.get()).thenReturn(Mono.just(AuditSettings.defaults()));
|
||||
when(client.create(any(AuditLog.class))).thenReturn(Mono.just(new AuditLog()));
|
||||
}
|
||||
|
||||
private RequestSnapshot snapshotOf(String url) {
|
||||
return RequestSnapshot.of(MockServerHttpRequest.post("http://localhost" + url)
|
||||
.remoteAddress(new InetSocketAddress(InetAddress.getLoopbackAddress(), 45678))
|
||||
.build());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldAssembleAndCreateAuditLog() {
|
||||
when(client.create(any(AuditLog.class))).thenReturn(Mono.just(new AuditLog()));
|
||||
var snapshot = RequestSnapshot.of(
|
||||
org.springframework.mock.http.server.reactive.MockServerHttpRequest
|
||||
MockServerHttpRequest
|
||||
.delete("http://localhost/apis/api.content.halo.run/v1alpha1/posts/xyz?foo=bar")
|
||||
.remoteAddress(new java.net.InetSocketAddress(
|
||||
java.net.InetAddress.getLoopbackAddress(), 45678))
|
||||
.remoteAddress(new InetSocketAddress(InetAddress.getLoopbackAddress(), 45678))
|
||||
.header("User-Agent", "UA-1")
|
||||
.build());
|
||||
|
||||
@@ -52,12 +73,7 @@ class AuditRecorderTest {
|
||||
|
||||
@Test
|
||||
void shouldUseUnknownUsernameWhenOperatorMissing() {
|
||||
when(client.create(any(AuditLog.class))).thenReturn(Mono.just(new AuditLog()));
|
||||
var snapshot = RequestSnapshot.of(
|
||||
org.springframework.mock.http.server.reactive.MockServerHttpRequest
|
||||
.post("http://localhost/login").build());
|
||||
|
||||
recorder.record(snapshot, 401, null);
|
||||
recorder.record(snapshotOf("/login"), 401, null);
|
||||
|
||||
var captor = ArgumentCaptor.forClass(AuditLog.class);
|
||||
verify(client).create(captor.capture());
|
||||
@@ -68,24 +84,31 @@ class AuditRecorderTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNotThrowWhenCreateFails() {
|
||||
when(client.create(any(AuditLog.class))).thenReturn(Mono.error(
|
||||
new IllegalStateException("storage unavailable")));
|
||||
var snapshot = RequestSnapshot.of(
|
||||
org.springframework.mock.http.server.reactive.MockServerHttpRequest
|
||||
.post("http://localhost/apis/core.halo.run/v1alpha1/users").build());
|
||||
void shouldSkipRecordingWhenAuditDisabled() {
|
||||
when(settingProvider.get()).thenReturn(Mono.just(new AuditSettings(false, 30)));
|
||||
|
||||
assertThatCode(() -> recorder.record(snapshot, 500, "admin")).doesNotThrowAnyException();
|
||||
recorder.record(snapshotOf("/apis/core.halo.run/v1alpha1/users"), 200, "admin");
|
||||
|
||||
verify(client, never()).create(any(AuditLog.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNotThrowWhenAssemblyFails() {
|
||||
// path 为 null 会在资源解析前返回 other,不会抛异常;这里模拟客户端抛异常场景
|
||||
when(client.create(any(AuditLog.class))).thenThrow(new IllegalStateException("boom"));
|
||||
var snapshot = RequestSnapshot.of(
|
||||
org.springframework.mock.http.server.reactive.MockServerHttpRequest
|
||||
.post("http://localhost/apis/core.halo.run/v1alpha1/users").build());
|
||||
void shouldSkipRecordingWhenSettingsUnavailable() {
|
||||
when(settingProvider.get()).thenReturn(Mono.error(new IllegalStateException("boom")));
|
||||
|
||||
assertThatCode(() -> recorder.record(snapshot, 200, "admin")).doesNotThrowAnyException();
|
||||
assertThatCode(() -> recorder.record(snapshotOf("/apis/core.halo.run/v1alpha1/users"),
|
||||
200, "admin")).doesNotThrowAnyException();
|
||||
|
||||
// 设置读取失败属于降级路径:按默认配置(开启)继续记录
|
||||
verify(client).create(any(AuditLog.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNotThrowWhenCreateFails() {
|
||||
when(client.create(any(AuditLog.class))).thenReturn(Mono.error(
|
||||
new IllegalStateException("storage unavailable")));
|
||||
|
||||
assertThatCode(() -> recorder.record(snapshotOf("/apis/core.halo.run/v1alpha1/users"),
|
||||
500, "admin")).doesNotThrowAnyException();
|
||||
}
|
||||
}
|
||||
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
package run.halo.operationaudit.housekeeping;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import reactor.core.publisher.Mono;
|
||||
import run.halo.app.plugin.ReactiveSettingFetcher;
|
||||
|
||||
/**
|
||||
* 设置 TTL 缓存测试(技术方案 D6):命中缓存、失败/缺省回退默认。
|
||||
*/
|
||||
class AuditSettingProviderTest {
|
||||
|
||||
private final ReactiveSettingFetcher fetcher = mock(ReactiveSettingFetcher.class);
|
||||
private final AuditSettingProvider provider = new AuditSettingProvider(fetcher);
|
||||
|
||||
@Test
|
||||
void shouldCacheWithinTtl() {
|
||||
var fetchCount = new AtomicInteger(0);
|
||||
when(fetcher.fetch(eq(AuditSettings.GROUP), eq(AuditSettings.class)))
|
||||
.thenAnswer(inv -> {
|
||||
fetchCount.incrementAndGet();
|
||||
return Mono.just(new AuditSettings(false, 30));
|
||||
});
|
||||
|
||||
var first = provider.get().block();
|
||||
var second = provider.get().block();
|
||||
|
||||
assertThat(first).extracting(AuditSettings::enabled, AuditSettings::retentionDays)
|
||||
.containsExactly(false, 30);
|
||||
assertThat(second).isSameAs(first);
|
||||
assertThat(fetchCount.get()).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldFallbackToDefaultsWhenFetchFails() {
|
||||
when(fetcher.fetch(eq(AuditSettings.GROUP), eq(AuditSettings.class)))
|
||||
.thenReturn(Mono.error(new IllegalStateException("configmap missing")));
|
||||
|
||||
var settings = provider.get().block();
|
||||
|
||||
assertThat(settings).isEqualTo(AuditSettings.defaults());
|
||||
assertThat(settings.enabledOrDefault()).isTrue();
|
||||
assertThat(settings.retentionDaysOrDefault()).isEqualTo(90);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldFallbackToDefaultsWhenConfigMissing() {
|
||||
when(fetcher.fetch(eq(AuditSettings.GROUP), eq(AuditSettings.class)))
|
||||
.thenReturn(Mono.empty());
|
||||
|
||||
assertThat(provider.get().block()).isEqualTo(AuditSettings.defaults());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldNormalizeIllegalValues() {
|
||||
when(fetcher.fetch(eq(AuditSettings.GROUP), eq(AuditSettings.class)))
|
||||
.thenReturn(Mono.just(new AuditSettings(null, 1)));
|
||||
|
||||
var settings = provider.get().block();
|
||||
|
||||
assertThat(settings.enabledOrDefault()).isTrue();
|
||||
assertThat(settings.retentionDaysOrDefault()).isEqualTo(90);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldRefetchAfterExpiry() {
|
||||
when(fetcher.fetch(eq(AuditSettings.GROUP), eq(AuditSettings.class)))
|
||||
.thenReturn(Mono.just(AuditSettings.defaults()));
|
||||
|
||||
provider.get().block();
|
||||
|
||||
// 手动使缓存过期(TTL 为 60s,等待必然不现实,直接构造过期条目)
|
||||
provider.cache = new AuditSettingProvider.CacheEntry(AuditSettings.defaults(), 0);
|
||||
|
||||
provider.get().block();
|
||||
verify(fetcher, times(2)).fetch(any(), any());
|
||||
}
|
||||
}
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
package run.halo.operationaudit.housekeeping;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import reactor.core.publisher.Mono;
|
||||
import run.halo.app.extension.ListOptions;
|
||||
import run.halo.app.extension.ListResult;
|
||||
import run.halo.app.extension.Metadata;
|
||||
import run.halo.app.extension.PageRequest;
|
||||
import run.halo.app.extension.ReactiveExtensionClient;
|
||||
import run.halo.operationaudit.audit.AuditLog;
|
||||
|
||||
/**
|
||||
* 保留期清理测试(技术方案 D5):批量删除、终止条件、补跑与调度时机。
|
||||
*/
|
||||
class RetentionCleanerTest {
|
||||
|
||||
private static final Instant NOW = Instant.parse("2026-11-21T03:00:00Z");
|
||||
|
||||
private final ReactiveExtensionClient client = mock(ReactiveExtensionClient.class);
|
||||
private final AuditSettingProvider settingProvider = mock(AuditSettingProvider.class);
|
||||
private final Clock fixedClock = Clock.fixed(NOW, ZoneId.of("UTC"));
|
||||
private final RetentionCleaner cleaner =
|
||||
new RetentionCleaner(client, settingProvider, fixedClock);
|
||||
|
||||
private void stubSettings() {
|
||||
when(settingProvider.get()).thenReturn(Mono.just(new AuditSettings(true, 90)));
|
||||
}
|
||||
|
||||
private static AuditLog logAt(Instant creation) {
|
||||
var auditLog = new AuditLog();
|
||||
var metadata = new Metadata();
|
||||
metadata.setName("log-" + creation.toEpochMilli());
|
||||
metadata.setCreationTimestamp(creation);
|
||||
auditLog.setMetadata(metadata);
|
||||
return auditLog;
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldDeleteExpiredInBatchesUntilBelowBatchSize() {
|
||||
stubSettings();
|
||||
// 第一批满 200 条,第二批 50 条 → 删除后停止
|
||||
var batch1 = new ArrayList<AuditLog>();
|
||||
for (int i = 0; i < RetentionCleaner.BATCH_SIZE; i++) {
|
||||
batch1.add(logAt(NOW.minus(Duration.ofDays(100))));
|
||||
}
|
||||
var batch2 = List.of(
|
||||
logAt(NOW.minus(Duration.ofDays(95))),
|
||||
logAt(NOW.minus(Duration.ofDays(91))));
|
||||
when(client.listBy(eq(AuditLog.class), any(ListOptions.class), any(PageRequest.class)))
|
||||
.thenReturn(Mono.just(new ListResult<>(1, 200, 250L, batch1)))
|
||||
.thenReturn(Mono.just(new ListResult<>(1, 200, 50L, batch2)));
|
||||
when(client.delete(any(AuditLog.class))).thenReturn(Mono.just(new AuditLog()));
|
||||
|
||||
var deleted = cleaner.cleanOnce().block();
|
||||
|
||||
assertThat(deleted).isEqualTo((long) RetentionCleaner.BATCH_SIZE + batch2.size());
|
||||
verify(client, org.mockito.Mockito.times(2))
|
||||
.listBy(eq(AuditLog.class), any(ListOptions.class), any(PageRequest.class));
|
||||
ArgumentCaptor<ListOptions> optionsCaptor = ArgumentCaptor.forClass(ListOptions.class);
|
||||
verify(client, org.mockito.Mockito.times(2))
|
||||
.listBy(eq(AuditLog.class), optionsCaptor.capture(), any(PageRequest.class));
|
||||
// 过期边界:creationTimestamp <= now - 90d(含边界)
|
||||
assertThat(optionsCaptor.getValue().toCondition().toString())
|
||||
.contains("metadata.creationTimestamp")
|
||||
.contains("2026-08-23T03:00:00Z");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldDoNothingWhenNoExpiredRecords() {
|
||||
stubSettings();
|
||||
when(client.listBy(eq(AuditLog.class), any(ListOptions.class), any(PageRequest.class)))
|
||||
.thenReturn(Mono.just(new ListResult<>(1, 200, 0L, List.of())));
|
||||
|
||||
var deleted = cleaner.cleanOnce().block();
|
||||
|
||||
assertThat(deleted).isZero();
|
||||
verify(client, never()).delete(any(AuditLog.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldUseRetentionDaysFromSettings() {
|
||||
when(settingProvider.get()).thenReturn(Mono.just(new AuditSettings(true, 7)));
|
||||
when(client.listBy(eq(AuditLog.class), any(ListOptions.class), any(PageRequest.class)))
|
||||
.thenReturn(Mono.just(new ListResult<>(1, 200, 0L, List.of())));
|
||||
|
||||
cleaner.cleanOnce().block();
|
||||
|
||||
var optionsCaptor = ArgumentCaptor.forClass(ListOptions.class);
|
||||
verify(client).listBy(any(), optionsCaptor.capture(), any(PageRequest.class));
|
||||
// cutoff = now - 7d
|
||||
assertThat(optionsCaptor.getValue().toCondition().toString())
|
||||
.contains("2026-11-14T03:00:00Z");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldScheduleNextRunAtThreeAm() {
|
||||
// 固定时钟:2026-11-21 05:00 UTC → 下一次执行为次日 03:00
|
||||
var clock = Clock.fixed(Instant.parse("2026-11-21T05:00:00Z"), ZoneId.of("UTC"));
|
||||
var cleaner = new RetentionCleaner(client, settingProvider, clock);
|
||||
|
||||
var delay = cleaner.delayUntilNextRun();
|
||||
|
||||
assertThat(delay).isEqualTo(Duration.ofHours(22));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldScheduleLaterTodayIfBeforeThreeAm() {
|
||||
var clock = Clock.fixed(Instant.parse("2026-11-21T01:30:00Z"), ZoneId.of("UTC"));
|
||||
var cleaner = new RetentionCleaner(client, settingProvider, clock);
|
||||
|
||||
var delay = cleaner.delayUntilNextRun();
|
||||
|
||||
assertThat(delay).isEqualTo(Duration.ofMinutes(90));
|
||||
}
|
||||
|
||||
@Test
|
||||
void startShouldRunCleanupImmediatelyThenSchedule() {
|
||||
stubSettings();
|
||||
when(client.listBy(eq(AuditLog.class), any(ListOptions.class), any(PageRequest.class)))
|
||||
.thenReturn(Mono.just(new ListResult<>(1, 200, 0L, List.of())));
|
||||
|
||||
cleaner.start();
|
||||
try {
|
||||
// 补跑一次(start 内 fire-and-forget 订阅)
|
||||
verify(client, org.mockito.Mockito.timeout(1000))
|
||||
.listBy(eq(AuditLog.class), any(ListOptions.class), any(PageRequest.class));
|
||||
} finally {
|
||||
cleaner.stop();
|
||||
}
|
||||
// 调度任务已注册并可停止(不阻塞测试)
|
||||
var now = LocalDateTime.now();
|
||||
assertThat(now).isNotNull();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user