Files
crawler-plugin/backend-java/src/test/java/com/nanri/aiimage/config/MappedPathProbe.java
T
huangzd1997 97ca6810f7 fix(护栏自证): 切片桩不冒充产品端点;版本闸门少一处异常控制流,把 catch 棘轮记回原基线
把这期后端护栏类并进"实跑档"以后,一次 mvn 就当夜逼出两处真红。两处都是测试件/我自己
上一笔提交的问题,不是产品逻辑错,但都必须改代码而不是改基线:

1) 上一版切片的桩控制器写了 GET /api/admin/users,与真 AdminUserController#listUsers
   撞在同一条完整映射上。MappedPathProbe 把整棵 main 树的映射枚举进同一个
   RequestMappingHandlerMapping,于是 ApiGuardCoverageBreachTest 先炸 Ambiguous mapping
   (2 errors);把桩路径改成 /api/client/slice-ping、/api/admin/slice-probe 后又暴露第二层:
   测试桩本身被当成"新增未设防端点"进判定 ⇒ 探针改为不登记测试夹具里的控制器
   (按最外层类名 Test/Tests/IT 排除,main 树里这种命名的真控制器实测 0 个)。
   分母守卫照旧有效:mapped.size() > 300 那条断言仍在,排掉桩不会把清单清成空的。

2) CatchSilenceRatchetTest 红的是我自己 9d762c55(20:25 提交)里那处
   `catch (NumberFormatException overflow) { return null; }`:total 1002→1003、
   不重抛 559→560。也就是说**那笔提交是带着一支红的护栏类交进去的**——上一轮我只把切片
   纳入实跑分母,没把这支棘轮一起跑,所以"7 例绿"的读数过期了。
   修法不是抬基线:版本号的单段长度超过 18 位本来就该按"判不出来"处理,于是用
   MAX_SEGMENT_DIGITS 上限替掉 try/catch,判定走向逐字不变(仍是 return null ⇒ 不拒),
   total 与不重抛都记回 1002/559,验收基线一格没动。RETHROW 下限 388、logOnly 172、
   empty 56 三档本轮都没碰。
   顺手改掉失败文案里的错算式(原写"= 验收基线 1000 + 1 处",实际那 2 处各自有出处)。

版本闸门本身仍未上线(现网 jar 是 12:3x 那版,9d762c55 在 20:25)⇒ 本改动零现网影响。

实跑:mvn -o test -Dtest=ClientVersionGuardContextSliceTest,ApiGuardCoverageBreachTest,
ApiGuardCoverageAuditorTest,ApiGuardCoverageAuditorWiringTest,CatchSilenceRatchetTest,
ClientVersionGuardFilterTest,BuildInfoLoggerTest
⇒ Tests run: 53, Failures: 0, Errors: 0 / BUILD SUCCESS(逐类 6/10/8/2/7/12/8)。
2026-10-09 00:23:14 +08:00

