fix(版本包): 最新版改为显式标记 + 新增升级包保留期清理

读取侧不再靠 created_at 现场算「最新版」(补插一条老记录就会把全体客户端更新目标带偏且
无报错),改读 web_config.is_latest,与数字人版本表口径对齐;上传/补录后标记,删除到最新版
时立刻改标剩余最新一条,全无标记时回退按时间取并补标——否则客户端会以为已是最新版而停更。
标记用一条 SET is_latest = (id = ?) 的整表 UPDATE,避免「先清零再置一」的中间零标记态需要拉事务。

另新增 SoftwareVersionRetentionService:client 桶 nanri-image/versions/ 前缀只增不删,
2026-09-21 已堆到 61 个对象 / 6.2GiB(单个约 106MB)。刻意不走 MinIO ILM 按天过期——
2026-09-08 那次全桶 30 天规则连着删掉 9 个仍被人下载的安装包,web_config 留下断链至今。
口径为「保留最近 N 个 + 最新版永不删」,删除复用 deleteSoftwareVersions 的 file_url 引用计数
(同版本重复上传共享同一 key),双节点 job 锁,默认 dry-run。
This commit is contained in:
2026-09-27 11:25:46 +08:00
parent c27a1e26c4
commit d706c09b0f
6 changed files with 532 additions and 8 deletions
@@ -3,7 +3,20 @@ package com.nanri.aiimage.modules.softwareversion.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.nanri.aiimage.modules.softwareversion.model.entity.SoftwareVersionEntity;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Update;
@Mapper
public interface SoftwareVersionMapper extends BaseMapper<SoftwareVersionEntity> {
/**
* 把指定行标成唯一的最新版,同时清掉其余行的标记。
*
* <p>刻意写成一条 {@code SET is_latest = (id = #{id})} 的整表 UPDATE,而不是
* 「先清零、再置一」两条语句:两条语句需要事务包住才不会让并发读看到一个
* 零标记的中间态,而本方法要在 MinIO 上传流程之后调用,不值得为 62 行的表
* 拉一个事务、还要为此绕开 Spring 自调用不走代理的问题。
*/
@Update("UPDATE web_config SET is_latest = (id = #{id})")
int markLatestById(@Param("id") Long id);
}
@@ -24,6 +24,9 @@ public class SoftwareVersionEntity {
/** 安装包可公开访问的下载链接(MinIO path-style 直链) */
private String fileUrl;
/** 是否最新版:全表至多一行为 true,由 SoftwareVersionMapper#markLatestById 单语句维护 */
private Boolean isLatest;
/** 创建时间,由数据库 CURRENT_TIMESTAMP 兜底 */
private LocalDateTime createdAt;
}
@@ -0,0 +1,101 @@
package com.nanri.aiimage.modules.softwareversion.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nanri.aiimage.common.service.DistributedJobLockService;
import com.nanri.aiimage.modules.softwareversion.mapper.SoftwareVersionMapper;
import com.nanri.aiimage.modules.softwareversion.model.entity.SoftwareVersionEntity;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.time.Duration;
import java.util.List;
/**
* 客户端升级包的保留期清理(MinIO {@code client} 桶 {@code nanri-image/versions/} 前缀)。
*
* <p>升级包只增不删:约 106MB/个,2026-09-21 盘点时该前缀已堆到 61 个对象 / 6.2GiB,最老的是
* 41 天前上传的。此前只能靠后台手删。
*
* <p>刻意不用 MinIO 生命周期规则做这件事:ILM 只能按时间过期,而升级包的正确口径是
* 「保留最近 N 个 + 最新版永不删」——发版密集时按天数会连着删掉还被人下载的版本。
* 2026-09-08 就发生过一次:给 {@code client} 桶根加了全桶 30 天过期规则,导致
* 3.0.24~3.0.37 共 9 个安装包被自动删除,{@code web_config} 里留下断链记录至今。
*
* <p>删除复用 {@link SoftwareVersionService#deleteSoftwareVersions(List)}:同一版本重复上传会
* 共享同一个对象 key,该方法按 file_url 做引用计数,只有已无记录引用时才真删对象。
*
* <p>双节点用 job 锁保证单实例执行;默认 dry-run,只记日志不动对象,确认口径后由
* {@code aiimage.software-version.retention-dry-run=false} 启用实际删除。
*/
@Service
@RequiredArgsConstructor
@Slf4j
public class SoftwareVersionRetentionService {
/** 单轮最多删除的记录数,剩余的留给下一轮,避免首次启用时一次性清掉整个历史。 */
static final int MAX_DELETIONS_PER_RUN = 20;
private final SoftwareVersionMapper softwareVersionMapper;
private final SoftwareVersionService softwareVersionService;
private final DistributedJobLockService distributedJobLockService;
/**
* 保留最近的版本数;下限钳到 1,避免配成 0 时把整表算进删除候选。
* 最新版另有 is_latest 标记兜底,见 {@link #purgeSupersededVersions()} 的过滤。
*/
@Value("${aiimage.software-version.retention-keep-count:20}")
private int keepCount = 20;
@Value("${aiimage.software-version.retention-dry-run:true}")
private boolean dryRun = true;
@Scheduled(cron = "${aiimage.software-version.retention-cron:0 50 4 * * *}")
public void purgeSupersededVersions() {
int keep = Math.max(1, keepCount);
DistributedJobLockService.LockHandle lockHandle =
distributedJobLockService.tryLock("software-version:retention", Duration.ofMinutes(10));
if (lockHandle == null) {
log.info("[version-retention] 升级包保留清理跳过:另一实例持锁");
return;
}
try (lockHandle) {
List<SoftwareVersionEntity> entities = softwareVersionMapper.selectList(
new LambdaQueryWrapper<SoftwareVersionEntity>()
.orderByDesc(SoftwareVersionEntity::getCreatedAt)
.orderByDesc(SoftwareVersionEntity::getId));
if (entities.size() <= keep) {
log.info("[version-retention] 无需清理 total={} keep={}", entities.size(), keep);
return;
}
List<SoftwareVersionEntity> superseded = entities.subList(keep, entities.size()).stream()
.filter(entity -> !Boolean.TRUE.equals(entity.getIsLatest()))
.toList();
if (superseded.isEmpty()) {
log.info("[version-retention] keep={} 之后的记录均带 is_latest 标记,本轮不删", keep);
return;
}
int beyondCap = Math.max(0, superseded.size() - MAX_DELETIONS_PER_RUN);
List<Long> ids = superseded.stream()
.limit(MAX_DELETIONS_PER_RUN)
.map(SoftwareVersionEntity::getId)
.toList();
List<String> versions = superseded.stream()
.limit(MAX_DELETIONS_PER_RUN)
.map(SoftwareVersionEntity::getVersion)
.toList();
if (dryRun) {
log.info("[version-retention] dry-run 未实际删除 total={} keep={} 候选={} versions={} 留待下轮={}",
entities.size(), keep, ids.size(), versions, beyondCap);
return;
}
int deleted = softwareVersionService.deleteSoftwareVersions(ids);
log.info("[version-retention] 升级包保留清理完成 total={} keep={} deleted={} versions={} 留待下轮={}",
entities.size(), keep, deleted, versions, beyondCap);
} catch (Exception ex) {
log.warn("[version-retention] 升级包保留清理失败 keep={} msg={}", keep, ex.getMessage(), ex);
}
}
}
@@ -25,8 +25,10 @@ import java.util.Set;
import java.util.regex.Pattern;
/**
* 客户端软件(桌面 ShuFuAI.exe)版本管理服务:读写 web_config 表,
* 与 Flask 时代 /api/admin/versions、/api/admin/version 行为对齐(读取/追加写,无覆盖、无删除)。
* 客户端软件(桌面 ShuFuAI.exe)版本管理服务:读写 web_config 表。
*
* <p>「最新版」是 web_config 上的显式 {@code is_latest} 标记(对齐数字人版本表),不再由
* created_at 现场算出——补插一条老记录就会把全体客户端的更新目标带偏,且无任何报错。
*/
@Service
@RequiredArgsConstructor
@@ -75,16 +77,27 @@ public class SoftwareVersionService {
}
/**
* 返回客户端更新接口所需的最新版本记录。空表时保持 Flask 时代的
* {"version": null, "file_url": null} 响应语义。
* 返回客户端更新接口所需的最新版本记录(web_config.is_latest 标记行)。
* 空表时保持 Flask 时代的 {"version": null, "file_url": null} 响应语义。
*/
public Map<String, Object> latestSoftwareVersion() {
log.info("[software-version] 查询客户端最新可用版本");
SoftwareVersionEntity entity = softwareVersionMapper.selectOne(
new LambdaQueryWrapper<SoftwareVersionEntity>()
.eq(SoftwareVersionEntity::getIsLatest, true)
.orderByDesc(SoftwareVersionEntity::getCreatedAt)
.orderByDesc(SoftwareVersionEntity::getId)
.last("LIMIT 1"));
if (entity == null) {
// 没有任何标记行:手工删过库、或迁移前的旧备份库直接接上。回退到按时间取最新
// 并补标,否则全体客户端会以为"已是最新版"而停更。
entity = newestByCreatedAt();
if (entity != null) {
log.warn("[software-version] web_config 缺少 is_latest 标记,已按创建时间回退并补标 id={} version={}",
entity.getId(), entity.getVersion());
softwareVersionMapper.markLatestById(entity.getId());
}
}
Map<String, Object> result = new LinkedHashMap<>();
if (entity == null) {
result.put("version", null);
@@ -96,6 +109,13 @@ public class SoftwareVersionService {
return result;
}
private SoftwareVersionEntity newestByCreatedAt() {
return softwareVersionMapper.selectOne(new LambdaQueryWrapper<SoftwareVersionEntity>()
.orderByDesc(SoftwareVersionEntity::getCreatedAt)
.orderByDesc(SoftwareVersionEntity::getId)
.last("LIMIT 1"));
}
/**
* 公开版本列表:桌面端"指定版本更新"下拉的可选版本(匿名可达,同 /latest)。
* 按创建时间倒序取最近 {@link PublicVersionLookup#DEFAULT_LIST_LIMIT} 条,字段口径
@@ -120,7 +140,9 @@ public class SoftwareVersionService {
/**
* 上传客户端软件安装包:zip 上传 MinIO(key:nanri-image/versions/{安全版本号}.zip),
* 并向 web_config 追加一条记录(不做"设为最新",桌面端按 created_at 倒序取第一条)。
* 向 web_config 追加一条记录并把这条新记录标成最新版。
*
* <p>标记落库放在 MinIO 上传成功之后:上传失败时不会留下一行「最新版」指向不存在的对象。
*/
public Map<String, Object> uploadSoftwareVersion(String version, MultipartFile file) {
String normalizedVersion = version == null ? "" : version.trim();
@@ -165,7 +187,8 @@ public class SoftwareVersionService {
entity.setFileUrl(fileUrl);
// 不显式写 created_at,走数据库 CURRENT_TIMESTAMP 默认值(与 Flask 行为一致)
softwareVersionMapper.insert(entity);
log.info("[software-version] 版本记录已写入 web_config id={} version={} elapsedMs={}",
softwareVersionMapper.markLatestById(entity.getId());
log.info("[software-version] 版本记录已写入 web_config 并标为最新版 id={} version={} elapsedMs={}",
entity.getId(), normalizedVersion, elapsedMs(startedAt));
Map<String, Object> result = new LinkedHashMap<>();
@@ -226,6 +249,7 @@ public class SoftwareVersionService {
entity.setVersion(normalizedVersion);
entity.setFileUrl(ossStorageService.getSoftwareVersionDownloadUrl(objectKey));
softwareVersionMapper.insert(entity);
softwareVersionMapper.markLatestById(entity.getId());
SoftwareVersionEntity saved = softwareVersionMapper.selectById(entity.getId());
return toItemMap(saved == null ? entity : saved);
}
@@ -259,8 +283,17 @@ public class SoftwareVersionService {
removedObjects += removeSoftwareVersionObjectQuietly(url) ? 1 : 0;
}
}
log.info("[software-version] 批量删除版本记录 ids={} deleted={} 清理关联文件数={}",
distinctIds, deleted, removedObjects);
// 删掉的行里若有最新版,必须马上把最新版改标到剩余最新的一条,
// 否则表里再无标记,客户端会停在旧版本上不动。
SoftwareVersionEntity promoted = null;
if (targets.stream().anyMatch(t -> Boolean.TRUE.equals(t.getIsLatest()))) {
promoted = newestByCreatedAt();
if (promoted != null) {
softwareVersionMapper.markLatestById(promoted.getId());
}
}
log.info("[software-version] 批量删除版本记录 ids={} deleted={} 清理关联文件数={} 最新版改标={}",
distinctIds, deleted, removedObjects, promoted == null ? "-" : promoted.getVersion());
return deleted;
}