refactor(phase-4): 解散万能 util——similarasin/util 与 common/util 按域归位
similarasin/util 7 支: - 域内件(SimilarAsinImageEmbedder/PuzzleImageMerger/SimilarAsinLogSupport/ BoundedImageCache)并入既有 service/support 先例; - 通用 Excel 件(ExcelCellImageWriter/WpsCellImageWriter)归 common/excel; - 仅测试用的 SimilarAsinPerfFixture 移出生产源到 src/test。 common/util 13 支解散为四个关注点包:excel(读/写/单元格图片)、 text(BrandLabel/SecretMasking/UserMessages)、task(行过滤/分组传播/判死文案/ 删除台账/锁跳过留痕)、support(LRU/下载头/线程池)。老 util 目录不再存在。 纯粹的包搬迁与 import 重写(diff 219 增 / 217 删),零行为改动: 搬迁前后由 SimilarAsinCreateTaskSnapshotTest 的建单入口 golden 对撞相等; 新增 MovedComponentScanTest 钉住三枚 @Component 仍被根包扫描发现、老包零残留。
This commit is contained in:
+68
@@ -0,0 +1,68 @@
|
||||
package com.nanri.aiimage.common.task;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class FailedStatusRowFilterTest {
|
||||
|
||||
@Test
|
||||
void findsStatusColumnByChineseOrEnglishAlias() {
|
||||
assertEquals(2, FailedStatusRowFilter.findStatusColumnIndex(List.of("id", "asin", "\u72b6\u6001")));
|
||||
assertEquals(1, FailedStatusRowFilter.findStatusColumnIndex(List.of("id", " Status ")));
|
||||
assertEquals(-1, FailedStatusRowFilter.findStatusColumnIndex(List.of("id", "asin", "country")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void matchesConfiguredFailedStatusValues() {
|
||||
assertTrue(FailedStatusRowFilter.matchesFailedStatus("\u9519\u8bef"));
|
||||
assertTrue(FailedStatusRowFilter.matchesFailedStatus("\u5931\u8d25"));
|
||||
assertTrue(FailedStatusRowFilter.matchesFailedStatus("FAILED"));
|
||||
assertTrue(FailedStatusRowFilter.matchesFailedStatus(" failed "));
|
||||
assertTrue(FailedStatusRowFilter.isBlankStatus(" "));
|
||||
assertFalse(FailedStatusRowFilter.matchesFailedStatus("\u6210\u529f"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void retainsOnlyFailedRowsWhenStatusFilteringEnabled() {
|
||||
List<String> rows = List.of("\u9519\u8bef", "\u6210\u529f", "FAILED", "\u5904\u7406\u4e2d");
|
||||
FailedStatusRowFilter.FilterResult<String> result =
|
||||
FailedStatusRowFilter.retainFailedRows(rows, true, value -> value);
|
||||
|
||||
assertTrue(result.filterApplied());
|
||||
assertEquals(List.of("\u9519\u8bef", "FAILED"), result.rows());
|
||||
assertEquals(2, result.filteredCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void keepsOriginalRowsWhenStatusFilteringDisabled() {
|
||||
List<String> rows = List.of("\u9519\u8bef", "\u6210\u529f");
|
||||
FailedStatusRowFilter.FilterResult<String> result =
|
||||
FailedStatusRowFilter.retainFailedRows(rows, false, value -> value);
|
||||
|
||||
assertFalse(result.filterApplied());
|
||||
assertEquals(rows, result.rows());
|
||||
assertEquals(0, result.filteredCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void canRetainFailedAndBlankRowsTogether() {
|
||||
List<String> rows = List.of("\u9519\u8bef", "", "\u6210\u529f", "FAILED");
|
||||
FailedStatusRowFilter.FilterResult<String> result =
|
||||
FailedStatusRowFilter.retainRows(
|
||||
rows,
|
||||
true,
|
||||
value -> value,
|
||||
value -> FailedStatusRowFilter.matchesFailedStatus(value)
|
||||
|| FailedStatusRowFilter.isBlankStatus(value)
|
||||
);
|
||||
|
||||
assertTrue(result.filterApplied());
|
||||
assertEquals(List.of("\u9519\u8bef", "", "FAILED"), result.rows());
|
||||
assertEquals(1, result.filteredCount());
|
||||
}
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
package com.nanri.aiimage.common.task;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class GroupResultPropagatorTest {
|
||||
|
||||
@Test
|
||||
void doesNotTreatNoInfringementAsInfringementHit() {
|
||||
List<ParsedRow> parsedRows = List.of(
|
||||
new ParsedRow("20_1"),
|
||||
new ParsedRow("20_2")
|
||||
);
|
||||
List<ResultRow> resultRows = List.of(
|
||||
new ResultRow("无侵权"),
|
||||
new ResultRow("无侵权")
|
||||
);
|
||||
|
||||
int updatedRows = GroupResultPropagator.propagateByGroup(
|
||||
parsedRows,
|
||||
ParsedRow::displayId,
|
||||
row -> resultRows.get(parsedRows.indexOf(row)),
|
||||
ResultRow::conclusion,
|
||||
ResultRow::setConclusion,
|
||||
List.of("已侵权", "侵权")
|
||||
);
|
||||
|
||||
assertEquals(0, updatedRows);
|
||||
assertEquals("无侵权", resultRows.get(0).conclusion());
|
||||
assertEquals("无侵权", resultRows.get(1).conclusion());
|
||||
}
|
||||
|
||||
@Test
|
||||
void propagatesWhenGroupHasRealInfringementHit() {
|
||||
List<ParsedRow> parsedRows = List.of(
|
||||
new ParsedRow("20_1"),
|
||||
new ParsedRow("20_2")
|
||||
);
|
||||
List<ResultRow> resultRows = List.of(
|
||||
new ResultRow("无侵权"),
|
||||
new ResultRow("侵权")
|
||||
);
|
||||
|
||||
int updatedRows = GroupResultPropagator.propagateByGroup(
|
||||
parsedRows,
|
||||
ParsedRow::displayId,
|
||||
row -> resultRows.get(parsedRows.indexOf(row)),
|
||||
ResultRow::conclusion,
|
||||
ResultRow::setConclusion,
|
||||
List.of("已侵权", "侵权")
|
||||
);
|
||||
|
||||
assertEquals(1, updatedRows);
|
||||
assertEquals("侵权", resultRows.get(0).conclusion());
|
||||
assertEquals("侵权", resultRows.get(1).conclusion());
|
||||
}
|
||||
|
||||
private record ParsedRow(String displayId) {
|
||||
}
|
||||
|
||||
private static final class ResultRow {
|
||||
|
||||
private String conclusion;
|
||||
|
||||
private ResultRow(String conclusion) {
|
||||
this.conclusion = conclusion;
|
||||
}
|
||||
|
||||
private String conclusion() {
|
||||
return conclusion;
|
||||
}
|
||||
|
||||
private void setConclusion(String conclusion) {
|
||||
this.conclusion = conclusion;
|
||||
}
|
||||
}
|
||||
}
|
||||
+226
@@ -0,0 +1,226 @@
|
||||
package com.nanri.aiimage.common.task;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.fail;
|
||||
|
||||
import com.nanri.aiimage.testutil.SourceScan;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* 锁跳过出口的<b>逐处</b>判据(2026-10-09 评审「稳定 5.5」项 1,权重 1.5)。
|
||||
*
|
||||
* <p>要拦的行为很具体:{@code if (<某个 lock 变量> == null) { continue; }} /
|
||||
* {@code { return; }} —— 巡检任务每轮跑、被锁挡掉的任务直接消失,一行日志都不留。
|
||||
* 实测基线(2026-10-10 自己数出来的,不是评审给的 14):全树 {@code src/main/java} 共
|
||||
* <b>29</b> 处这种形状,28 处已接 {@link LockSkipWitness},剩下 1 处当年记进了例外台账。
|
||||
* <b>2026-10-22 那条例外被现网证伪并已删除</b>(它保的正是"跨线程 close 静默不放手"这条
|
||||
* 造成 11.3 小时僵尸锁的路径),台账现为空,见 {@link #LEDGERED_EXCEPTIONS}。
|
||||
*
|
||||
* <p>判据打在<b>分支体</b>上而不是打在"某个类里出现过锚点"上:分支体剥掉注释后必须只剩
|
||||
* {@code continue;} / {@code return;}(顶多一行 {@code LockSkipWitness.*} 调用)。
|
||||
* 这样"锚点方法存在但没人调"(2026-10-09 踩过的那坑)在这儿会直接红——
|
||||
* {@link #witnessedSiteCountCannotShrink} 把已接线的点位数钉成 28,掉一处就红,
|
||||
* {@link #everyPointLiteralIsUsedByExactlyOneSite} 保证点位没有互相覆盖成一坨。
|
||||
*/
|
||||
class LockSkipSilentExitGuardrailTest {
|
||||
|
||||
/** 形如 lock / jobLock / taskLockHandle / neverReportedLock / distributedJobLockService 的变量判空。 */
|
||||
private static final Pattern LOCK_NULL_CHECK =
|
||||
Pattern.compile("if\\s*\\(\\s*(\\w*[Ll]ock\\w*)\\s*==\\s*null\\s*\\)\\s*\\{");
|
||||
|
||||
/** 分支体剥掉出口调用后,只剩这两种语句就是「跳过但什么都不做」。 */
|
||||
private static final List<String> BARE_EXITS = List.of("continue;", "return;");
|
||||
|
||||
private static final Pattern WITNESS_CALL = Pattern.compile("LockSkipWitness\\.\\w+\\s*\\(([^;]*)\\);");
|
||||
|
||||
/**
|
||||
* 例外台账:<b>文件名 -> 判定不该接的原因</b>。加一行要有现网证据,删一行就是补了出口。
|
||||
*
|
||||
* <p>2026-10-22 清空。原先唯一那行是 {@code TaskDistributedLockService.close()} 里的
|
||||
* {@code heldLock == null},当时的判读是"重复 close 的幂等护栏,不挡工作也不丢数据"。
|
||||
* 现网把它证伪了:那句判空按<b>取锁线程</b>的 ThreadLocal 找锁,于是
|
||||
* <b>跨线程 close 会走进这条"无事可做"分支静默不放手</b>——锁留在原地、续期任务留在原地,
|
||||
* 三把 {@code task:similar-asin:*} 被看门狗喂到 11.3 小时不放,期间该任务每次结果回传
|
||||
* 都判 40902(两小时 2370 次),任务永久停在 RUNNING。修复后句柄直接绑住持锁对象,
|
||||
* 这条分支已不存在,台账随之归零:今后任何文件再写一处裸跳过,上面那条判据直接判红。
|
||||
*/
|
||||
private static final Set<String> LEDGERED_EXCEPTIONS = Set.of();
|
||||
|
||||
/** 已接线点位数的硬分母:只许升(新增出口),不许降(出口被摘)。 */
|
||||
private static final int MIN_WITNESSED_SITES = 28;
|
||||
|
||||
@Test
|
||||
void everyLockNullSkipBranchCarriesAVisibleWitness() {
|
||||
List<String> unwitnessed = new ArrayList<>();
|
||||
int witnessed = 0;
|
||||
for (Path file : mainSources()) {
|
||||
String source = SourceScan.withoutComments(read(file));
|
||||
for (String body : lockNullBranches(source)) {
|
||||
if (!isSkipOnlyBranch(body)) {
|
||||
continue;
|
||||
}
|
||||
if (body.contains("LockSkipWitness.")) {
|
||||
witnessed++;
|
||||
} else if (!LEDGERED_EXCEPTIONS.contains(file.getFileName().toString())) {
|
||||
unwitnessed.add(file.getFileName() + " -> " + body.strip());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 自检(否定句必须配同口径非零对照):扫描器真抓得到已接线的那批,否则下面那句 isEmpty() 是恒绿
|
||||
assertThat(witnessed)
|
||||
.as("已接 LockSkipWitness 的锁跳过点位数(掉一处就是在摘出口)")
|
||||
.isGreaterThanOrEqualTo(MIN_WITNESSED_SITES);
|
||||
assertThat(unwitnessed)
|
||||
.as("剩下「判空即跳过且零日志」的锁出口,必须全在例外台账里")
|
||||
.isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void exceptionLedgerCannotBeReopenedWithoutAStory() {
|
||||
// 台账一旦有名字,上面那条"每处裸跳过都要出口"就对该文件失效——等于自己给自己发免检。
|
||||
// 2026-10-22 那把 11.3 小时的僵尸锁就是这张免检牌保下来的形状,所以这里要求:
|
||||
// 想加回去,必须带着现网证据来改这段判据,而不是悄悄加一行文件名。
|
||||
assertThat(LEDGERED_EXCEPTIONS)
|
||||
.as("例外台账必须为空(唯一那条例外在无主锁事故里被证伪并已随修复删除)")
|
||||
.isEmpty();
|
||||
}
|
||||
|
||||
/**
|
||||
* 「跳过但什么都不做」的分支体:剥掉出口调用与空白后,只剩 {@code continue;} 或 {@code return;}。
|
||||
* 有别的语句(比如 {@code taskFileJobService.requeue(...)})就不是被拦的对象——那条路本来就留了痕。
|
||||
*/
|
||||
private static boolean isSkipOnlyBranch(String body) {
|
||||
String stripped = body.replaceAll("LockSkipWitness\\.\\w+\\s*\\([^;]*\\);", "").strip();
|
||||
return BARE_EXITS.contains(stripped);
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyPointLiteralIsUsedByExactlyOneSite() {
|
||||
List<String> points = new ArrayList<>();
|
||||
for (Path file : mainSources()) {
|
||||
if ("LockSkipWitness.java".equals(file.getFileName().toString())) {
|
||||
continue;
|
||||
}
|
||||
Matcher m = WITNESS_CALL.matcher(SourceScan.withoutComments(read(file)));
|
||||
while (m.find()) {
|
||||
String args = m.group(1);
|
||||
String first = args.split(",")[0].strip();
|
||||
if (first.startsWith("\"") && first.endsWith("\"") && first.length() > 2) {
|
||||
points.add(first);
|
||||
} else if (!first.isBlank()) {
|
||||
fail("点位字面量必须写死在第一个参数(不打行号、不拼变量),实际=" + args
|
||||
+ " @ " + file.getFileName());
|
||||
}
|
||||
}
|
||||
}
|
||||
Set<String> distinct = new LinkedHashSet<>(points);
|
||||
assertThat(points)
|
||||
.as("全树 LockSkipWitness 调用数")
|
||||
.hasSizeGreaterThanOrEqualTo(MIN_WITNESSED_SITES);
|
||||
assertThat(distinct)
|
||||
.as("点位字面量必须一一对应:两个跳过处共用一个点位,现网就分不出是谁在被挡")
|
||||
.hasSize(points.size());
|
||||
// 命名口径也钉一下:点位都是小写 kebab,允许带一个 ":用途" 后缀。
|
||||
// 带后缀的是任务级点位(模块内多处跳过要分得开);不带后缀的是作业锁点位,
|
||||
// 它直接沿用 tryLock 已有的锁名(如 expired-account-task-stop),不去另起一套标识。
|
||||
assertThat(distinct).allSatisfy(point ->
|
||||
assertThat(point).matches("\"[a-z0-9][a-z0-9.-]*(:[a-z0-9.-]+)?\""));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anchorIsReusedFromTheSingleDefinitionPoint() {
|
||||
// 锚点只有 LockSkipWitness 一处定义;业务侧禁止把 "[lock-skip]" 抄成字面量,
|
||||
// 否则改了常量之后 grep 得到的是半套出口。
|
||||
String witnessSource = SourceScan.withoutComments(SourceScan.sourceText("LockSkipWitness.java"));
|
||||
assertThat(witnessSource).contains("public static final String ANCHOR = \"[lock-skip]\"");
|
||||
|
||||
List<String> copycats = new ArrayList<>();
|
||||
for (Path file : mainSources()) {
|
||||
if ("LockSkipWitness.java".equals(file.getFileName().toString())) {
|
||||
continue;
|
||||
}
|
||||
if (SourceScan.withoutComments(read(file)).contains("[lock-skip]")) {
|
||||
copycats.add(file.getFileName().toString());
|
||||
}
|
||||
}
|
||||
assertThat(copycats).as("[lock-skip] 字面量不得在业务侧被抄第二遍").isEmpty();
|
||||
}
|
||||
|
||||
// ---- 扫描助手:抓 if (<lock> == null) { … } 的分支体(含大括号配对,注释已剥) ----
|
||||
|
||||
private static List<String> lockNullBranches(String sourceWithoutComments) {
|
||||
List<String> bodies = new ArrayList<>();
|
||||
Matcher m = LOCK_NULL_CHECK.matcher(sourceWithoutComments);
|
||||
while (m.find()) {
|
||||
int open = m.end() - 1;
|
||||
int close = matchingBrace(sourceWithoutComments, open);
|
||||
if (close > open) {
|
||||
bodies.add(sourceWithoutComments.substring(open + 1, close));
|
||||
}
|
||||
}
|
||||
return bodies;
|
||||
}
|
||||
|
||||
/** 朴素大括号配对(剥注释后字符串字面量里的大括号仍可能干扰,够用即止:只在判空分支上用)。 */
|
||||
private static int matchingBrace(String text, int openIndex) {
|
||||
int depth = 0;
|
||||
for (int i = openIndex; i < text.length(); i++) {
|
||||
char c = text.charAt(i);
|
||||
if (c == '{') {
|
||||
depth++;
|
||||
} else if (c == '}') {
|
||||
depth--;
|
||||
if (depth == 0) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
private static List<Path> mainSources() {
|
||||
Path root = moduleRoot().resolve("src/main/java");
|
||||
try (Stream<Path> walk = Files.walk(root)) {
|
||||
List<Path> files = walk.filter(p -> p.toString().endsWith(".java"))
|
||||
.sorted(Comparator.comparing(Path::toString))
|
||||
.toList();
|
||||
assertThat(files).as("src/main/java 扫到的 .java 数(扫不到就是路径坏了)")
|
||||
.hasSizeGreaterThan(900);
|
||||
return files;
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException("扫描失败: " + root, e);
|
||||
}
|
||||
}
|
||||
|
||||
private static Path moduleRoot() {
|
||||
Path here = Path.of("").toAbsolutePath();
|
||||
if (Files.isDirectory(here.resolve("src/main/java"))) {
|
||||
return here;
|
||||
}
|
||||
Path nested = here.resolve("backend-java");
|
||||
if (Files.isDirectory(nested.resolve("src/main/java"))) {
|
||||
return nested;
|
||||
}
|
||||
throw new IllegalStateException("无法定位 backend-java 源码目录(cwd=" + here + ")");
|
||||
}
|
||||
|
||||
private static String read(Path file) {
|
||||
try {
|
||||
return Files.readString(file);
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException("读不了 " + file, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
package com.nanri.aiimage.common.task;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import ch.qos.logback.classic.Logger;
|
||||
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||
import ch.qos.logback.core.read.ListAppender;
|
||||
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* 分布式锁跳过出口({@link LockSkipWitness})的判据(2026-10-09 评审「稳定 5.5」项 1)。
|
||||
*
|
||||
* <p>这条判据要钉住的是<b>两件事</b>,不是两件里的一件:
|
||||
* <ol>
|
||||
* <li>锚点字面量真的打在日志上(能被巡检 grep);</li>
|
||||
* <li>调用它确实<b>累计</b>得出数(可聚合,不是"记了一行没人看的日志")。</li>
|
||||
* </ol>
|
||||
* 只判第 1 件就会重演 2026-10-09 踩过的坑:锚点方法存在、零调用者,判据恒绿而现网照旧。
|
||||
* 调用面由 {@link LockSkipSilentExitGuardrailTest} 按点位台账逐处钉住,两支合起来才是"出口在响"。
|
||||
*/
|
||||
class LockSkipWitnessTest {
|
||||
|
||||
@AfterEach
|
||||
void unbindRegistry() {
|
||||
LockSkipWitness.bind(null);
|
||||
}
|
||||
|
||||
private ListAppender<ILoggingEvent> capture() {
|
||||
Logger logger = (Logger) LoggerFactory.getLogger(LockSkipWitness.class);
|
||||
ListAppender<ILoggingEvent> appender = new ListAppender<>();
|
||||
appender.start();
|
||||
logger.addAppender(appender);
|
||||
return appender;
|
||||
}
|
||||
|
||||
private void release(ListAppender<ILoggingEvent> appender) {
|
||||
((Logger) LoggerFactory.getLogger(LockSkipWitness.class)).detachAppender(appender);
|
||||
}
|
||||
|
||||
@Test
|
||||
void recordEmitsAnchorLineWithAggregationFields() {
|
||||
ListAppender<ILoggingEvent> captured = capture();
|
||||
try {
|
||||
long before = LockSkipWitness.total();
|
||||
LockSkipWitness.record("test:anchor-shape", LockSkipWitness.OUTCOME_SKIPPED, "PUBLISH", 123L);
|
||||
List<String> messages = captured.list.stream().map(ILoggingEvent::getFormattedMessage).toList();
|
||||
|
||||
assertThat(messages).as("走到跳过分支必须留下一行日志").hasSize(1);
|
||||
String line = messages.get(0);
|
||||
// 锚点 + 聚合维度都得在这一行里,巡检才分得出是哪个点位、挡了多少
|
||||
assertThat(line).contains(LockSkipWitness.ANCHOR)
|
||||
.contains("point=test:anchor-shape")
|
||||
.contains("outcome=skipped")
|
||||
.contains("moduleType=PUBLISH")
|
||||
.contains("taskId=123");
|
||||
assertThat(captured.list.get(0).getLevel().toString()).isEqualTo("WARN");
|
||||
assertThat(LockSkipWitness.total()).as("同一行也必须进台账计数").isEqualTo(before + 1);
|
||||
} finally {
|
||||
release(captured);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void ledgerAggregatesPerPointAndSnapshotIsReadable() {
|
||||
LockSkipWitness.resetLedgerForTests();
|
||||
LockSkipWitness.recordSkip("test:agg-a", "BRAND", 1L);
|
||||
LockSkipWitness.recordSkip("test:agg-a", "BRAND", 2L);
|
||||
LockSkipWitness.abandoned("test:agg-b");
|
||||
|
||||
assertThat(LockSkipWitness.countOf("test:agg-a")).isEqualTo(2);
|
||||
assertThat(LockSkipWitness.countOf("test:agg-b")).isEqualTo(1);
|
||||
assertThat(LockSkipWitness.countOf("test:never-recorded")).as("没记过的点位读数必须是 0 而不是抛").isZero();
|
||||
assertThat(LockSkipWitness.snapshot())
|
||||
.as("快照要能一次看全点位(巡检/告警的取数面)")
|
||||
.containsEntry("test:agg-a", 2L)
|
||||
.containsEntry("test:agg-b", 1L);
|
||||
assertThat(LockSkipWitness.total()).isEqualTo(3);
|
||||
}
|
||||
|
||||
@Test
|
||||
void skippedAndAbandonedAreTwoDifferentOutcomes() {
|
||||
LockSkipWitness.resetLedgerForTests();
|
||||
ListAppender<ILoggingEvent> captured = capture();
|
||||
try {
|
||||
LockSkipWitness.recordSkip("test:outcome-skipped", "PUBLISH", 7L);
|
||||
LockSkipWitness.recordAbandoned("test:outcome-abandoned", "PUBLISH", 8L);
|
||||
List<String> lines = captured.list.stream().map(ILoggingEvent::getFormattedMessage).toList();
|
||||
|
||||
assertThat(lines).hasSize(2);
|
||||
assertThat(lines.get(0)).contains("outcome=skipped");
|
||||
assertThat(lines.get(1)).contains("outcome=abandoned");
|
||||
// 两种结果都得进台账——只有一种被数到就等于另一种仍然没有出口
|
||||
assertThat(LockSkipWitness.snapshot()).containsKeys("test:outcome-skipped", "test:outcome-abandoned");
|
||||
} finally {
|
||||
release(captured);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void micrometerCounterCarriesPointAndOutcomeTagsWhenBound() {
|
||||
LockSkipWitness.resetLedgerForTests();
|
||||
SimpleMeterRegistry registry = new SimpleMeterRegistry();
|
||||
LockSkipWitness.bind(registry);
|
||||
try {
|
||||
LockSkipWitness.record("test:metric-shape", LockSkipWitness.OUTCOME_ABANDONED, "SIMILAR_ASIN", 9L);
|
||||
|
||||
List<String> found = new ArrayList<>();
|
||||
for (var meter : registry.getMeters()) {
|
||||
if (LockSkipWitness.METRIC.equals(meter.getId().getName())) {
|
||||
found.add(meter.getId().getTag("point") + "/" + meter.getId().getTag("outcome")
|
||||
+ "/" + meter.getId().getTag("moduleType"));
|
||||
}
|
||||
}
|
||||
assertThat(found).as("指标必须带得上点位/结果/模块三个聚合标签").containsExactly(
|
||||
"test:metric-shape/abandoned/SIMILAR_ASIN");
|
||||
double value = registry.get(LockSkipWitness.METRIC)
|
||||
.tag("point", "test:metric-shape")
|
||||
.counter()
|
||||
.count();
|
||||
assertThat(value).isEqualTo(1.0);
|
||||
assertThat(registry.get(LockSkipWitness.METRIC + ".total").gauge().value())
|
||||
.as("总览 gauge 也在,读数为零时能区分「没人被挡」和「指标没接上」")
|
||||
.isGreaterThanOrEqualTo(1.0);
|
||||
} finally {
|
||||
registry.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingContextLandsOnKnownBucketInsteadOfThrowing() {
|
||||
LockSkipWitness.resetLedgerForTests();
|
||||
ListAppender<ILoggingEvent> captured = capture();
|
||||
try {
|
||||
// 点位缺失 + 模块缺失:不能抛,也不能悄悄丢掉这次记录
|
||||
LockSkipWitness.record(null, null, " ", null);
|
||||
assertThat(captured.list).hasSize(1);
|
||||
assertThat(captured.list.get(0).getFormattedMessage())
|
||||
.contains("point=unpointed")
|
||||
.as("缺失的 outcome 单独进 unknown 桶,不许折叠进 skipped/abandoned 那两个真桶")
|
||||
.contains("outcome=unknown")
|
||||
.contains("moduleType=unknown");
|
||||
assertThat(LockSkipWitness.countOf("unpointed")).isEqualTo(1);
|
||||
assertThat(LockSkipWitness.snapshot()).containsKey("unpointed");
|
||||
} finally {
|
||||
release(captured);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void ledgerStopsGrowingPastItsKeyCeilingButKeepsCounting() {
|
||||
LockSkipWitness.resetLedgerForTests();
|
||||
for (int i = 0; i < LockSkipWitness.LEDGER_KEYS_MAX + 60; i++) {
|
||||
LockSkipWitness.record("test:flood-" + i, LockSkipWitness.OUTCOME_SKIPPED, null, null);
|
||||
}
|
||||
assertThat(LockSkipWitness.snapshot())
|
||||
.as("点位键数封顶,不被未知点位撑爆内存")
|
||||
.hasSizeLessThanOrEqualTo(LockSkipWitness.LEDGER_KEYS_MAX + 1);
|
||||
assertThat(LockSkipWitness.snapshot()).containsKey("overflow");
|
||||
assertThat(LockSkipWitness.total())
|
||||
.as("封顶只影响键的数量,不影响总次数:一次都不能少记")
|
||||
.isEqualTo(LockSkipWitness.LEDGER_KEYS_MAX + 60L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anchorLiteralIsTheContractInspectionGreps() {
|
||||
// 巡检/告警按这条字面量匹配;改它等于删掉现网规则,所以这里钉死字面值
|
||||
assertThat(LockSkipWitness.ANCHOR).isEqualTo("[lock-skip]");
|
||||
assertThat(LockSkipWitness.METRIC).isEqualTo("aiimage.distributed.lock.skip");
|
||||
|
||||
// 另一半:锚点必须真被 record() 打进日志(不是只当常量挂着)——上一条用例已实测,
|
||||
// 这里再钉一次源码形状,防止有人把 log.warn 里的 ANCHOR 换成写死的别的字符串。
|
||||
String source = com.nanri.aiimage.testutil.SourceScan.withoutComments(
|
||||
com.nanri.aiimage.testutil.SourceScan.sourceText("LockSkipWitness.java"));
|
||||
assertThat(source).as("record() 里的日志必须带锚点参数").contains("ANCHOR, key");
|
||||
}
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
package com.nanri.aiimage.common.task;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
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.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* 待删对象日志:入队追加、启动回放、收敛重写。对应审查项 D13(删除补偿队列重启即丢)。
|
||||
*/
|
||||
class PendingDeleteJournalTest {
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
@Test
|
||||
void recordThenReadAllReturnsAdmittedKeysInOrder() {
|
||||
PendingDeleteJournal journal = new PendingDeleteJournal(tempDir.resolve("nested/queue.log"), 100);
|
||||
|
||||
journal.record("a/1.bin");
|
||||
journal.record("b/2.bin");
|
||||
journal.record("a/1.bin");
|
||||
|
||||
assertEquals(List.of("a/1.bin", "b/2.bin"), journal.readAll());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rewriteKeepsOnlyRemainingAndDropsFileWhenEmpty() throws Exception {
|
||||
Path path = tempDir.resolve("queue.log");
|
||||
PendingDeleteJournal journal = new PendingDeleteJournal(path, 100);
|
||||
journal.record("keep.bin");
|
||||
journal.record("done.bin");
|
||||
|
||||
journal.rewrite(List.of("keep.bin"));
|
||||
assertEquals(List.of("keep.bin"), journal.readAll());
|
||||
|
||||
journal.rewrite(List.of());
|
||||
assertFalse(Files.exists(path), "队列收敛为空后日志文件应删除");
|
||||
assertEquals(List.of(), journal.readAll());
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingFileYieldsEmptyInsteadOfThrowing() {
|
||||
PendingDeleteJournal journal = new PendingDeleteJournal(tempDir.resolve("not-created.log"), 10);
|
||||
assertEquals(List.of(), journal.readAll());
|
||||
}
|
||||
|
||||
@Test
|
||||
void blankAndMultilineRecordsAreSanitizedOrIgnored() throws Exception {
|
||||
Path path = tempDir.resolve("queue.log");
|
||||
PendingDeleteJournal journal = new PendingDeleteJournal(path, 10);
|
||||
|
||||
journal.record(null);
|
||||
journal.record(" ");
|
||||
journal.record("bad\nkey.bin");
|
||||
journal.record(" good.bin ");
|
||||
|
||||
assertEquals(List.of("bad key.bin", "good.bin"), journal.readAll());
|
||||
// 单行一条记录:换行被替换,不会破坏行结构
|
||||
assertEquals(2, Files.readAllLines(path, StandardCharsets.UTF_8).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void corruptedLineIsIgnoredWhileValidOnesSurvive() throws Exception {
|
||||
Path path = tempDir.resolve("queue.log");
|
||||
Files.createDirectories(tempDir);
|
||||
Files.writeString(path, "\n \nvalid.bin\n", StandardCharsets.UTF_8);
|
||||
|
||||
PendingDeleteJournal journal = new PendingDeleteJournal(path, 10);
|
||||
|
||||
assertEquals(List.of("valid.bin"), journal.readAll());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rewriteRespectsMaxEntriesCap() {
|
||||
PendingDeleteJournal journal = new PendingDeleteJournal(tempDir.resolve("queue.log"), 2);
|
||||
|
||||
journal.rewrite(List.of("k1.bin", "k2.bin", "k3.bin"));
|
||||
|
||||
assertEquals(List.of("k1.bin", "k2.bin"), journal.readAll());
|
||||
assertTrue(journal.readAll().size() <= 2);
|
||||
}
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
package com.nanri.aiimage.common.task;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class StaleTaskDeathReasonTest {
|
||||
|
||||
private static final LocalDateTime T = LocalDateTime.of(2026, 10, 1, 12, 34, 5);
|
||||
|
||||
@Test
|
||||
void neverUploadedSaysNoResultUploadedNotThatPythonCrashed() {
|
||||
String reason = new StaleTaskDeathReason(0L, null, T, null, false, 30).describe();
|
||||
assertTrue(reason.contains("未回传任何检测结果"), reason);
|
||||
assertTrue(reason.contains("超过 30 分钟无进展"), reason);
|
||||
assertTrue(reason.contains("最后心跳 10-01 12:34"), reason);
|
||||
assertFalse(reason.contains("Python"), reason);
|
||||
assertFalse(reason.contains("最后上报"), reason);
|
||||
}
|
||||
|
||||
@Test
|
||||
void queuedTaskIsToldApartFromACrashedOneByTheReportedPhase() {
|
||||
String reason = new StaleTaskDeathReason(0L, null, T, "排队等待空闲槽位", false, 30).describe();
|
||||
assertTrue(reason.contains("最后上报 排队等待空闲槽位"), reason);
|
||||
assertFalse(reason.contains("已收到"), reason);
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingHeartbeatAndBlankPhaseDegradeQuietly() {
|
||||
String reason = new StaleTaskDeathReason(0L, null, null, " ", false, 30).describe();
|
||||
assertTrue(reason.contains("最后心跳 时间未知"), reason);
|
||||
assertFalse(reason.contains("最后上报"), reason);
|
||||
}
|
||||
|
||||
@Test
|
||||
void interruptedUploadReportsChunksAndLastChunkTime() {
|
||||
String reason = new StaleTaskDeathReason(7L, T, T, "第 120/500 组", false, 30).describe();
|
||||
assertTrue(reason.contains("客户端回传中断"), reason);
|
||||
assertTrue(reason.contains("已收到 7 个分片,最后一次 10-01 12:34"), reason);
|
||||
assertTrue(reason.contains("最后上报 第 120/500 组"), reason);
|
||||
assertFalse(reason.contains("结果文件生成"), reason);
|
||||
}
|
||||
|
||||
@Test
|
||||
void exhaustedFileJobBlamesFileGenerationInsteadOfTheClient() {
|
||||
String reason = new StaleTaskDeathReason(7L, T, T, "第 120/500 组", true, 30).describe();
|
||||
assertTrue(reason.contains("结果文件生成多次失败"), reason);
|
||||
assertFalse(reason.contains("回传中断"), reason);
|
||||
}
|
||||
|
||||
@Test
|
||||
void exhaustedFileJobWithoutAnyChunkStillReportsClientSilence() {
|
||||
String reason = new StaleTaskDeathReason(0L, null, T, null, true, 30).describe();
|
||||
assertTrue(reason.contains("未回传任何检测结果"), reason);
|
||||
assertFalse(reason.contains("结果文件生成"), reason);
|
||||
}
|
||||
|
||||
@Test
|
||||
void nonPositiveTimeoutNeverPrintsZeroMinutes() {
|
||||
assertTrue(new StaleTaskDeathReason(0L, null, null, null, false, 0)
|
||||
.describe().contains("超过 1 分钟"));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user