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:
+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();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user