117 lines
6.1 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package com.nanri.aiimage.config;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* 不连库、不起容器,把「Spring MVC 真正会登记的映射」原样枚举出来。
*
* <p>为什么不用正则扫源码:{@link ApiGuardCoverageAuditor} 判的是 {@code handlerMapping.getPatternValues()},
* 类级 {@code @RequestMapping} 与方法级路径的拼接、{@code {"/a","/b"}} 多值、方法级空路径这些细节由 Spring 自己算。
* 自己抄一份正则就会和真实映射慢慢脱钩——而存量快照一旦比真实集合少一条,
* 现网就变成"新增未设防端点 ⇒ 拒绝启动"的假事故(两台同时起不来=重启窗口事故重演)。
*
* <p>做法:把控制器注册成 bean <b>定义</b> 并标成懒加载,再让真实的
* {@link RequestMappingHandlerMapping#afterPropertiesSet()} 去发现它们。
* {@code preInstantiateSingletons} 跳过懒加载定义 ⇒ 控制器不被实例化(它们的构造器要 DataSource/Redis),
* 登记的 HandlerMethod 只持 beanName ⇒ 不需要 DB / Redis / RocketMQ,也不需要 {@code @SpringBootTest}。
*
* <p>这里刻意只用 {@code getMethod().getDeclaringClass()},不碰 {@code HandlerMethod#getBeanType()}——
* 后者会把 bean 解析出来,就把"不实例化"这个前提破坏了。
*/
final class MappedPathProbe {
static final String BASE_PACKAGE = "com.nanri.aiimage";
private MappedPathProbe() {
}
/** Spring 登记的全部映射(路径模式 × 处理器方法),与现网 handlerMapping.getHandlerMethods() 同口径。 */
static Map<RequestMappingInfo, String> handlerMethods() {
GenericApplicationContext ctx = new GenericApplicationContext();
for (Class<?> controller : controllerClasses()) {
GenericBeanDefinition def = new GenericBeanDefinition();
def.setBeanClass(controller);
def.setLazyInit(true);
ctx.registerBeanDefinition("probe-" + controller.getName(), def);
}
ctx.refresh();
RequestMappingHandlerMapping mapping = new RequestMappingHandlerMapping();
mapping.setApplicationContext(ctx);
mapping.afterPropertiesSet();
Map<RequestMappingInfo, String> out = new java.util.LinkedHashMap<>();
try {
mapping.getHandlerMethods().forEach((info, handlerMethod) -> out.put(info,
handlerMethod.getMethod().getDeclaringClass().getSimpleName() + "#" + handlerMethod.getMethod().getName()));
} finally {
ctx.close();
}
return out;
}
/** @return 去重后的请求路径模式(审计器的分母单位)。 */
static Set<String> mappedPaths() {
Set<String> paths = new LinkedHashSet<>();
handlerMethods().keySet().forEach(info -> paths.addAll(info.getPatternValues()));
return paths;
}
/** 「路径 -> 处理器」逐条清单,供与现网 handler 数对账、也供快照生成用。 */
static List<String> mappingLines() {
List<String> out = new ArrayList<>();
handlerMethods().forEach((info, handler) ->
info.getPatternValues().forEach(p -> out.add(p + " -> " + handler)));
out.sort(java.util.Comparator.naturalOrder());
return out;
}
/** 控制器类清单:判据与 {@code RequestMappingHandlerMapping#isHandler} 对齐。 */
static List<Class<?>> controllerClasses() {
ClassPathScanningCandidateComponentProvider scanner =
new ClassPathScanningCandidateComponentProvider(false);
scanner.addIncludeFilter(new AnnotationTypeFilter(RestController.class));
scanner.addIncludeFilter(new AnnotationTypeFilter(Controller.class));
List<Class<?>> out = new ArrayList<>();
scanner.findCandidateComponents(BASE_PACKAGE).forEach(cd -> {
String binary = cd.getBeanClassName();
// 测试夹具里的 @RestController(切片桩)不是产品端点:登记进来会让映射清单凭空多出
// 真树里没有的条目,桩与真控制器撞同一条完整路径时还会当场抛 Ambiguous mapping
// (上一版切片写 GET /api/admin/users,就是把探针宿主用例打成 2 errors 的原因)。
int dollar = binary.indexOf('$');
String outermost = dollar < 0 ? binary : binary.substring(0, dollar);
if (outermost.endsWith("Test") || outermost.endsWith("Tests")
|| outermost.endsWith("IT")) {
return;
}
try {
Class<?> type = Class.forName(binary);
boolean handler = AnnotatedElementUtils.hasAnnotation(type, Controller.class)
|| AnnotatedElementUtils.hasAnnotation(type, RequestMapping.class);
// @ControllerAdvice / @RestControllerAdvice 不是 handler,MVC 不会为它登记映射
boolean advice = AnnotatedElementUtils.hasAnnotation(type, ControllerAdvice.class);
if (handler && !advice) {
out.add(type);
}
} catch (ClassNotFoundException e) {
throw new IllegalStateException("控制器类加载失败:" + cd.getBeanClassName(), e);
}
});
return out;
}
}