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:
+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