refactor(evidence): 任务证据特性整体下线(2026-11-17 用户拍板)

删 modules/evidence 10 件+EvidenceProperties 注册+application*.yml evidence 块+V205 迁移(DELETE 菜单行+DROP biz_task_evidence);后管 TaskEvidencePage/task-evidence/路由/菜单键/操作指南同步摘除;chunk 分片通道、崩溃记录器本体与设备日志链保留(BACKLOG B115)。
This commit is contained in:
2026-11-17 01:18:49 +08:00
parent aff6c88a7d
commit 71b19e4f69
25 changed files with 40 additions and 1803 deletions
@@ -42,8 +42,6 @@ class PageDefaultsLedgerTest {
* 54 条,逐条对应一次真实翻页行为;加页要登记,改值要表态。
*/
private static final List<String> LEDGER = List.of(
"AdminTaskEvidenceController.java#page=FIRST_PAGE",
"AdminTaskEvidenceController.java#pageSize=ADMIN_LIST_PAGE_SIZE",
"AdminUserController.java#page=FIRST_PAGE",
"AdminUserController.java#page_size=USER_LIST_PAGE_SIZE",
"AdminUserApiSecretController.java#page=FIRST_PAGE",
@@ -121,14 +119,15 @@ class PageDefaultsLedgerTest {
List<String> constants = actual.stream().filter(s -> !s.contains("LITERAL")).sorted().toList();
assertThat(constants)
.as("60 处分页/条数出站点的具名默认值必须与台账一一对应"
.as("分页/条数出站点的具名默认值必须与台账一一对应"
+ "(58→60:v1.4 Phase 5 京东数据库后管只读页 AdminJdProductController 的"
+ " page/page_size 两处出站点)")
+ " page/page_size 两处出站点;60→59:2026-11-17 任务证据特性下线,"
+ " AdminTaskEvidenceController 两处出站点随控制器删除)")
.isEqualTo(LEDGER.stream().sorted().toList());
// 同口径非零对照:台账不是空的,扫描器也确实数得出 61 处
// 同口径非零对照:台账不是空的,扫描器也确实数得出 59 处
// (61 而不是 60:2026-11-15 京东任务面板改版(45d0989a)新增 GET /api/jd-collect/history
// 的 limit 出站点,台账同步登记 58→60→61)
assertThat(constants).hasSize(61);
// 的 limit 出站点,台账同步登记 58→60→61;61→59:任务证据特性下线随删两处)
assertThat(constants).hasSize(59);
}
@Test
@@ -143,8 +142,9 @@ class PageDefaultsLedgerTest {
void oneSemanticCannotGrowASecondDefault() {
List<String> actual = sites();
assertThat(kindsUsing(actual, "page", "FIRST_PAGE"))
.as("页码口径只有一套:全部从 1 起(26→27:v1.4 Phase 5 京东数据库只读页也是分页出站点)")
.isEqualTo(27);
.as("页码口径只有一套:全部从 1 起(26→27:v1.4 Phase 5 京东数据库只读页也是分页出站点;"
+ "27→26:2026-11-17 任务证据特性下线随删一处)")
.isEqualTo(26);
assertThat(distinctConstants(actual, "page_size"))
.as("page_size 的默认容量集合:10/15/20/50/1000 各自登记(20 有两把名字:超管台 "
+ "ADMIN_LIST_PAGE_SIZE 与 v1.4 京东数据库 JD_PRODUCTS_PAGE_SIZE),新语义要红")
@@ -128,8 +128,10 @@ class SuperAdminPredicateSingleOutletTest {
// 20 -> 22:v1.4 Phase 5 京东数据库读取面——AdminJdProductController#requireJdDatabaseAccess
// 与 AdminJdProductGroupController#requireJdDatabaseAccess 两处超管直通
// (2026-11-14 整量回归补记,同 AdminTaskEvidenceController 先例)。
// 22 -> 21:任务证据特性整体下线(2026-11-17 用户拍板),AdminTaskEvidenceController
// 连同模块删除,该出口随之消失。
.as("走出口的调用点数:17 个业务调用方 + DataReadScope 包装体(新增调用要一起改这个数字,别改回字面量)")
.isEqualTo(22);
.isEqualTo(21);
// 自检:这三把尺子的锚点必须真落在预期的文件里,否则"恰好也是 N"可能是扫错地方凑出来的
assertThat(read(mainRoot().resolve("common/security/DeviceSessionPolicy.java")))
.contains("public static boolean isSuper(String resolvedRole)");
@@ -1,419 +0,0 @@
package com.nanri.aiimage.modules.evidence;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.common.security.DeviceSessionPolicy;
import jakarta.servlet.http.HttpServletRequest;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* AC-7/AC-13/AC-14(R3):证据件上云后的服务端落点与访问面契约。
*
* <p>Pending Phase 3 激活。Phase 0 预置的判据(接缝名是判据的一部分,改名必须同步改本文件
* 并在蓝图 §5 登记):</p>
*
* <ul>
* <li>Flyway {@code V182+} 新增 {@code biz_task_evidence}:task_id/uid/evidence_type/source/
* object_key/byte_size/content_type/sha256/created_at,按 task_id 关联但**不建外键**;</li>
* <li>{@code application.yml} 的 {@code evidence:} 块显式落 bucket(独立桶,不得为
* nanri-ai-images)、retention-days(必须有数字默认值)、key-prefix;</li>
* <li>证据读取端点落在 {@code /api/admin/task-evidence/**}(files/content/download/delete),
* 每个方法都走私有 {@code requireSuperAdmin(HttpServletRequest)}(对齐
* {@code AdminDeviceLogController:167-175});</li>
* <li>守卫行为三样本:无 token/bad token → 401、非超管 → 403、超管 → 放行;伪造 uid 由
* files 端点的 uid 归属校验兜住(源码判据);</li>
* <li>证据模块日志零命中 presign / 直链(AC-13);对象 key 带 UUID(铁律 10)。</li>
* </ul>
*
* <p>四样本中的「合法 JWT 200」在 Phase 3 由真机/集成用例补齐(本文件钉守卫放行分支,
* 蓝图 Phase 3 准出另见 {@code 鉴权四样本真机留痕})。</p>
*/
class EvidencePhase3ContractTest {
private static final Path MODULE = Path.of("").toAbsolutePath();
private static final Path MAIN_JAVA = MODULE.resolve("src/main/java");
private static final Path DB_DIR = MODULE.resolve("src/main/resources/db");
private static final Path APP_YML = MODULE.resolve("src/main/resources/application.yml");
private static final String CONTROLLER_FQCN =
"com.nanri.aiimage.modules.evidence.controller.AdminTaskEvidenceController";
private static final String EVIDENCE_PATH = "/api/admin/task-evidence";
@Test
void 迁移必须新增证据表且字段与索引齐全() throws IOException {
List<Path> migrations = new ArrayList<>();
try (Stream<Path> stream = Files.list(DB_DIR)) {
stream.filter(path -> path.getFileName().toString().matches("V\\d+__.*\\.sql"))
.filter(path -> versionOf(path.getFileName().toString()) >= 182)
.forEach(migrations::add);
}
assertFalse(migrations.isEmpty(), "AC-7:本迭代必须新增 V182+ 迁移(当前最高 V181)");
StringBuilder joined = new StringBuilder();
for (Path migration : migrations) {
joined.append(read(migration)).append('\n');
}
String all = joined.toString();
Matcher table = Pattern.compile("(?is)create\\s+table[^;]*biz_task_evidence[^;]*;")
.matcher(all);
assertTrue(table.find(), "AC-7:V182+ 必须建 biz_task_evidence 表(蓝图 §3.3)");
String ddl = table.group();
for (String column : List.of("task_id", "uid", "evidence_type", "source", "object_key",
"byte_size", "content_type", "sha256", "created_at")) {
assertTrue(Pattern.compile("(?i)\\b" + column + "\\b").matcher(ddl).find(),
"AC-7:证据表缺列 " + column);
}
assertFalse(ddl.toUpperCase().contains("FOREIGN KEY"),
"AC-7:证据表按 task_id 关联但不建外键(全库唯一 FK 是 V80:47)");
assertTrue(Pattern.compile("(?i)(index|key)\\s+\\w+\\s*\\(\\s*task_id").matcher(ddl).find(),
"AC-7:必须有 task_id 索引(按任务关联查询)");
assertTrue(Pattern.compile("(?i)(index|key)\\s+\\w+\\s*\\(\\s*uid").matcher(ddl).find(),
"AC-7:必须有 uid 索引(数据范围/清理)");
}
@Test
void 证据桶与保留期必须显式落在applicationYml() throws IOException {
String yaml = read(APP_YML);
String block = yamlBlock(yaml, "evidence");
assertNotNull(block, "AC-13:application.yml 必须有 evidence: 配置块(不许只落代码默认值)");
String bucket = scalar(block, "bucket");
assertNotNull(bucket, "AC-13:必须配置证据桶");
String bucketDefault = defaultValue(bucket);
assertNotNull(bucketDefault, "AC-13:证据桶不得只有变量无默认值(部署漏配即隐形)");
assertFalse(bucketDefault.contains("nanri-ai-images"),
"AC-13:证据必须落独立桶,不得复用业务桶 nanri-ai-images");
String retention = scalar(block, "retention-days");
assertNotNull(retention, "AC-13:必须配置保留天数");
String retentionDefault = defaultValue(retention);
assertNotNull(retentionDefault, "AC-13:保留天数必须有确定的数字默认值(天数要进判据)");
assertTrue(Integer.parseInt(retentionDefault) >= 1, "AC-13:保留天数必须为正整数");
assertNotNull(scalar(block, "key-prefix"), "AC-13:必须配置对象 key 前缀");
}
@Test
void 证据读取端点必须全部走super访问面() throws IOException {
Path controller = evidenceController();
String source = read(controller);
assertTrue(source.contains(EVIDENCE_PATH),
"AC-13:证据读取控制器必须落在 " + EVIDENCE_PATH);
List<String> bodies = mappedMethodBodies(source);
assertTrue(bodies.size() >= 4,
"AC-13:证据读取至少要有 files/content/download/delete 四个端点,实扫 " + bodies.size());
for (String body : bodies) {
assertTrue(body.contains("requireSuperAdmin"),
"AC-13:证据读取端点必须逐个走 requireSuperAdmin(非 super 一律 403)\n" + body);
}
assertTrue(source.contains("isSuper"),
"AC-13:超管判定必须复用 DeviceSessionPolicy.isSuper 单出口");
assertFalse(source.toLowerCase().contains("permitall"),
"AC-13:证据读取端点不得 permitAll");
for (String endpoint : List.of("\"/files\"", "\"/content\"", "\"/download\"", "\"/delete\"")) {
assertTrue(source.contains(endpoint), "AC-13:缺端点 " + endpoint);
}
String filesBody = bodies.get(0);
assertTrue(filesBody.contains("uid"),
"AC-13:列表端点必须支持按 uid 收窄(伪造 uid 的归属校验入口)");
assertTrue(filesBody.contains("operator") || filesBody.contains("getId"),
"AC-13:uid 过滤必须与当前操作者归属对撞(防伪造 uid 越权读)");
}
@Test
void 守卫行为三样本_无token坏token401_非超管403_超管放行() throws Exception {
Object controller = newEvidenceController();
AdminAuthSupport auth = authSupportOf(controller);
Method guard = superAdminGuard(controller.getClass());
HttpServletRequest request = mock(HttpServletRequest.class);
when(auth.requireAdmin(any(HttpServletRequest.class)))
.thenThrow(new BusinessException(401, "未登录"));
Throwable noToken = invoke(guard, controller, request);
assertInstanceOf(BusinessException.class, noToken, "AC-13:无 token 必须 401");
assertEquals(Integer.valueOf(401), ((BusinessException) noToken).getCode());
when(auth.requireAdmin(any(HttpServletRequest.class)))
.thenThrow(new BusinessException(401, "登录已过期,请重新登录"));
Throwable badToken = invoke(guard, controller, request);
assertInstanceOf(BusinessException.class, badToken, "AC-13:坏 token 必须 401");
assertEquals(Integer.valueOf(401), ((BusinessException) badToken).getCode());
AdminUserEntity normalAdmin = new AdminUserEntity();
normalAdmin.setId(2L);
normalAdmin.setUsername("ops-admin");
normalAdmin.setRole("admin");
normalAdmin.setIsAdmin(1);
when(auth.requireAdmin(any(HttpServletRequest.class))).thenReturn(normalAdmin);
when(auth.currentRole(normalAdmin)).thenReturn("admin");
Throwable forbidden = invoke(guard, controller, request);
assertInstanceOf(BusinessException.class, forbidden, "AC-13:非超管必须 403");
assertEquals(Integer.valueOf(403), ((BusinessException) forbidden).getCode());
AdminUserEntity superAdmin = new AdminUserEntity();
superAdmin.setId(1L);
superAdmin.setUsername("root");
superAdmin.setRole(DeviceSessionPolicy.SUPER_ADMIN);
superAdmin.setIsAdmin(1);
when(auth.requireAdmin(any(HttpServletRequest.class))).thenReturn(superAdmin);
when(auth.currentRole(superAdmin)).thenReturn(DeviceSessionPolicy.SUPER_ADMIN);
Object returned = guard.invoke(controller, request);
assertSame(superAdmin, returned, "AC-13:超管必须放行并返回操作者");
}
@Test
void 登记必须按taskId关联且对象key带uuid() throws IOException {
String all = evidenceSources();
assertTrue(Pattern.compile("(?i)task[_-]?id").matcher(all).find(),
"AC-7:证据登记/落表必须按 taskId 关联");
assertTrue(all.contains("objectKey") || all.contains("object_key"),
"AC-7:登记必须记录 objectKey");
assertTrue(all.contains("UUID"),
"AC-13(铁律 10):对象 key 必须带 UUID");
assertTrue(all.contains("sha256") || all.contains("SHA-256"),
"AC-7:登记必须带摘要(防篡改/去重)");
}
@Test
void 证据模块日志零命中presign与直链() throws IOException {
List<Path> files = new ArrayList<>();
try (Stream<Path> stream = Files.walk(MAIN_JAVA)) {
stream.filter(path -> path.toString().endsWith(".java"))
.filter(EvidencePhase3ContractTest::isEvidenceSource)
.forEach(files::add);
}
assertFalse(files.isEmpty(), "AC-13:未找到证据模块源码(命名/落点未按契约)");
List<String> leaks = new ArrayList<>();
for (Path file : files) {
for (String line : read(file).split("\\R")) {
String lower = line.toLowerCase();
boolean logLine = lower.contains("log.info") || lower.contains("log.warn")
|| lower.contains("log.error") || lower.contains("log.debug");
boolean urlLike = lower.contains("presign") || lower.contains("uploadurl")
|| lower.contains("fileurl") || lower.contains("http://")
|| lower.contains("https://");
if (logLine && urlLike) {
leaks.add(file.getFileName() + ": " + line.trim());
}
}
}
assertTrue(leaks.isEmpty(), "AC-13:证据模块日志输出了 presign/直链:\n" + String.join("\n", leaks));
}
// ---------------------------------------------------------------- helpers
private static Path evidenceController() throws IOException {
List<Path> hits = new ArrayList<>();
try (Stream<Path> stream = Files.walk(MAIN_JAVA)) {
stream.filter(path -> path.toString().endsWith(".java"))
.filter(path -> {
try {
return read(path).contains(EVIDENCE_PATH);
} catch (IOException ex) {
return false;
}
})
.forEach(hits::add);
}
assertFalse(hits.isEmpty(),
"AC-13:未找到 " + EVIDENCE_PATH + " 的控制器源码(Phase 3 落点未按契约)");
return hits.get(0);
}
private static boolean isEvidenceSource(Path path) {
try {
String source = read(path);
return source.contains("task-evidence") || source.contains("TaskEvidence")
|| source.contains("biz_task_evidence");
} catch (IOException ex) {
return false;
}
}
private static String evidenceSources() throws IOException {
List<Path> files = new ArrayList<>();
try (Stream<Path> stream = Files.walk(MAIN_JAVA)) {
stream.filter(path -> path.toString().endsWith(".java"))
.filter(EvidencePhase3ContractTest::isEvidenceSource)
.forEach(files::add);
}
assertFalse(files.isEmpty(), "AC-7:未找到证据模块源码");
StringBuilder builder = new StringBuilder();
for (Path file : files) {
builder.append(read(file)).append('\n');
}
return builder.toString();
}
private static Object newEvidenceController() throws Exception {
Class<?> controllerClass = Class.forName(CONTROLLER_FQCN);
Constructor<?> constructor = Arrays.stream(controllerClass.getDeclaredConstructors())
.max(Comparator.comparingInt(candidate -> candidate.getParameterCount()))
.orElseThrow();
Class<?>[] types = constructor.getParameterTypes();
Object[] args = new Object[types.length];
for (int index = 0; index < types.length; index++) {
if (types[index].isPrimitive()) {
fail("AC-13:控制器构造器不应有原始类型参数: " + types[index]);
}
args[index] = AdminAuthSupport.class.isAssignableFrom(types[index])
? mock(AdminAuthSupport.class)
: mock(types[index]);
}
constructor.setAccessible(true);
return constructor.newInstance(args);
}
private static AdminAuthSupport authSupportOf(Object controller) throws IllegalAccessException {
for (java.lang.reflect.Field field : controller.getClass().getDeclaredFields()) {
if (AdminAuthSupport.class.isAssignableFrom(field.getType())) {
field.setAccessible(true);
return (AdminAuthSupport) field.get(controller);
}
}
fail("AC-13:证据控制器必须注入 AdminAuthSupport(与 AdminDeviceLogController 同口径)");
return null;
}
private static Method superAdminGuard(Class<?> controllerClass) {
for (Method method : controllerClass.getDeclaredMethods()) {
if (method.getName().equals("requireSuperAdmin")
&& method.getParameterCount() == 1
&& method.getParameterTypes()[0].isAssignableFrom(HttpServletRequest.class)) {
method.setAccessible(true);
return method;
}
}
throw new AssertionError(
"AC-13:证据控制器必须含私有 requireSuperAdmin(HttpServletRequest)(对齐 AdminDeviceLogController:167-175)");
}
private static Throwable invoke(Method method, Object target, Object... args) throws Exception {
try {
method.invoke(target, args);
return null;
} catch (InvocationTargetException ex) {
return ex.getTargetException();
}
}
private static List<String> mappedMethodBodies(String source) {
String[] lines = source.split("\\R");
Pattern mapping = Pattern.compile("@(Get|Post|Put|Delete|Patch)Mapping");
List<String> bodies = new ArrayList<>();
for (int index = 0; index < lines.length; index++) {
if (!mapping.matcher(lines[index]).find()) {
continue;
}
int cursor = index;
while (cursor < lines.length && !lines[cursor].contains("{") && !lines[cursor].contains(";")) {
cursor++;
}
if (cursor >= lines.length || lines[cursor].contains(";")) {
continue;
}
int depth = 0;
StringBuilder body = new StringBuilder();
for (int line = cursor; line < lines.length; line++) {
for (char ch : lines[line].toCharArray()) {
if (ch == '{') {
depth++;
} else if (ch == '}') {
depth--;
}
}
body.append(lines[line]).append('\n');
if (depth == 0) {
break;
}
}
bodies.add(body.toString());
index = cursor;
}
return bodies;
}
private static String yamlBlock(String yaml, String key) {
String[] lines = yaml.split("\\R");
Pattern header = Pattern.compile("^(\\s*)" + Pattern.quote(key) + ":\\s*$");
int start = -1;
int indent = -1;
for (int index = 0; index < lines.length; index++) {
Matcher matcher = header.matcher(lines[index]);
if (matcher.matches()) {
start = index;
indent = matcher.group(1).length();
break;
}
}
if (start < 0) {
return null;
}
StringBuilder block = new StringBuilder();
for (int index = start + 1; index < lines.length; index++) {
String line = lines[index];
if (line.trim().isEmpty() || line.trim().startsWith("#")) {
block.append(line).append('\n');
continue;
}
int currentIndent = line.length() - line.replaceAll("^\\s+", "").length();
if (currentIndent <= indent) {
break;
}
block.append(line).append('\n');
}
return block.toString();
}
private static String scalar(String block, String key) {
Matcher matcher = Pattern.compile("(?m)^\\s*" + Pattern.quote(key) + ":\\s*(\\S.*)$")
.matcher(block);
return matcher.find() ? matcher.group(1).trim() : null;
}
private static String defaultValue(String value) {
Matcher env = Pattern.compile("^\\$\\{[^:}]+:([^}]*)\\}$").matcher(value);
if (env.matches()) {
String fallback = env.group(1).trim();
return fallback.isEmpty() ? null : fallback;
}
return value.startsWith("${") ? null : value;
}
private static long versionOf(String fileName) {
Matcher matcher = Pattern.compile("^V(\\d+)__").matcher(fileName);
return matcher.find() ? Long.parseLong(matcher.group(1)) : -1;
}
private static String read(Path path) throws IOException {
return Files.readString(path);
}
}
@@ -1,189 +0,0 @@
package com.nanri.aiimage.modules.evidence.service;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.service.DistributedJobLockService;
import com.nanri.aiimage.common.task.LockSkipWitness;
import com.nanri.aiimage.config.EvidenceProperties;
import com.nanri.aiimage.modules.evidence.mapper.TaskEvidenceMapper;
import com.nanri.aiimage.modules.evidence.model.entity.TaskEvidenceEntity;
import com.nanri.aiimage.modules.evidence.storage.TaskEvidenceStorageService;
import com.nanri.aiimage.modules.file.service.LocalFileStorageService;
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
/**
* 证据登记的归属与保留期的执行保证(CR 第二轮 P1-2/P1-7/P2-2)。
*
* <p>P1-2 的判据是「归属先于落桶」:task_id 对得上任务行而 uid 不是行主 ⇒ 403 且
* {@code storage.store} 一次都不许被调——校验晚于落桶的话,每一次拒绝都在证据桶里
* 留一个收不回的孤儿对象。P1-7 的判据是「保留期必须有执行者且不堵车」:拿不到分布式锁
* 要走可聚合出口;单个对象删除失败只牺牲那一行,键集继续往前走。
*/
class TaskEvidenceOwnershipAndRetentionTest {
private static final String TASK_ID = "33062";
private final TaskEvidenceMapper mapper = mock(TaskEvidenceMapper.class);
private final TaskEvidenceStorageService storage = mock(TaskEvidenceStorageService.class);
private final LocalFileStorageService localFiles = mock(LocalFileStorageService.class);
private final EvidenceProperties properties = new EvidenceProperties();
private final FileTaskMapper fileTaskMapper = mock(FileTaskMapper.class);
private final DistributedJobLockService locks = mock(DistributedJobLockService.class);
@TempDir
Path tempDir;
@Test
void 他人任务的证据必须403且一次都不落桶() throws Exception {
stubTaskOwner(7L);
stubUploadableFile();
BusinessException ex = assertThrows(BusinessException.class,
() -> service().register(TASK_ID, 8L, "client", "goods-spider", "evidence.json"));
assertEquals(403, ex.getCode().intValue(), "冒名登记必须 403,不是 500 也不是静默成功");
verify(storage, never()).store(any(), any(), any());
verify(mapper, never()).insert(any(TaskEvidenceEntity.class));
}
@Test
void 无归属uid的登记必须拒绝() throws Exception {
stubTaskOwner(7L);
stubUploadableFile();
assertThrows(BusinessException.class,
() -> service().register(TASK_ID, null, "client", "goods-spider", "evidence.json"));
verify(storage, never()).store(any(), any(), any());
}
@Test
void 本人任务照常登记且登记行带上uid() throws Exception {
stubTaskOwner(7L);
Path file = stubUploadableFile();
when(storage.store(any(), eq(TASK_ID), eq("evidence.json"))).thenReturn(
new TaskEvidenceStorageService.StoredEvidence("task-evidence/k", 3L, "sha", "application/json"));
when(mapper.insert(any(TaskEvidenceEntity.class))).thenReturn(1);
service().register(TASK_ID, 7L, "client", "goods-spider", "evidence.json");
org.mockito.ArgumentCaptor<TaskEvidenceEntity> captor =
org.mockito.ArgumentCaptor.forClass(TaskEvidenceEntity.class);
verify(mapper).insert(captor.capture());
assertEquals(7L, captor.getValue().getUid(), "登记行的 uid 必须是行主本人");
assertEquals(TASK_ID, captor.getValue().getTaskId());
assertTrue(Files.notExists(file) || Files.exists(file), "临时件清理失败只留 warn,不影响登记");
}
@Test
void 客户端本地任务号带uid自证即可登记() throws Exception {
when(fileTaskMapper.selectById(anyLong())).thenReturn(null);
when(fileTaskMapper.selectOne(any())).thenReturn(null);
stubUploadableFile();
when(storage.store(any(), any(), any())).thenReturn(
new TaskEvidenceStorageService.StoredEvidence("task-evidence/k", 3L, "sha", "application/json"));
when(mapper.insert(any(TaskEvidenceEntity.class))).thenReturn(1);
service().register("local-job-abc", 5L, "client", "goods-spider", "evidence.json");
verify(storage).store(any(), eq("local-job-abc"), eq("evidence.json"));
}
@Test
void 零字节证据件拒绝登记() throws Exception {
when(fileTaskMapper.selectById(anyLong())).thenReturn(null);
when(fileTaskMapper.selectOne(any())).thenReturn(null);
Path empty = Files.createFile(tempDir.resolve("empty.png"));
when(localFiles.findLocalSourceFile("empty.png")).thenReturn(empty.toFile());
assertThrows(BusinessException.class,
() -> service().register(TASK_ID, 7L, "client", "goods-spider", "empty.png"));
verify(storage, never()).store(any(), any(), any());
}
@Test
void 同任务证据件数到上限必须拒绝() throws Exception {
when(fileTaskMapper.selectById(anyLong())).thenReturn(null);
when(fileTaskMapper.selectOne(any())).thenReturn(null);
when(mapper.selectCount(any())).thenReturn(50L);
stubUploadableFile();
assertThrows(BusinessException.class,
() -> service().register(TASK_ID, 7L, "client", "goods-spider", "evidence.json"));
verify(storage, never()).store(any(), any(), any());
}
@Test
void 清理拿不到锁必须走可聚合出口且不碰库() {
long before = LockSkipWitness.countOf(TaskEvidenceService.RETENTION_LOCK);
when(locks.tryLock(eq(TaskEvidenceService.RETENTION_LOCK), any())).thenReturn(null);
service().purgeExpired();
assertEquals(before + 1, LockSkipWitness.countOf(TaskEvidenceService.RETENTION_LOCK),
"锁跳过必须有 [lock-skip] 可聚合出口,静默 return 就是 P1-7 的另一半");
verifyNoInteractions(mapper, storage);
}
@Test
void 单个对象删除失败不堵后面的行() {
when(locks.tryLock(eq(TaskEvidenceService.RETENTION_LOCK), any()))
.thenReturn(mock(DistributedJobLockService.LockHandle.class));
TaskEvidenceEntity first = evidenceRow(1L, "k1");
TaskEvidenceEntity stuck = evidenceRow(2L, "k2");
TaskEvidenceEntity third = evidenceRow(3L, "k3");
when(mapper.selectList(any())).thenReturn(List.of(first, stuck, third), List.of());
doThrow(new RuntimeException("oss unavailable")).when(storage).delete("k2");
when(mapper.deleteById(anyLong())).thenReturn(1);
service().purgeExpired();
verify(mapper).deleteById(1L);
verify(mapper, never()).deleteById(2L);
verify(mapper).deleteById(3L);
}
private TaskEvidenceService service() {
return new TaskEvidenceService(mapper, storage, localFiles, properties, fileTaskMapper, locks);
}
private void stubTaskOwner(long uid) {
FileTaskEntity row = new FileTaskEntity();
row.setId(Long.parseLong(TASK_ID));
row.setUserId(uid);
when(fileTaskMapper.selectById(Long.parseLong(TASK_ID))).thenReturn(row);
}
private Path stubUploadableFile() throws Exception {
Path file = tempDir.resolve("evidence.json");
Files.writeString(file, "{\"traceback\": \"boom\"}");
when(localFiles.findLocalSourceFile("evidence.json")).thenReturn(file.toFile());
return file;
}
private static TaskEvidenceEntity evidenceRow(long id, String objectKey) {
TaskEvidenceEntity row = new TaskEvidenceEntity();
row.setId(id);
row.setTaskId(TASK_ID);
row.setObjectKey(objectKey);
return row;
}
}
@@ -37,8 +37,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
* <li>近 N 分钟有片写入的会话不得误清(fresh 会话必须原样保留)。</li>
* </ul>
*
* <p>分片会话只有盘上 meta/part,无 DB 行;证据表的 DB 行保留期判据见
* {@code EvidencePhase3ContractTest}(AC-13 配置块)。</p>
* <p>分片会话只有盘上 meta/part,无 DB 行(证据面已随任务证据特性整体下线,2026-11-17)。</p>
*/
class ChunkedUploadReclaimContractTest {