后端(四面9分批次): 锁跳过留痕、状态词表收成单点、版本硬地板进 yml 并记账
- 14 处「拿不到锁就 continue」过去零日志,现统一带可聚合锚点并有留痕判据 (LockSkipWitnessTest 7 例 + LockSkipSilentExitGuardrailTest 4 例)。 - 任务状态词表:散落内联集合改由单一定义点判方向(TaskStatusVocabularyRatchetTest 7 例), CANCELED/CANCELLED 只做归一映射,没改库值也没改对外契约。 - 版本硬地板三键(min-supported / enforce / rejectUnreported)此前在任何 yml 里 0 处=出厂即惰性; 现在入册且 enforce=false 走记账模式(ClientVersionFloorConfigTest 9 例),真挡谁留给用户拍。 - 业务码→HTTP 状态只做映射单点 + 开关(默认关,开启前逐字节等价,BusinessErrorHttpStatusTest 8 例); 直接翻面会让三个前端把业务失败读成网络挂了。 - 验收:mvn -o test 这 5 个类 35 例 0 红(用 python subprocess 起 mvn——bash 里 cmd 包一层 开的是交互式 cmd,rc 是 cmd 的,会给出假的 rc=0)。
This commit is contained in:
+269
@@ -0,0 +1,269 @@
|
||||
package com.nanri.aiimage.common.exception;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import ch.qos.logback.classic.Logger;
|
||||
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||
import ch.qos.logback.core.read.ListAppender;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.service.TaskOwnerForwardService;
|
||||
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import java.io.InputStream;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.boot.env.YamlPropertySourceLoader;
|
||||
import org.springframework.core.env.EnumerablePropertySource;
|
||||
import org.springframework.core.env.PropertySource;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
/**
|
||||
* 业务码 → 真 HTTP 状态码的映射单点判据(2026-10-09 评审「交互 5.5」项 4,本轮只做安全的一半)。
|
||||
*
|
||||
* <p>要钉住的三件事,缺一半都不算做完:
|
||||
* <ol>
|
||||
* <li><b>默认关</b>:开关在 {@code application.yml} 里显式写着 false,且关掉时
|
||||
* {@link BusinessErrorHttpStatus#render} 返回<b>同一个实例</b>——不是"看起来一样",
|
||||
* 是根本没构造 {@code ResponseEntity},序列化路径与改动前逐字节相同;</li>
|
||||
* <li><b>白名单是封闭的</b>:表外 code(含历史大量不带码的 {@code ApiResponse.fail(message)})
|
||||
* 即使开关打开也恒走 200。这条是翻真时唯一的兜底——它保证"打开开关"的爆炸半径
|
||||
* 只有白名单里那 13 个码,而不是全部 1,242 处业务失败;</li>
|
||||
* <li><b>打开时只改状态行、不改响应体</b>:body 实例不变,成功响应(40901 幂等忽略)不许被拖进映射。</li>
|
||||
* </ol>
|
||||
*
|
||||
* <p>重跑:{@code mvn -o test -Dtest=BusinessErrorHttpStatusTest}(cwd = backend-java)。
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class BusinessErrorHttpStatusTest {
|
||||
|
||||
private static final Pattern PLACEHOLDER = Pattern.compile("^\\$\\{([^:}]+):([^}]*)\\}$");
|
||||
|
||||
@Mock private TaskOwnerForwardService taskOwnerForwardService;
|
||||
@InjectMocks private GlobalExceptionHandler handler;
|
||||
|
||||
@AfterEach
|
||||
void switchBackOff() {
|
||||
BusinessErrorHttpStatus.bindForTests(false, null);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 1. 默认关
|
||||
|
||||
@Test
|
||||
void switchShipsDeclaredAndOffInApplicationYml() {
|
||||
Map<String, String> flat = flatten("application.yml");
|
||||
assertThat(flat)
|
||||
.as("开关必须显式写在 yml 里(「没写=隐式默认」就是版本地板踩过的坑)")
|
||||
.containsKey(BusinessErrorHttpStatus.ENABLED_KEY);
|
||||
assertThat(defaultOf(flat, BusinessErrorHttpStatus.ENABLED_KEY)).isEqualTo("false");
|
||||
// 组件构造时把配置值搬到静态判定上;默认态必须两处一致(两套默认值会漂)
|
||||
@SuppressWarnings("unchecked")
|
||||
org.springframework.beans.factory.ObjectProvider<io.micrometer.core.instrument.MeterRegistry> provider =
|
||||
mock(org.springframework.beans.factory.ObjectProvider.class);
|
||||
when(provider.getIfAvailable()).thenReturn(null);
|
||||
new BusinessErrorHttpStatus(provider, false);
|
||||
assertThat(BusinessErrorHttpStatus.isEnabled())
|
||||
.as("出厂态就是关:没人拍板之前不该有任何状态码变化")
|
||||
.isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void disabledRenderReturnsTheExactSameInstance() {
|
||||
BusinessErrorHttpStatus.bindForTests(false, null);
|
||||
ApiResponse<Void> body = ApiResponse.fail(401, "未登录");
|
||||
|
||||
Object rendered = BusinessErrorHttpStatus.render(body, 401);
|
||||
|
||||
// 关掉时不是"造一个等价的 ResponseEntity",是根本没造——否则就不是逐字节一致
|
||||
assertThat(rendered).isSameAs(body);
|
||||
assertThat(rendered).isNotInstanceOf(ResponseEntity.class);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 2. 白名单封闭
|
||||
|
||||
@Test
|
||||
void whitelistIsExactlyThePinnedCodeList() {
|
||||
assertThat(BusinessErrorHttpStatus.mappings().keySet())
|
||||
.as("会被映射成非 200 的 code 清单(改这里=改现网状态码契约,必须点名评审)")
|
||||
.containsExactlyInAnyOrder(400, 401, 403, 404, 409, 422, 500, 503,
|
||||
4011, 4012, 40401, 40902, 40903);
|
||||
|
||||
assertThat(BusinessErrorHttpStatus.statusFor(401)).isEqualTo(HttpStatus.UNAUTHORIZED);
|
||||
assertThat(BusinessErrorHttpStatus.statusFor(403)).isEqualTo(HttpStatus.FORBIDDEN);
|
||||
assertThat(BusinessErrorHttpStatus.statusFor(400)).isEqualTo(HttpStatus.BAD_REQUEST);
|
||||
assertThat(BusinessErrorHttpStatus.statusFor(404)).isEqualTo(HttpStatus.NOT_FOUND);
|
||||
assertThat(BusinessErrorHttpStatus.statusFor(4011))
|
||||
.as("被顶下线:码族是鉴权,翻真后是 401")
|
||||
.isEqualTo(HttpStatus.UNAUTHORIZED);
|
||||
assertThat(BusinessErrorHttpStatus.statusFor(4012))
|
||||
.as("客户端版本过低:让调用方看见 4xx 而不是 200")
|
||||
.isEqualTo(HttpStatus.BAD_REQUEST);
|
||||
assertThat(BusinessErrorHttpStatus.statusFor(BusinessCodes.TASK_BUSY)).isEqualTo(HttpStatus.CONFLICT);
|
||||
assertThat(BusinessErrorHttpStatus.statusFor(BusinessCodes.TASK_OWNER_FORWARD))
|
||||
.isEqualTo(HttpStatus.CONFLICT);
|
||||
assertThat(BusinessErrorHttpStatus.statusFor(BusinessCodes.TASK_NOT_FOUND))
|
||||
.isEqualTo(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
|
||||
@Test
|
||||
void idempotentSuccessCodeIsNeverMappedToAnErrorStatus() {
|
||||
// 40901 在 handler 里是幂等忽略、返回 success=true。它是成功响应,
|
||||
// 一旦被写进映射表,翻真后"重复提交"会从 200 变 409,客户端会当成失败重试。
|
||||
assertThat(BusinessErrorHttpStatus.mappings())
|
||||
.as("TASK_ALREADY_FINISHED 不在白名单里")
|
||||
.doesNotContainKey(BusinessCodes.TASK_ALREADY_FINISHED);
|
||||
assertThat(BusinessErrorHttpStatus.statusFor(BusinessCodes.TASK_ALREADY_FINISHED))
|
||||
.isEqualTo(HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Test
|
||||
void codesOutsideTheWhitelistStayOnTwoHundredEvenWhenSwitchIsOn() {
|
||||
BusinessErrorHttpStatus.bindForTests(true, null);
|
||||
try {
|
||||
// 开关开着也不能碰没预料到的码:这是翻真时唯一的爆炸半径上限
|
||||
assertThat(BusinessErrorHttpStatus.statusFor(40999)).isEqualTo(HttpStatus.OK);
|
||||
assertThat(BusinessErrorHttpStatus.statusFor(0)).isEqualTo(HttpStatus.OK);
|
||||
assertThat(BusinessErrorHttpStatus.statusFor(200)).isEqualTo(HttpStatus.OK);
|
||||
assertThat(BusinessErrorHttpStatus.statusFor(null)).isEqualTo(HttpStatus.OK);
|
||||
|
||||
ApiResponse<Void> body = ApiResponse.fail(40999, "没登记过的业务码");
|
||||
assertThat(BusinessErrorHttpStatus.render(body, 40999)).isSameAs(body);
|
||||
ApiResponse<Void> codeless = ApiResponse.fail("历史上大量不带码的失败");
|
||||
assertThat(BusinessErrorHttpStatus.render(codeless, null)).isSameAs(codeless);
|
||||
} finally {
|
||||
BusinessErrorHttpStatus.bindForTests(false, null);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 3. 打开时只改状态行
|
||||
|
||||
@Test
|
||||
void enabledRenderKeepsBodyInstanceAndOnlyChangesStatusLine() {
|
||||
SimpleMeterRegistry registry = new SimpleMeterRegistry();
|
||||
BusinessErrorHttpStatus.bindForTests(true, registry);
|
||||
ListAppender<ILoggingEvent> captured = capture();
|
||||
try {
|
||||
ApiResponse<Void> body = ApiResponse.fail(403, "没有权限");
|
||||
Object rendered = BusinessErrorHttpStatus.render(body, 403);
|
||||
|
||||
assertThat(rendered).isInstanceOfSatisfying(ResponseEntity.class, r -> {
|
||||
assertThat(r.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
|
||||
assertThat(r.getBody()).as("响应体必须是同一个实例,不改一个字节").isSameAs(body);
|
||||
});
|
||||
|
||||
assertThat(captured.list.stream().map(ILoggingEvent::getFormattedMessage).toList())
|
||||
.as("改写状态行这件事本身要可 grep、可聚合")
|
||||
.anySatisfy(line -> assertThat(line)
|
||||
.contains(BusinessErrorHttpStatus.ANCHOR)
|
||||
.contains("code=403")
|
||||
.contains("HTTP 403"));
|
||||
assertThat(registry.get(BusinessErrorHttpStatus.METRIC)
|
||||
.tag("code", "403").tag("httpStatus", "403").counter().count()).isEqualTo(1.0);
|
||||
} finally {
|
||||
release(captured);
|
||||
registry.close();
|
||||
BusinessErrorHttpStatus.bindForTests(false, null);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 4. 出口真的接在 handler 上
|
||||
|
||||
@Test
|
||||
void handlerKeepsHttpTwoHundredWhileSwitchOff() {
|
||||
BusinessErrorHttpStatus.bindForTests(false, null);
|
||||
Object result = handler.handleBusinessException(
|
||||
new BusinessException(403, "无权访问"), request(), mock(HttpServletResponse.class));
|
||||
|
||||
// 关掉时 handler 的返回类型都必须是 ApiResponse 本体,不是 ResponseEntity 包一层
|
||||
assertThat(result).isInstanceOf(ApiResponse.class);
|
||||
assertThat(result).isNotInstanceOf(ResponseEntity.class);
|
||||
ApiResponse<?> body = (ApiResponse<?>) result;
|
||||
assertThat(body.isSuccess()).isFalse();
|
||||
assertThat(body.getCode()).isEqualTo(403);
|
||||
assertThat(body.getMessage()).isNotBlank();
|
||||
}
|
||||
|
||||
@Test
|
||||
void handlerEmitsRealStatusOnceSwitchIsOn() {
|
||||
SimpleMeterRegistry registry = new SimpleMeterRegistry();
|
||||
BusinessErrorHttpStatus.bindForTests(true, registry);
|
||||
try {
|
||||
Object result = handler.handleBusinessException(
|
||||
new BusinessException(403, "无权访问"), request(), mock(HttpServletResponse.class));
|
||||
|
||||
ResponseEntity<?> response = (ResponseEntity<?>) result;
|
||||
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
|
||||
ApiResponse<?> body = (ApiResponse<?>) response.getBody();
|
||||
assertThat(body.getCode()).as("响应体一个字节都不许多改").isEqualTo(403);
|
||||
|
||||
// 第二件:幂等忽略那条成功路径即使在开关开着时也必须还是 200/ApiResponse
|
||||
Object finished = handler.handleBusinessException(
|
||||
new BusinessException(BusinessCodes.TASK_ALREADY_FINISHED, "任务已结束"),
|
||||
request(), mock(HttpServletResponse.class));
|
||||
assertThat(finished).isInstanceOf(ApiResponse.class);
|
||||
assertThat(((ApiResponse<?>) finished).isSuccess()).isTrue();
|
||||
} finally {
|
||||
registry.close();
|
||||
BusinessErrorHttpStatus.bindForTests(false, null);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 助手
|
||||
|
||||
private HttpServletRequest request() {
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
when(request.getMethod()).thenReturn("POST");
|
||||
when(request.getRequestURI()).thenReturn("/api/publish/tasks");
|
||||
return request;
|
||||
}
|
||||
|
||||
private ListAppender<ILoggingEvent> capture() {
|
||||
Logger logger = (Logger) org.slf4j.LoggerFactory.getLogger(BusinessErrorHttpStatus.class);
|
||||
ListAppender<ILoggingEvent> appender = new ListAppender<>();
|
||||
appender.start();
|
||||
logger.addAppender(appender);
|
||||
return appender;
|
||||
}
|
||||
|
||||
private void release(ListAppender<ILoggingEvent> appender) {
|
||||
((Logger) org.slf4j.LoggerFactory.getLogger(BusinessErrorHttpStatus.class)).detachAppender(appender);
|
||||
}
|
||||
|
||||
private Map<String, String> flatten(String fileName) {
|
||||
ClassPathResource resource = new ClassPathResource(fileName);
|
||||
assertThat(resource.exists()).as("classpath 上找不到 " + fileName).isTrue();
|
||||
try (InputStream in = resource.getInputStream()) {
|
||||
Map<String, String> flat = new LinkedHashMap<>();
|
||||
for (PropertySource<?> source : new YamlPropertySourceLoader().load(fileName, resource)) {
|
||||
if (source instanceof EnumerablePropertySource<?> enumerable) {
|
||||
for (String name : enumerable.getPropertyNames()) {
|
||||
Object value = enumerable.getProperty(name);
|
||||
flat.put(name, value == null ? "" : String.valueOf(value));
|
||||
}
|
||||
}
|
||||
}
|
||||
return flat;
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("读 " + fileName + " 失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
private String defaultOf(Map<String, String> flat, String key) {
|
||||
String raw = flat.get(key).trim();
|
||||
Matcher m = PLACEHOLDER.matcher(raw);
|
||||
return m.matches() ? m.group(2).trim() : raw;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user