Compare commits

..

14 Commits

Author SHA1 Message Date
huangzd1997 479114cf95 test(phase-3): 3D 收口——publish 建单段 golden 落地,七支「先补再动」最后一格缺口闭合
PublishTaskService 一字未改。新落 PublishCreateTaskSnapshotTest(吃真入口
parseAndCreateTask)+ publish/golden/create-task-snapshot.txt:7 段场景由
7 支执行用例渲染,第 8 支是写档器(无 SHUFU_SNAPSHOT_WRITE 即 skip)。

补这支的理由:3D 迁移本体当时把 newTaskHeader/insertTask/newScopeRow 换成底座件,
等值证据只有「旧块/现块/底座件体做 setter 差集」——推理级证据,不是可复跑的防线。
本支在册两条快照都碰不到建单:PublishBatchLoadingSnapshotEquivTest 吃读侧
(history/dashboard/getTaskDetail/getTaskProgress),PublishSubmitResultSnapshotTest
吃 submitResult。

钉住的现网形状(逐段读 golden 得来,非推测):
1. 解析在事务外、落库在事务内:tx.begin→task.insert→file.insert→item.insertBatch
   →result.insert→tx.commit,一次 execute();
2. 建单时刻一枚复用给头行/文件行/结果行(同一枚引用),而 insertRows 自己再取一次
   now ⇒ 行项目 createdAt 与之不同——这条不对称由 itemCreatedAtEqualsTaskNow=false 钉住;
3. 文件解析失败不抛只标 FAILED,有一个可用任务仍 PENDING;全失败才 FAILED
   +「全部文件解析或店铺匹配失败」+ finishedAt,且结果行照插(rowCount=0);
4. 计数与落库不同径:totalRows/rowCount 取 rows.size() 含 null,insertRows 跳 null;
   0 行不调 insertBatch 但文件仍 PENDING、任务照样建起来;
5. 结果行 success 写 0(AP 留 NULL、ShopDataCrawl 写 -1,三种形状);
6. 行内品牌在落库那格过 BrandLabel.strip:"品牌: 耐克"→"耐克"、
   "Brand: NIKE: X"→"NIKE: X"(只剥行首一枚标签)、全角冒号同样剥。

两处夹具自踩(都是「不判红就看不见的假证据」那一族):① 兜底 stub 若用 when(any())
注册在调用方 when("shop-a") 之后,Mockito 后注册者优先会把具体桩顶掉 ⇒ 匹配分流
收敛成一枚 thenAnswer;② tx.begin 整条不含空格,照 AP 那版 substring(0, indexOf(' '))
取事件名当场越界 ⇒ 补 eventKind 容错。

门禁:mvn -o test-compile rc=0;整类 9 例/0 红/1 skip;定向(Publish* 全面+
SourceScan/TaskModuleCoverage/CatchSilence/ArchitectureBoundary/LockSkip/
TaskStatusVocabulary/TaskLifecycleDebt/ForbiddenLogAudit/SqlLayering/
TaskServiceWiringSlice)205 例/0 红/2 skip;后端整量单跑 4616 例/0 红/0 错/
17 skipped,BUILD SUCCESS,真实 rc=0;golden 非写模式逐字节复现,
git status 仅本笔两件、其余快照一字未动。ops 面 ruff All checks passed。
真机启动验收本格仍欠(本机无 MySQL/Redis 监听,本笔零生产码改动)。
2026-10-21 00:07:10 +08:00
huangzd1997 74384fa6ac fix(brand-check): 补测耗尽通知按失败类别说话,代理套餐问题不再算成上游的锅
16890 改烧任务归属用户自己的代理提取链接后,失败主因从上游不可用变成用户侧套餐:
现网 12 分钟内 18 条「全部 N 把代理 key 处于冷却」、4 条「余额不足」。而耗尽通知仍一律写
「上游商标库持续不可用,建议稍后重新提交采集任务重跑这些 ASIN」——既把账算到别人头上,
又把人推向"重跑必然还是同样失败"的那条路。

- 新增 BrandCheckFailureNotice:原始原因 → Kind(未配置/套餐耗尽/冷却/出口被拒/技术性/上游),
  每类给一句"发生了什么 + 该做什么",代理侧全部指向「密钥设置」的「代理设置」。
- 拒付判定排在冷却之前:key 因余额不足被拒后整批写冷却,只报冷却等于让用户白等。
- pushRecheckOutcome 多收一个 Kind,耗尽分支改用它给的句子;last_error 照库存原文供后台取证。
- 30 支用例(分类器 9 / 通知 7 / 调度 10,含冷却原话透传到通知那支),判据串取自现网读到的原文。
2026-10-20 23:05:29 +08:00
huangzd1997 b9fb25c270 fix(brand-label): 品牌检测链读写两端接上 BrandLabel,解析处单点清洗
onRow 落 row map 时就把品牌列的标签前缀剥掉:查询集 uniqueBrands、与执行方回传值的匹配、
结果文件里那一格必须是同一个字符串。只在写出端剥会让比对两边分家——判为"不符合"的行剔不掉,
用户把没通过的行当成已通过上架。纯标签值("Brand:")洗完即空,与"这行没填品牌"走同一条路径,
不再送给上游当 Solr 字段限定符(2026-10-08 单日 19,247 次 undefined field Brand 的起点)。

normalizeBrandSet 与 normalizeBrandSetFromInvalids 也归一:执行方刻意回传原值(失败清单要能对
得上用户表里那一行),服务端两侧同口径才命中,legacy 脏分片照样剔得掉。
「不符合品牌」与「查询失败品牌」两张 sheet 的写出各兜一次——后者本身就是被打回的品牌清单,
用户改完直接再传,这一格不洗就把同一个脏值原样送回链路。

BrandTaskServiceResultRowsTest 里 "Brand: CC" 那条出件断言按新口径改为 "CC"(那张表用户会再传),
另加一条钉住"查询集与出件同口径、纯标签行不算品牌"。

门禁:隔离 worktree(HEAD + 本笔两文件)跑 mvn -o test 全量 4595 例 0 红。本仓工作树此刻另有
一路在飞的 brand/support 抽取(NotificationDispatchService 签名未接完),全量读数只在隔离树取。
2026-10-20 22:55:28 +08:00
huangzd1997 cdef922251 fix(brand-label): 品牌标签清洗抽公共件,六模块读写两端统一过出口
PublishBrandLabel 从 publish 私有件搬入 common/util/BrandLabel(三条守卫尺子随迁:
唯一副本、实体写出不许绕过、解析端不许重复实现),品牌列的读入与出件两端都走这一处。

读入端接上:asincache 缓存落库、invalidasin 人工黑名单(先洗再判空——键对不上是静默失效,
比脏值出件更难发现)、appearancepatent resolveBrand(两条取值分支同一个串)、collectdata
入库、shopdatacrawl copyRow/sameRow/rowDedupKey(键与值分家会让同一行跨分片重复出件)、
撞款解析与 re-baseline、dedupe 按表头名只洗品牌列。
写出端接上:publish/similarasin×2/appearancepatent/collectdata/撞款 csv+xlsx/shopdatacrawl。

rows-snapshot golden 里品牌格去掉首尾空格:正本 strip 自 2026-10-08 就含 trim,
Java/Python/MySQL 三处同形,不是这次新加的行为。

门禁:后端 mvn -o test 4594 例 0 红。BrandTaskService(含四张 sheet 出件与解析端匹配)
因同仓另一路在飞改动未动,见 docs/audit/BACKLOG.md B5。
2026-10-20 22:35:25 +08:00
huangzd1997 e855801237 refactor(brand-check): 归属用户读取下沉为 SecretUsageContext.currentUserId()
上一笔在 AppearancePatentLlmClient 里就地取上下文(+6 行),把那支已进超长点名
台账的文件从 1465 顶到 1471,可读棘轮按对象判红。改为未入册的 SecretUsageContext
提供一个静态访问器(含「无上下文就不该打上游」的口径),调用点回到一行——该文件
现在 1464 行,比基线还短一行。AP/品牌相关 273 例全绿,test-compile 零错误。
2026-10-20 20:54:47 +08:00
huangzd1997 3500feb921 fix(brand-check): 出表整读源文件展开全量行——同品牌不同 ASIN 不再被删
任务 2735 复盘:品牌检测解析阶段按品牌删行后,同一份行集既当执行方查询清单
又当出表数据源,904 行源文件结果只剩 173 行。现解析器加 dedupeRowsByBrand
开关,payload 仍逐品牌一行(执行方按行提品牌,不重烧代理),组装时用真实源
文件整读展开全量行;不符合/未检测品牌的挪 sheet 语义不变。
新增 BrandTaskServiceResultRowsTest 4 例,Abort 夹具换真实 Excel 并钉双 ASIN 保行。
2026-10-20 20:49:19 +08:00
huangzd1997 e71a1077af fix(brand-check): 缓存测试两处 verify 补齐第 4 位 userId 匹配器
后端全量 4574 例复跑抓到:checkAll 已是 (brands, strategy, budgetMillis, userId)
四参重载,captor 版 verify 仍写三位 ⇒ Mockito 判「参数不同」。上一笔只按 13 类
点名复跑,漏圈了这支随迁移一并改过的第 15 文件。
2026-10-20 20:15:10 +08:00
huangzd1997 6c14f29a87 feat(brand-check): 品牌检测按任务归属用户取代理并计用量——三处调用接入
- BrandCheckClient 契约扩展:构造器收 UserApiSecretService,check/checkAll/
  checkTitleText(s) 全系带 userId,请求体新增 user_id + proxy_url(proxy 取自
  用户密钥库 module=proxy);响应新增 reason/retryable,retryable=false(供应商
  拒付、用户没配代理)当场停重试阶梯并短路整批
- 三处调用方接入:CollectDataService 品牌过滤、CollectDataBrandRecheckScheduler
  补测(markAttempted 带真实原因)、AppearancePatentLlmClient 标题查标(取
  SecretUsageContext 归属用户)
- 用户未配置代理:整批本地定论「用户未配置代理」,零 HTTP,不再有平台钥匙兜底
- 测试迁移:15 支测试文件按新契约迁移(3 参构造、userId 实参、BrandCheckBatchResult
  第 4 位 reason、Mockito 匹配器加宽);HTTP 类测试 stub findPlainValue 非空代理
  以绕开零 HTTP 短路。13 类 119 例全绿(1 skip 为既有快照写盘门),test-compile 零错误
2026-10-20 18:14:52 +08:00
huangzd1997 492a27270a refactor(phase-3): 3A 拆薄第十一笔——AP 结果作业与出表出件,服务 1827→1409 2026-10-20 17:58:54 +08:00
huangzd1997 3a22267b0d refactor(phase-3): 3A 拆薄第十笔——AP 交付闸门与补检出件,服务 1942→1827 2026-10-20 16:49:59 +08:00
huangzd1997 56e5a58b18 refactor(phase-3): 3A 拆薄第九笔——AP 回传分片 prepare/persist/scope 出件,服务 2161→1942 2026-10-20 15:54:13 +08:00
huangzd1997 421d9da1b3 refactor(phase-3): 3A 拆薄第八笔——AP 进度与视图组装出件,服务 2377→2161
G 聚类(看板/历史/批量进度、文件构建进度百分比与快照落库)原样搬进
AppearancePatentProgressSupport;四个公开入口与 saveFileBuildProgress
保留同名薄委托。SourceScan 面数 34→35、support 11→12 并点名新件。
2026-10-20 15:23:06 +08:00
huangzd1997 a765468a9f refactor(phase-3): 3A 拆薄第六七笔——AP 载荷与结果行读取出件,服务 2801→2377
I 聚类(解析/分片载荷组装、读取、事务后删除)进 AppearancePatentPayloadSupport;
H 聚类(回传分组展开、解析行计数、分片载荷读取、分页结果行与行键口径)进
AppearancePatentResultRowReader。归一、归属、分组、afterCommit 与解析载荷读取
仍由服务回调交出。SourceScan 面数 32→34、support 9→11 并逐枚点名新件。
2026-10-20 15:11:53 +08:00
huangzd1997 4bcce9d534 refactor(phase-3): 3A 拆薄第五笔——外观专利 LLM 批管线出件,服务 3135→2801
B 聚类(候选收集、批调度、轮次判死、结果行合并、批计数)原样搬进
service/support/AppearancePatentLlmBatchPipeline;读分片、分片合并、
心跳、封口判定仍留在服务侧,以回调交入。四枚同名入口保留为测试
按名反射的接缝;SourceScanTest 面数 31→32、support 8→9 并逐枚点名新件。
2026-10-20 14:03:18 +08:00
73 changed files with 5046 additions and 2210 deletions
@@ -1,19 +1,23 @@
package com.nanri.aiimage.modules.publish.service;
package com.nanri.aiimage.common.util;
import java.util.regex.Pattern;
/**
* 上架链路上品牌值的唯一清洗出口:剥掉 {@code Brand: } 这类"字段标签 + 冒号"前缀。
* 品牌值的唯一清洗出口:剥掉 {@code Brand: } 这类"字段标签 + 冒号"前缀。全仓只此一份,
* 读入(解析上传的 Excel、接收客户端回传的行)与写出(出件写 cell)两端都走它。
*
* <p>亚马逊详情页把卖家名渲染成 "Brand: XXX",用户从页面复制进 Excel 就会带上前缀。
* 该值进 WIPO 品牌库查询时会被当 Solr 字段限定符({@code undefined field Brand} → 上游 500),
* 10-08 单日被顶着重跑 30 轮、连带把品牌全局锁持到 1h45m,压死 11 个别的用户的任务。
*
* <p>清洗必须落在这里而不是某个调用点:{@code biz_publish_item.brand} 有两个写入来源
* <p>清洗必须落在这一处而不是某个调用点:{@code biz_publish_item.brand} 有两个写入来源
* (服务端 Excel 解析、客户端结果分片回传 {@code replaceRows}),历史上只堵了前者,
* 后者在任务完成时整表删后重插,把脏值又写回去。
*
* <p>读写两端都要过一遍,是因为干净值不等于干净文件:出件是用户的下一份上传物,
* 任何一个出件漏剥,用户下载再上传就把脏值送回链路里,清洗脚本的账也随之作废。
*/
public final class PublishBrandLabel {
public final class BrandLabel {
/**
* 只剥行首的一个标签,且要求冒号紧跟其后:{@code Brands: NIKE} 与 {@code Brand: NIKE: X}
@@ -22,7 +26,7 @@ public final class PublishBrandLabel {
private static final Pattern LABEL_PREFIX = Pattern.compile(
"(?i)^\\s*(?:brand|品牌|marke|marca|marque|marka)\\s*[::]\\s*");
private PublishBrandLabel() {
private BrandLabel() {
}
public static String strip(String value) {
@@ -1042,7 +1042,7 @@ public class AppearancePatentLlmClient {
BrandCheckClient.BrandCheckBatchResult[] byRowIndex =
new BrandCheckClient.BrandCheckBatchResult[results.size()];
if (!pending.isEmpty()) {
List<BrandCheckClient.BrandCheckBatchResult> batch = brandCheckClient.checkTitleTexts(titles, "Terms");
List<BrandCheckClient.BrandCheckBatchResult> batch = brandCheckClient.checkTitleTexts(titles, "Terms", SecretUsageContext.currentUserId());
for (int k = 0; k < pending.size(); k++) {
byRowIndex[pending.get(k)] = batch.get(k);
}
@@ -0,0 +1,362 @@
package com.nanri.aiimage.modules.appearancepatent.service.support;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.task.TaskResultAdmission;
import com.nanri.aiimage.common.task.TaskStatuses;
import com.nanri.aiimage.modules.appearancepatent.model.dto.AppearancePatentResultRowDto;
import com.nanri.aiimage.modules.appearancepatent.model.dto.AppearancePatentSubmitResultRequest;
import com.nanri.aiimage.modules.appearancepatent.service.AppearancePatentTaskCacheService;
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
import com.nanri.aiimage.modules.task.mapper.TaskChunkMapper;
import com.nanri.aiimage.modules.task.mapper.TaskScopeStateMapper;
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import com.nanri.aiimage.modules.task.model.entity.TaskChunkEntity;
import com.nanri.aiimage.modules.task.model.entity.TaskScopeStateEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import java.time.LocalDateTime;
import java.util.List;
/**
* 外观专利的分片回传与范围状态(D 聚类),从 {@code AppearancePatentTaskService}
* <b>原样搬移</b>(3A 拆薄第九笔):prepare/persist/complete 三段、Python 超时封口、
* 范围状态 upsert 与分片计数,连同事务边界之外的纯计算形状、重复分片的短路与日志一字没改。
*
* <p><b>搬的是分片落库,不是宿主能力。</b>任务加载(底座准入)、归属校验、回传分组展开、
* 解析行计数、载荷写入、序列化出口、任务收尾都还留在服务侧,以回调交进来——
* 它们分属底座/B/H/I/E 聚类,跟着 D 一起拖出来会把依赖面放大。
*/
@Slf4j
public class AppearancePatentChunkSubmissionSupport {
@FunctionalInterface
public interface SubmissionTaskLoader {
FileTaskEntity load(Long taskId);
}
@FunctionalInterface
public interface OwnershipChecker {
void check(FileTaskEntity task, String operation);
}
@FunctionalInterface
public interface RowFlattener {
List<AppearancePatentResultRowDto> flatten(AppearancePatentSubmitResultRequest request);
}
@FunctionalInterface
public interface RowCounter {
int count(FileTaskEntity task);
}
@FunctionalInterface
public interface ChunkPayloadWriter {
String store(Long taskId, String scopeHash, Integer chunkIndex, String payloadJson);
}
@FunctionalInterface
public interface JsonWriter {
String write(Object value, String failureMessage);
}
@FunctionalInterface
public interface TaskFinalizer {
void finalizeTask(FileTaskEntity task, String error, int rowCount, boolean assembleWorkbook);
}
@FunctionalInterface
public interface FirstNonBlank {
String pick(String preferred, String fallback);
}
public record SubmitContext(FileTaskEntity task,
String scopeKey,
String scopeHash,
Integer chunkIndex,
boolean forceFlush,
String error) {
}
public record PreparedSubmittedChunk(FileTaskEntity task,
String scopeKey,
String scopeHash,
Integer chunkIndex,
Integer chunkTotal,
boolean done,
String error,
String payloadJson,
String storedPayload,
String payloadHash) {
}
private static final String STATUS_RUNNING = TaskStatuses.FileTask.RUNNING;
private final String moduleType;
private final FileTaskMapper fileTaskMapper;
private final TaskChunkMapper taskChunkMapper;
private final TaskScopeStateMapper taskScopeStateMapper;
private final AppearancePatentTaskCacheService taskCacheService;
private final SubmissionTaskLoader taskLoader;
private final OwnershipChecker ownershipChecker;
private final RowFlattener rowFlattener;
private final RowCounter rowCounter;
private final ChunkPayloadWriter chunkPayloadWriter;
private final JsonWriter jsonWriter;
private final TaskFinalizer finalizer;
private final FirstNonBlank firstNonBlank;
public AppearancePatentChunkSubmissionSupport(String moduleType,
FileTaskMapper fileTaskMapper,
TaskChunkMapper taskChunkMapper,
TaskScopeStateMapper taskScopeStateMapper,
AppearancePatentTaskCacheService taskCacheService,
SubmissionTaskLoader taskLoader,
OwnershipChecker ownershipChecker,
RowFlattener rowFlattener,
RowCounter rowCounter,
ChunkPayloadWriter chunkPayloadWriter,
JsonWriter jsonWriter,
TaskFinalizer finalizer,
FirstNonBlank firstNonBlank) {
this.moduleType = moduleType;
this.fileTaskMapper = fileTaskMapper;
this.taskChunkMapper = taskChunkMapper;
this.taskScopeStateMapper = taskScopeStateMapper;
this.taskCacheService = taskCacheService;
this.taskLoader = taskLoader;
this.ownershipChecker = ownershipChecker;
this.rowFlattener = rowFlattener;
this.rowCounter = rowCounter;
this.chunkPayloadWriter = chunkPayloadWriter;
this.jsonWriter = jsonWriter;
this.finalizer = finalizer;
this.firstNonBlank = firstNonBlank;
}
/**
* /result 提交的纯计算阶段(无事务注解):读任务 + 校验归属 + 分组展开 +
* 序列化 + payload 存储 + 哈希预计算,全部在事务开始前完成。
* 重复 chunk(查重命中)时不做存储与哈希,落库由 persist 按同一查重短路。
*/
public PreparedSubmittedChunk prepareSubmittedChunk(Long taskId, AppearancePatentSubmitResultRequest request) {
FileTaskEntity task = taskLoader.load(taskId);
ownershipChecker.check(task, "submit result");
int chunkIndex = request.getChunkIndex() == null ? 0 : request.getChunkIndex();
int chunkTotal = request.getChunkTotal() == null ? 1 : request.getChunkTotal();
boolean done = Boolean.TRUE.equals(request.getDone());
String scopeKey = firstNonBlank.pick(request.getSubmissionId(), "task:" + taskId);
String scopeHash = DigestUtil.sha256Hex(scopeKey);
TaskChunkEntity existing = taskChunkMapper.selectOne(new LambdaQueryWrapper<TaskChunkEntity>()
.eq(TaskChunkEntity::getTaskId, taskId)
.eq(TaskChunkEntity::getModuleType, moduleType)
.eq(TaskChunkEntity::getScopeHash, scopeHash)
.eq(TaskChunkEntity::getChunkIndex, chunkIndex)
.last("limit 1"));
if (existing != null) {
return new PreparedSubmittedChunk(task, scopeKey, scopeHash, chunkIndex, chunkTotal, done,
request.getError(), null, null, null);
}
List<AppearancePatentResultRowDto> rawRows = rowFlattener.flatten(request);
String payloadJson = jsonWriter.write(rawRows, "结果序列化失败");
String storedPayload = chunkPayloadWriter.store(taskId, scopeHash, chunkIndex, payloadJson);
return new PreparedSubmittedChunk(task, scopeKey, scopeHash, chunkIndex, chunkTotal, done,
request.getError(), payloadJson, storedPayload, DigestUtil.sha256Hex(payloadJson));
}
public SubmitContext persistSubmittedChunk(PreparedSubmittedChunk prepared) {
Long taskId = prepared.task().getId();
FileTaskEntity task = fileTaskMapper.selectById(taskId);
if (task == null || !moduleType.equals(task.getModuleType())) {
throw new BusinessException("任务不存在");
}
if (!STATUS_RUNNING.equals(task.getStatus())) {
TaskResultAdmission.rejectNotRunning(task.getStatus());
}
ownershipChecker.check(task, "submit result");
taskCacheService.touchTaskHeartbeat(taskId);
TaskChunkEntity existing = taskChunkMapper.selectOne(new LambdaQueryWrapper<TaskChunkEntity>()
.eq(TaskChunkEntity::getTaskId, taskId)
.eq(TaskChunkEntity::getModuleType, moduleType)
.eq(TaskChunkEntity::getScopeHash, prepared.scopeHash())
.eq(TaskChunkEntity::getChunkIndex, prepared.chunkIndex())
.last("limit 1"));
if (existing == null && prepared.storedPayload() != null) {
TaskChunkEntity chunk = new TaskChunkEntity();
chunk.setTaskId(taskId);
chunk.setModuleType(moduleType);
chunk.setScopeKey(prepared.scopeKey());
chunk.setScopeHash(prepared.scopeHash());
chunk.setChunkIndex(prepared.chunkIndex());
chunk.setChunkTotal(prepared.chunkTotal());
chunk.setPayloadJson(prepared.storedPayload());
chunk.setPayloadHash(prepared.payloadHash());
chunk.setCreatedAt(LocalDateTime.now());
chunk.setUpdatedAt(LocalDateTime.now());
try {
taskChunkMapper.insert(chunk);
} catch (DuplicateKeyException ex) {
log.info("[appearance-patent] duplicate chunk inserted concurrently taskId={} scope={} chunk={}",
taskId, prepared.scopeKey(), prepared.chunkIndex());
}
} else if (existing != null) {
log.info("[appearance-patent] duplicate chunk ignored taskId={} scope={} chunk={}",
taskId, prepared.scopeKey(), prepared.chunkIndex());
}
upsertScopeState(taskId, prepared.scopeKey(), prepared.scopeHash(), prepared.chunkTotal(),
prepared.error(), prepared.done(), false);
task.setUpdatedAt(LocalDateTime.now());
fileTaskMapper.updateById(task);
return new SubmitContext(task, prepared.scopeKey(), prepared.scopeHash(), prepared.chunkIndex(),
prepared.done(), prepared.error());
}
public void completeSubmittedChunk(SubmitContext context) {
FileTaskEntity task = fileTaskMapper.selectById(context.task().getId());
if (task == null || !moduleType.equals(task.getModuleType())) {
throw new BusinessException("任务不存在");
}
if (!STATUS_RUNNING.equals(task.getStatus())) {
log.info("[appearance-patent] skip completion because task already finalized taskId={} status={}",
task.getId(), task.getStatus());
return;
}
upsertScopeState(task.getId(), context.scopeKey(), context.scopeHash(), null, context.error(), context.forceFlush(), false);
if (context.forceFlush() || context.error() != null && !context.error().isBlank()) {
finalizer.finalizeTask(task, context.error(), rowCounter.count(task), true);
return;
}
task.setUpdatedAt(LocalDateTime.now());
fileTaskMapper.updateById(task);
}
public int markSubmissionCompleteOnPythonTimeout(Long taskId) {
if (taskId == null || taskId <= 0) {
return 0;
}
List<TaskScopeStateEntity> inputStates = taskScopeStateMapper.selectList(new LambdaQueryWrapper<TaskScopeStateEntity>()
.eq(TaskScopeStateEntity::getTaskId, taskId)
.eq(TaskScopeStateEntity::getModuleType, moduleType)
.isNull(TaskScopeStateEntity::getLlmStatus)
.orderByDesc(TaskScopeStateEntity::getUpdatedAt));
if (inputStates == null || inputStates.isEmpty()) {
TaskChunkEntity latestChunk = taskChunkMapper.selectOne(new LambdaQueryWrapper<TaskChunkEntity>()
.eq(TaskChunkEntity::getTaskId, taskId)
.eq(TaskChunkEntity::getModuleType, moduleType)
.orderByDesc(TaskChunkEntity::getUpdatedAt)
.last("limit 1"));
if (latestChunk == null || latestChunk.getScopeHash() == null || latestChunk.getScopeHash().isBlank()) {
log.warn("[appearance-patent] stale recovery found no latest chunk to complete taskId={}", taskId);
return 0;
}
log.info("[appearance-patent] stale recovery recreating input scope from chunk taskId={} scopeKey={} scopeHash={} chunkTotal={}",
taskId, latestChunk.getScopeKey(), latestChunk.getScopeHash(), latestChunk.getChunkTotal());
upsertScopeState(taskId,
firstNonBlank.pick(latestChunk.getScopeKey(), "task:" + taskId),
latestChunk.getScopeHash(),
latestChunk.getChunkTotal(),
null,
true,
false);
return 1;
}
LocalDateTime now = LocalDateTime.now();
int updated = 0;
for (TaskScopeStateEntity state : inputStates) {
if (state == null || state.getId() == null) {
continue;
}
state.setCompleted(1);
if (state.getLastChunkAt() == null) {
state.setLastChunkAt(now);
}
state.setUpdatedAt(now);
state.setStateJson("{\"phase\":\"RECEIVED\",\"llm\":\"PENDING\"}");
taskScopeStateMapper.updateById(state);
updated++;
}
return updated;
}
private void upsertScopeState(Long taskId,
String scopeKey,
String scopeHash,
Integer chunkTotal,
String error,
boolean completed,
boolean llmDone) {
TaskScopeStateEntity scope = taskScopeStateMapper.selectOne(new LambdaQueryWrapper<TaskScopeStateEntity>()
.eq(TaskScopeStateEntity::getTaskId, taskId)
.eq(TaskScopeStateEntity::getModuleType, moduleType)
.eq(TaskScopeStateEntity::getScopeHash, scopeHash)
.last("limit 1"));
LocalDateTime now = LocalDateTime.now();
if (scope == null) {
scope = new TaskScopeStateEntity();
scope.setTaskId(taskId);
scope.setModuleType(moduleType);
scope.setScopeKey(scopeKey);
scope.setScopeHash(scopeHash);
scope.setCreatedAt(now);
}
if (chunkTotal != null) {
scope.setChunkTotal(chunkTotal);
}
scope.setReceivedChunkCount(countChunks(taskId, scopeHash));
scope.setLastChunkAt(now);
scope.setLastError(error);
scope.setCompleted(completed ? 1 : 0);
scope.setUpdatedAt(now);
scope.setStateJson(llmDone
? "{\"phase\":\"RECEIVED\",\"llm\":\"DONE\"}"
: "{\"phase\":\"RECEIVED\",\"llm\":\"PENDING\"}");
if (scope.getId() == null) {
try {
taskScopeStateMapper.insert(scope);
log.info("[appearance-patent] scope state inserted taskId={} scope={} scopeHash={} completed={} llmDone={}",
taskId, scopeKey, scopeHash, completed, llmDone);
return;
} catch (DuplicateKeyException ex) {
log.info("[appearance-patent] duplicate scope state inserted concurrently taskId={} scope={}", taskId, scopeKey);
scope = taskScopeStateMapper.selectOne(new LambdaQueryWrapper<TaskScopeStateEntity>()
.eq(TaskScopeStateEntity::getTaskId, taskId)
.eq(TaskScopeStateEntity::getModuleType, moduleType)
.eq(TaskScopeStateEntity::getScopeHash, scopeHash)
.last("limit 1"));
if (scope == null) {
log.info("[appearance-patent] scope state winner not committed yet, skip duplicate updater taskId={} scope={}",
taskId, scopeKey);
return;
}
if (chunkTotal != null) {
scope.setChunkTotal(chunkTotal);
}
scope.setReceivedChunkCount(countChunks(taskId, scopeHash));
scope.setLastChunkAt(now);
scope.setLastError(error);
scope.setCompleted(completed ? 1 : 0);
scope.setUpdatedAt(now);
scope.setStateJson(llmDone
? "{\"phase\":\"RECEIVED\",\"llm\":\"DONE\"}"
: "{\"phase\":\"RECEIVED\",\"llm\":\"PENDING\"}");
}
}
taskScopeStateMapper.updateById(scope);
log.info("[appearance-patent] scope state updated taskId={} scope={} scopeHash={} completed={} llmDone={}",
taskId, scopeKey, scopeHash, completed, llmDone);
}
public int countChunks(Long taskId, String scopeHash) {
Long count = taskChunkMapper.selectCount(new LambdaQueryWrapper<TaskChunkEntity>()
.eq(TaskChunkEntity::getTaskId, taskId)
.eq(TaskChunkEntity::getModuleType, moduleType)
.eq(TaskChunkEntity::getScopeHash, scopeHash));
return count == null ? 0 : count.intValue();
}
}
@@ -0,0 +1,297 @@
package com.nanri.aiimage.modules.appearancepatent.service.support;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.task.TaskStatuses;
import com.nanri.aiimage.config.AppearancePatentProperties;
import com.nanri.aiimage.modules.appearancepatent.model.dto.AppearancePatentParsedPayloadDto;
import com.nanri.aiimage.modules.appearancepatent.model.dto.AppearancePatentResultRowDto;
import com.nanri.aiimage.modules.appearancepatent.model.vo.AppearancePatentParsedRowVo;
import com.nanri.aiimage.modules.appearancepatent.service.AppearancePatentTaskCacheService;
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
import com.nanri.aiimage.modules.task.model.entity.FileResultEntity;
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import com.nanri.aiimage.modules.task.model.entity.TaskFileJobEntity;
import com.nanri.aiimage.modules.task.service.TaskFileJobService;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* 外观专利的交付闸门与补检(E 聚类之一),从 {@code AppearancePatentTaskService} <b>原样搬移</b>
* (3A 拆薄第十笔):覆盖率判定、交付行账、缺口写消息、两条补检预算(回传链路与失败兜底出口)。
*
* <p>无状态、按调用现取(与 {@code historyAssembler()} 同一先例),不新增 Spring bean。
* 行读取、载荷读取、分片切分与首非空归一由宿主以回调交出,本件不直接持有那些件。
*/
@Slf4j
public class AppearancePatentDeliverySupport {
private static final String STATUS_FAILED = TaskStatuses.FileTask.FAILED;
private final String moduleType;
private final AppearancePatentProperties properties;
private final AppearancePatentTaskCacheService taskCacheService;
private final TaskFileJobService taskFileJobService;
private final FileTaskMapper fileTaskMapper;
private final PayloadReader payloadReader;
private final RowSplitter rowSplitter;
private final ResultRowLoader resultRowLoader;
private final ResultRowFinder resultRowFinder;
private final FirstNonBlank firstNonBlank;
private final Normalizer normalizer;
public interface PayloadReader {
AppearancePatentParsedPayloadDto read(FileTaskEntity task);
}
public interface RowSplitter {
List<AppearancePatentResultPackager.SourceRows> split(AppearancePatentParsedPayloadDto parsed,
List<AppearancePatentParsedRowVo> rows,
String fallbackFilename);
}
public interface ResultRowLoader {
Map<String, AppearancePatentResultRowDto> load(Long taskId, List<AppearancePatentParsedRowVo> rows);
}
public interface ResultRowFinder {
AppearancePatentResultRowDto find(AppearancePatentParsedRowVo row,
Map<String, AppearancePatentResultRowDto> resultMap);
}
public interface FirstNonBlank {
String pick(String preferred, String fallback);
}
public interface Normalizer {
String normalize(String value);
}
public AppearancePatentDeliverySupport(String moduleType,
AppearancePatentProperties properties,
AppearancePatentTaskCacheService taskCacheService,
TaskFileJobService taskFileJobService,
FileTaskMapper fileTaskMapper,
PayloadReader payloadReader,
RowSplitter rowSplitter,
ResultRowLoader resultRowLoader,
ResultRowFinder resultRowFinder,
FirstNonBlank firstNonBlank,
Normalizer normalizer) {
this.moduleType = moduleType;
this.properties = properties;
this.taskCacheService = taskCacheService;
this.taskFileJobService = taskFileJobService;
this.fileTaskMapper = fileTaskMapper;
this.payloadReader = payloadReader;
this.rowSplitter = rowSplitter;
this.resultRowLoader = resultRowLoader;
this.resultRowFinder = resultRowFinder;
this.firstNonBlank = firstNonBlank;
this.normalizer = normalizer;
}
/**
* 有行没跑完就先别把半张表当成品发:撤销这些行的检测标记(完成态与处理中都要撤,
* 否则 {@code beginRowInspection} 下一轮仍然申领不到它们),把作业排回队列补检一轮。
*
* <p>排不上队时**不许**退化成"按已有结果交付"。现网(2026-10-19)四例
* {@code 交付缺口补检排不上队,按已有结果交付} 的 missingRows 是 112/455/1471/2110,
* 作业全部 {@code retry_count=5}——把预算抛满的恰恰是"还没检完"(覆盖率抛、空结果抛),
* 于是 {@code requeue} 那条 {@code retry_count < MAX} 的闸自我锁死:越慢越补不上。
* 这里改吃抛:让作业走到终态失败,由 {@code fallbackAssembleResultFile} 按**补检自己的**
* 预算({@code recheckMaxRounds})决定重排还是放行,两条预算不再互相占用。
*
* <p>行级重发次数仍受 {@code llmRowMaxRounds} 约束(到顶的行会被判死并写上
* 「重发轮次已达上限」的结论,从此不再是空行),所以这条不会无限循环。
*/
public boolean requestRecheckForMissingRows(FileTaskEntity task, TaskFileJobEntity job,
AppearancePatentRowOutcome.Facts facts) {
if (task == null || job == null || job.getId() == null || facts == null
|| facts.missingRows() <= 0 || facts.missingKeys().isEmpty()) {
return false;
}
List<String> keys = facts.missingKeys();
// 只有这条出口允许连完成标记一起撤:结果落过库却又读不回来的行,不撤就永远补不回来。
// 代价(该行可能被重发一次 LLM、多扣一次次数)是这一档修法里用户点名要付的。
taskCacheService.releaseRowInspection(task.getId(), keys, true);
boolean requeued = taskFileJobService.requeue(job.getId(),
"有 " + facts.missingRows() + " 行未完成检测,补检一轮后重新组装结果文件");
if (requeued) {
log.warn("[appearance-patent] 交付缺口触发补检轮 taskId={} jobId={} missingRows={} keys={} noDataRows={}",
task.getId(), job.getId(), facts.missingRows(), keys.size(), facts.noDataRows());
return true;
}
log.warn("[appearance-patent] 交付缺口补检排不上队,转失败兜底出口按补检预算处置 taskId={} jobId={} missingRows={}",
task.getId(), job.getId(), facts.missingRows());
throw new BusinessException("有 " + facts.missingRows() + " 行未完成检测,等待补检轮");
}
/**
* 只量行账、不出表。补检的决定必须做在 {@code assembleResultWorkbook} 之前,而那一跑完就把
* 成品传上 OSS 并挂好了 {@code resultFileUrl}。判据与出表共用
* {@link AppearancePatentRowOutcome#summarize},两边不许各判一套。
*/
public AppearancePatentRowOutcome.Facts measureDeliveryFacts(FileTaskEntity task, FileResultEntity result) {
AppearancePatentParsedPayloadDto parsed = payloadReader.read(task);
List<AppearancePatentParsedRowVo> parsedRows = parsed.getAllItems() == null
? List.of() : parsed.getAllItems();
AppearancePatentRowOutcome.Facts facts = AppearancePatentRowOutcome.Facts.EMPTY;
for (AppearancePatentResultPackager.SourceRows item
: rowSplitter.split(parsed, parsedRows, result.getSourceFilename())) {
Map<String, AppearancePatentResultRowDto> resultMap =
resultRowLoader.load(task.getId(), item.rows());
facts = facts.plus(AppearancePatentRowOutcome.summarize(
item.rows(), row -> resultRowFinder.find(row, resultMap)));
}
return facts;
}
/**
* 失败兜底出口上的第二条补检预算。
*
* <p>{@code fallbackAssembleResultFile} 的注释原来断言「作业已判死,缺口不再有补齐窗口」,
* 现网读数证明它是假的:底座早就有 {@code resetTerminalFailedForRecovery}(终态失败且 retry
* 到顶 ⇒ retryCount 清零、重回 PENDING、重派发),补传恢复那条路一直在用它,只有交付缺口
* 这条路没接上。轮次上限走 Redis 的 {@code recheckMaxRounds},与作业重试预算彻底分开——
* 「因为慢而抛满重试」不再等于「永远补不了」。
*
* <p>预算耗尽、或重排没接上时仍按已有结果出表:「起码失败了也可以下载」那条保证不变。
*/
public boolean scheduleFallbackRecheck(FileTaskEntity task, FileResultEntity result,
AppearancePatentRowOutcome.Facts facts) {
int maxRounds = properties.getRecheckMaxRounds();
if (task == null || task.getId() == null || result == null || result.getId() == null
|| facts == null || maxRounds <= 0) {
return false;
}
long done = taskCacheService.recheckRounds(task.getId());
if (done >= maxRounds) {
log.warn("[appearance-patent] 补检预算已耗尽,按已有结果交付 taskId={} rounds={}/{}",
task.getId(), done, maxRounds);
return false;
}
if (facts.missingRows() <= 0 || facts.missingKeys().isEmpty()) {
return false;
}
taskCacheService.releaseRowInspection(task.getId(), facts.missingKeys(), true);
TaskFileJobEntity reset = taskFileJobService.resetTerminalFailedForRecovery(
task.getId(), moduleType, result.getId());
if (reset == null || !"PENDING".equals(reset.getStatus())) {
log.warn("[appearance-patent] 失败兜底出口补检重排未接上,按已有结果交付 taskId={} resultId={} jobStatus={}",
task.getId(), result.getId(), reset == null ? "ABSENT" : reset.getStatus());
return false;
}
// 轮次只在重排真的接上之后才记:否则"没接上"也要扣一轮,预算会被失败的重排自己吃光
taskCacheService.countRecheckRound(task.getId());
log.warn("[appearance-patent] 失败兜底出口触发补检轮 taskId={} jobId={} round={}/{} missingRows={} keys={}",
task.getId(), reset.getId(), done + 1, maxRounds, facts.missingRows(), facts.missingKeys().size());
return true;
}
/**
* 覆盖率判定:分母必须是**真正会写进结果文件的那批行**,且"该行有没有数据"要同时看
* 用户上传表的解析行与客户端回传的结果行——只看解析行,用户表不带标题列时分母恒为 0,
* 闸门对整份文件失明(现网 6 份已交付文件里 20%–51% 空行、零告警就是这么来的)。
* 判据本身在 {@link AppearancePatentRowOutcome#summarize},与表格文案共用一套,不许两边各判。
*/
public AppearancePatentRowOutcome.Facts validateCompleteLlmCoverage(Long taskId,
List<AppearancePatentParsedRowVo> parsedRows,
Map<String, AppearancePatentResultRowDto> resultMap) {
return validateCompleteLlmCoverage(taskId, parsedRows, resultMap, false);
}
public AppearancePatentRowOutcome.Facts validateCompleteLlmCoverage(Long taskId,
List<AppearancePatentParsedRowVo> parsedRows,
Map<String, AppearancePatentResultRowDto> resultMap,
boolean allowPartial) {
if (parsedRows == null || parsedRows.isEmpty()) {
return AppearancePatentRowOutcome.Facts.EMPTY;
}
AppearancePatentRowOutcome.Facts facts =
AppearancePatentRowOutcome.summarize(parsedRows, row -> resultRowFinder.find(row, resultMap));
FileTaskEntity task = fileTaskMapper.selectById(taskId);
boolean taskAlreadyFailed = task != null && STATUS_FAILED.equals(task.getStatus());
if (facts.missingRows() > 0 || facts.noDataRows() > 0) {
log.warn("[appearance-patent] 交付行账不完整 taskId={} expectedRows={} judgedRows={} missingRows={} noDataRows={} coverage={} taskFailed={} samples={}",
taskId, facts.expectedRows(), facts.judgedRows(), facts.missingRows(), facts.noDataRows(),
String.format("%.2f%%", facts.coverage() * 100), taskAlreadyFailed,
sampleAsins(parsedRows, resultMap, facts));
}
double minCoverage = properties.getLlmCoverageMinRatio();
// 已判失败的任务走的是"按已有分片出部分结果"这条既有口径,这里再抛会把成品彻底拿掉;
// 失败兜底路径(allowPartial=true,作业已判死)同理放行。
// 两者都不再静默:上面的行账锚点必打,缺口由调用方写进任务错误信息,用户看得到「N 行没检测」。
if (!taskAlreadyFailed && !allowPartial && minCoverage > 0 && facts.expectedRows() > 0
&& facts.coverage() + 1e-9 < minCoverage) {
throw new BusinessException("LLM 结果不完整:仅 " + facts.judgedRows() + "/" + facts.expectedRows()
+ " 行拿到检测结论(低于 " + Math.round(minCoverage * 100) + "% 覆盖率下限)"
+ noDataSuffix(facts) + ",请重新运行任务");
}
return facts;
}
private List<String> sampleAsins(List<AppearancePatentParsedRowVo> parsedRows,
Map<String, AppearancePatentResultRowDto> resultMap,
AppearancePatentRowOutcome.Facts facts) {
List<String> samples = new ArrayList<>(5);
if (facts.missingRows() <= 0) {
return samples;
}
for (AppearancePatentParsedRowVo parsedRow : parsedRows) {
if (samples.size() >= 5) {
break;
}
if (parsedRow == null) {
continue;
}
if (AppearancePatentRowOutcome.classify(parsedRow, resultRowFinder.find(parsedRow, resultMap))
!= AppearancePatentRowOutcome.Kind.NOT_INSPECTED) {
continue;
}
samples.add(firstNonBlank.pick(parsedRow.getAsin(),
firstNonBlank.pick(parsedRow.getDisplayId(), "")));
}
return samples;
}
private String noDataSuffix(AppearancePatentRowOutcome.Facts facts) {
return facts.noDataRows() > 0
? ";另有 " + facts.noDataRows() + " 行未采集到数据、无法检测"
: "";
}
/** 交付缺口写进任务错误信息:让后台列表与用户端都能看到「N 行没检测完」,而不是只有一张半空表。 */
public String appendDeliveryGapMessage(String existingError, AppearancePatentRowOutcome.Facts facts) {
if (facts == null || (facts.missingRows() <= 0 && facts.noDataRows() <= 0)) {
return existingError;
}
StringBuilder gap = new StringBuilder();
if (facts.missingRows() > 0) {
gap.append("有 ").append(facts.missingRows()).append(" 行未完成检测");
}
if (facts.noDataRows() > 0) {
if (gap.length() > 0) {
gap.append("、");
}
gap.append("有 ").append(facts.noDataRows()).append(" 行未采集到数据");
}
gap.append("(结果文件中这些行已单独标注)");
String existing = firstNonBlank.pick(existingError, "");
if (existing.contains("未完成检测") || existing.contains("未采集到数据")) {
return existing;
}
return existing.isBlank() ? gap.toString() : existing + ";" + gap;
}
public boolean hasReasonFields(AppearancePatentResultRowDto row) {
if (row == null) {
return false;
}
return !normalizer.normalize(row.getAppearanceReason()).isBlank()
|| !normalizer.normalize(row.getPatentReason()).isBlank()
|| !normalizer.normalize(row.getTitleReason()).isBlank();
}
}
@@ -0,0 +1,498 @@
package com.nanri.aiimage.modules.appearancepatent.service.support;
import com.nanri.aiimage.config.AppearancePatentProperties;
import com.nanri.aiimage.modules.appearancepatent.client.AppearancePatentLlmClient;
import com.nanri.aiimage.modules.appearancepatent.model.dto.AppearancePatentResultRowDto;
import com.nanri.aiimage.modules.appearancepatent.service.AppearancePatentTaskCacheService;
import com.nanri.aiimage.modules.task.model.entity.FileResultEntity;
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import com.nanri.aiimage.modules.task.model.entity.TaskChunkEntity;
import com.nanri.aiimage.modules.task.model.entity.TaskFileJobEntity;
import com.nanri.aiimage.modules.task.service.TaskFileJobService;
import com.nanri.aiimage.modules.usersecret.support.SecretUsageContext;
import com.nanri.aiimage.modules.usersecret.support.UserSecretModule;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
/**
* 外观专利的 LLM 批管线(B 聚类),从 {@code AppearancePatentTaskService} <b>原样搬移</b>
* (3A 拆薄第五笔):候选收集、批调度、轮次到顶判死、结果行合并回分片、批工作单元计数,
* 连同它们的日志文案与判序一个字没改。
*
* <p><b>搬的是批管线,不是它的宿主能力。</b>读分片载荷({@code readChunkRows})、分片合并
* ({@code mergeChunkPayload})、任务心跳({@code touchJavaSideTaskActivity})、提交是否封口
* ({@code isResultSubmissionComplete})都还留在服务侧,以回调交进来——它们分属 D/G/H 聚类,
* 跟着 B 一起拖出来就得先给它们再造一套构造器,而 3A 的账已经证明
* 「结构性成本 &gt; 可沉件收益」是要避免的事。回调是这一笔里唯一的新形状。
*
* <p><b>作用域必须是单次调用。</b>本类是单例服务里的临时协作者(每次入口新建),
* {@link ChunkRowKeyIndex} 随栈丢弃;做成服务字段就是多任务共享一个裸 LinkedHashMap,
* 而且分片键永不过期、只增不减(原注释里那条约束一并带过来)。
*
* <p>搬移后唯一的可观测差异是 logger 名:从
* {@code ...service.AppearancePatentTaskService} 变为
* {@code ...service.support.AppearancePatentLlmBatchPipeline},消息文本、级别与参数顺序未动。
*/
@Slf4j
public class AppearancePatentLlmBatchPipeline {
/** 分片载荷合并(D 聚类)留在服务侧;返回真正写进这一片载荷的行键。 */
@FunctionalInterface
public interface ChunkRowMerger {
List<String> merge(Long taskId, String scopeHash, Integer chunkIndex,
List<AppearancePatentResultRowDto> rows);
}
private final AppearancePatentProperties properties;
private final AppearancePatentLlmClient llmClient;
private final AppearancePatentTaskCacheService taskCacheService;
private final TaskFileJobService taskFileJobService;
private final Function<AppearancePatentResultRowDto, String> rowKeyer;
private final Predicate<AppearancePatentResultRowDto> shouldInspect;
private final Function<TaskChunkEntity, Map<String, AppearancePatentResultRowDto>> chunkRowReader;
private final Function<Long, List<TaskChunkEntity>> submittedChunksLoader;
private final Predicate<Long> submissionComplete;
private final Consumer<Long> taskActivityToucher;
private final Function<FileTaskEntity, String> promptReader;
private final Function<FileTaskEntity, String> apiKeyReader;
private final ChunkRowMerger chunkRowMerger;
private final BiFunction<String, String, String> firstNonBlankFn;
public AppearancePatentLlmBatchPipeline(AppearancePatentProperties properties,
AppearancePatentLlmClient llmClient,
AppearancePatentTaskCacheService taskCacheService,
TaskFileJobService taskFileJobService,
Function<AppearancePatentResultRowDto, String> rowKeyer,
Predicate<AppearancePatentResultRowDto> shouldInspect,
Function<TaskChunkEntity, Map<String, AppearancePatentResultRowDto>> chunkRowReader,
Function<Long, List<TaskChunkEntity>> submittedChunksLoader,
Predicate<Long> submissionComplete,
Consumer<Long> taskActivityToucher,
Function<FileTaskEntity, String> promptReader,
Function<FileTaskEntity, String> apiKeyReader,
ChunkRowMerger chunkRowMerger,
BiFunction<String, String, String> firstNonBlankFn) {
this.properties = properties;
this.llmClient = llmClient;
this.taskCacheService = taskCacheService;
this.taskFileJobService = taskFileJobService;
this.rowKeyer = rowKeyer;
this.shouldInspect = shouldInspect;
this.chunkRowReader = chunkRowReader;
this.submittedChunksLoader = submittedChunksLoader;
this.submissionComplete = submissionComplete;
this.taskActivityToucher = taskActivityToucher;
this.promptReader = promptReader;
this.apiKeyReader = apiKeyReader;
this.chunkRowMerger = chunkRowMerger;
this.firstNonBlankFn = firstNonBlankFn;
}
/**
* 同步检测:按批次串行调用 LLM(批内行级并发由 client 负责),
* 结果直接合并回 chunk。批间去重用 Redis 行级标记防止 submitResult 与 stale 恢复双入口重复检测。
*/
public void submitLlmBatches(FileTaskEntity task,
FileResultEntity result,
TaskFileJobEntity job,
List<TaskChunkEntity> chunks) {
if (chunks == null || chunks.isEmpty()) {
return;
}
String prompt = promptReader.apply(task);
String apiKey = apiKeyReader.apply(task);
int batchSize = Math.max(1, properties.getLlmBatchSize());
ChunkRowKeyIndex rowKeyIndex = new ChunkRowKeyIndex();
List<AppearancePatentResultRowDto> candidates = terminalizeRoundExhaustedRows(
task, collectPendingLlmCandidates(chunks, rowKeyIndex), rowKeyIndex);
boolean flushRemainder = isResultSubmissionComplete(task.getId());
if (!flushRemainder && !candidates.isEmpty()) {
LocalDateTime jobUpdatedAt = job.getUpdatedAt();
long pendingFlushMillis = flushPendingMillis();
if (jobUpdatedAt != null
&& Duration.between(jobUpdatedAt, LocalDateTime.now()).toMillis() >= pendingFlushMillis) {
flushRemainder = true;
log.warn("[appearance-patent] 零头批次等待超时,强制提交 taskId={} jobId={} pendingRows={} batchSize={} jobUpdatedAt={} flushAfterMillis={}",
task.getId(), job.getId(), candidates.size(), batchSize, jobUpdatedAt, pendingFlushMillis);
}
}
int submitLimit = (candidates.size() / batchSize) * batchSize;
if (flushRemainder && submitLimit < candidates.size()) {
submitLimit = candidates.size();
}
if (submitLimit <= 0) {
log.info("[appearance-patent] llm batch waiting for more rows taskId={} jobId={} pendingRows={} batchSize={} finalUpload={}",
task.getId(), job.getId(), candidates.size(), batchSize, flushRemainder);
return;
}
if (TransactionSynchronizationManager.isActualTransactionActive()) {
// 守住"整批 LLM 跑在事务里"这一类回归:下面循环每批开头的 touchRunning 是
// UPDATE biz_task_file_job ... WHERE id=? AND status='RUNNING',本方法一旦处在事务中,
// 这把行锁就要持到全部批次结束才释放(线上实测一批 18 分钟),另一台的卡死自愈扫描
// 于是每 110 秒撞一次 50 秒锁等待、并且整轮作废。历史上真发生过,见
// docs/ops/prod-decisions-2026-09-28.md §9。
log.error("[appearance-patent] llm 批次正跑在事务里,行锁会持到批次结束 taskId={} jobId={} pendingRows={}",
task.getId(), job.getId(), submitLimit);
}
int batchTotal = Math.max(1, (submitLimit + batchSize - 1) / batchSize);
int batchIndex = 1;
for (int i = 0; i < submitLimit; i += batchSize) {
List<AppearancePatentResultRowDto> batchRows = candidates.subList(i, Math.min(i + batchSize, submitLimit));
taskFileJobService.touchRunning(job.getId());
List<String> batchRowKeys = batchRows.stream().map(this::rowKey).filter(key -> !key.isBlank()).toList();
taskCacheService.touchRowInspection(task.getId(), batchRowKeys);
taskCacheService.countRowInspectionRound(task.getId(), batchRowKeys);
long startedAt = System.currentTimeMillis();
List<AppearancePatentResultRowDto> llmRows;
boolean batchAnswered = true;
try {
llmRows = SecretUsageContext.call(task.getUserId(), UserSecretModule.APPEARANCE_PATENT.key(),
() -> llmClient.inspectRows(batchRows, prompt, apiKey));
} catch (Exception ex) {
String message = firstNonBlank(ex.getMessage(), "LLM 检测失败");
log.warn("[appearance-patent] llm batch failed taskId={} jobId={} rows={} batch={}/{} err={}",
task.getId(), job.getId(), batchRows.size(), batchIndex, batchTotal, message);
llmRows = llmClient.markRowsFailed(batchRows, message);
batchAnswered = false;
}
List<String> keysToRetry = new ArrayList<>(batchRowKeys);
try {
Set<String> landedKeys = mergeLlmRowsIntoChunks(task, llmRows, batchRows, rowKeyIndex);
// 完成标记只能打在真正落库的行上——这是「发版重启会不会丢行」的分界线
if (batchAnswered) {
List<String> landed = batchRowKeys.stream().filter(landedKeys::contains).toList();
if (!landed.isEmpty()) {
taskCacheService.completeRowInspection(task.getId(), landed);
}
keysToRetry.removeAll(landed);
}
} finally {
// 本批结束时处理中名额必须让出来:没落库的行撤销后下一轮马上能重新申领,不等 TTL
if (!keysToRetry.isEmpty()) {
taskCacheService.releaseRowInspection(task.getId(), keysToRetry);
if (batchAnswered) {
// 结果拿到了却落不进分片(少回、rowToken 被改写、分片已清):
// 打成已完成就是"扣了次数永久没结论",宁可重发一轮。
log.warn("[appearance-patent] 本批结果未全部落库,撤销已检测标记交由下一轮重发 taskId={} jobId={} batch={}/{} sent={} retrying={}",
task.getId(), job.getId(), batchIndex, batchTotal, batchRowKeys.size(), keysToRetry);
}
}
}
log.info("[appearance-patent] llm batch done taskId={} jobId={} rows={} batch={}/{} costMs={}",
task.getId(), job.getId(), batchRows.size(), batchIndex, batchTotal,
System.currentTimeMillis() - startedAt);
// 每批刷新任务心跳:软恢复后的检测阶段可达数小时,不刷会被通用兜底线按 updated_at 超 120 分钟误杀(2026-09-28 29473/29479)
taskActivityToucher.accept(task.getId());
batchIndex++;
}
}
/**
* 轮次已到顶的行就地判失败并打成「已完成」,从此退出候选。
*
* <p>失败行会被撤销处理中标记、下一轮重新申领——这是「不丢行」的另一半代价。没有这道闸的话,
* 上游劣化窗口内同一批行会一轮轮重发,每轮都过 {@link SecretUsageContext} 扣用户的 LLM 次数,
* 而 assemble job 走的是 deferRunning(不累加 retryCount),MAX_RETRY_COUNT 那条永不触发。
*/
private List<AppearancePatentResultRowDto> terminalizeRoundExhaustedRows(
FileTaskEntity task,
List<AppearancePatentResultRowDto> candidates,
ChunkRowKeyIndex rowKeyIndex) {
int maxRounds = properties.getLlmRowMaxRounds();
if (maxRounds <= 0 || candidates == null || candidates.isEmpty()) {
return candidates == null ? List.of() : candidates;
}
List<AppearancePatentResultRowDto> retryable = new ArrayList<>(candidates.size());
List<AppearancePatentResultRowDto> exhausted = new ArrayList<>();
for (AppearancePatentResultRowDto row : candidates) {
String key = rowKey(row);
if (!key.isBlank() && taskCacheService.rowInspectionRounds(task.getId(), key) >= maxRounds) {
exhausted.add(row);
} else {
retryable.add(row);
}
}
if (exhausted.isEmpty()) {
return retryable;
}
String reason = "重发轮次已达上限 " + maxRounds + " 轮仍未取到结论,请稍后重新发起检测";
log.warn("[appearance-patent] llm round cap reached taskId={} rows={} maxRounds={}",
task.getId(), exhausted.size(), maxRounds);
List<String> exhaustedKeys = exhausted.stream().map(this::rowKey).filter(key -> !key.isBlank()).toList();
boolean rowsTerminated = false;
try {
mergeLlmRowsIntoChunks(task, llmClient.markRowsFailed(exhausted, reason),
exhausted, rowKeyIndex);
rowsTerminated = true;
} finally {
// 失败原因没落库就不能打成「已完成」,否则这批行既没结论也再不会重试
if (rowsTerminated) {
taskCacheService.completeRowInspection(task.getId(), exhaustedKeys);
} else {
taskCacheService.releaseRowInspection(task.getId(), exhaustedKeys);
}
}
return retryable;
}
public Set<String> mergeLlmRowsIntoChunks(FileTaskEntity task,
List<AppearancePatentResultRowDto> llmRows,
List<AppearancePatentResultRowDto> batchRows,
ChunkRowKeyIndex rowKeyIndex) {
if (llmRows == null || llmRows.isEmpty()) {
return Set.of();
}
Map<String, AppearancePatentResultRowDto> deduped = new LinkedHashMap<>();
for (int i = 0; i < llmRows.size(); i++) {
AppearancePatentResultRowDto row = llmRows.get(i);
AppearancePatentResultRowDto sourceRow = i < batchRows.size() ? batchRows.get(i) : null;
String key = rowKey(row);
if (key.isBlank()) {
if (sourceRow != null) {
key = rowKey(sourceRow);
}
}
if (key.isBlank() || !deduped.containsKey(key)) {
deduped.put(key, row);
}
}
return mergeLlmRowsIntoSubmittedChunks(task, new ArrayList<>(deduped.values()), null, null, rowKeyIndex);
}
/**
* 收集未检测的候选行:**逐行**申领——同一父号下的 {@code 2_1/2_2/2_3} 每行都各自进候选、各自送检。
*
* <p>历史上这里只挑「组代表行」,其余兄弟行指望 {@code expandRows} 在发起那一轮借用代表行的结论——
* 那是把「同一个父号」当成「同一件东西」,而子序行各有各的 sku、标题和图片链接。
* 口径(2026-10-10 用户定):这些行**都要检测**。折叠与借用一起撤掉,因为借用的后果不是省钱,
* 而是成片空行随结果文件交付(10-08 任务 30426:1211 行里只有 960 行有结论、251 行整段空白,
* 而任务报成功;10-09 任务 30455 的 281 行空行 100% 属于"同父号已有一行被判"这一形状)。
*
* <p>"这行算不算已经检过"用交付口径(标题维+外观维+结论三列齐,见
* {@link AppearancePatentRowOutcome#isJudged})。旧代码用的是"四个字段里任一可用",于是
* 只带着专利维度文本、或只带一个 error 的行会被判"已检测",从此退出候选,而表格里它那三列全是空的。
*/
public List<AppearancePatentResultRowDto> collectPendingLlmCandidates(List<TaskChunkEntity> chunks,
ChunkRowKeyIndex rowKeyIndex) {
if (chunks == null || chunks.isEmpty()) {
return List.of();
}
List<AppearancePatentResultRowDto> candidates = new ArrayList<>();
int claimBlocked = 0;
int judgedSkipped = 0;
int noDataSkipped = 0;
int chunkRows = 0;
for (TaskChunkEntity chunk : chunks) {
Map<String, AppearancePatentResultRowDto> persistedRows = readChunkRows(chunk);
if (persistedRows.isEmpty()) {
continue;
}
// 这一遍已经把这批分片的载荷读进来了,顺手把「这片里有哪些行」记进索引:
// 下面每批落库前都要这份索引,不记的话就得每批把全部分片重读重解析一遍
rememberChunkRowKeys(rowKeyIndex, chunk, persistedRows.keySet());
chunkRows += persistedRows.size();
for (AppearancePatentResultRowDto row : persistedRows.values()) {
String key = rowKey(row);
if (key.isBlank()) {
continue;
}
if (AppearancePatentRowOutcome.isJudged(row)) {
judgedSkipped++;
continue;
}
if (!shouldInspect.test(row)) {
// 连标题带图都没采到的行:送过去也只能回"外观识别异常",白扣一次
noDataSkipped++;
continue;
}
if (!taskCacheService.beginRowInspection(chunk.getTaskId(), key)) {
// 被"处理中/已完成"标记挡住的行必须数得出来:历史上这里静默 continue,
// 于是"扣了次数却永久没结论"和"这行本来就不该检"在日志里长得一模一样
claimBlocked++;
continue;
}
candidates.add(row);
}
}
log.info("[appearance-patent] 候选收集逐行申领 taskId={} chunkRows={} judgedSkipped={} noDataSkipped={} claimBlocked={} candidates={}",
chunks.get(0).getTaskId(), chunkRows, judgedSkipped, noDataSkipped, claimBlocked, candidates.size());
return candidates;
}
/**
* 只计数、不申领。用 {@link #collectPendingLlmCandidates} 计数会把行标成处理中,
* 紧接着真正发起检测的那一步就一行也申领不到,只能等处理中标记的 TTL 过期。
*/
public int countUninspectedRows(List<TaskChunkEntity> chunks) {
if (chunks == null || chunks.isEmpty()) {
return 0;
}
int total = 0;
for (TaskChunkEntity chunk : chunks) {
Map<String, AppearancePatentResultRowDto> persistedRows = readChunkRows(chunk);
for (AppearancePatentResultRowDto row : persistedRows.values()) {
if (!rowKey(row).isBlank() && !AppearancePatentRowOutcome.isJudged(row)) {
total++;
}
}
}
return total;
}
public int countLlmWorkUnits(List<TaskChunkEntity> chunks, int batchSize) {
if (chunks == null || chunks.isEmpty()) {
return 0;
}
int total = 0;
for (TaskChunkEntity chunk : chunks) {
Map<String, AppearancePatentResultRowDto> persistedRows = readChunkRows(chunk);
if (persistedRows.isEmpty()) {
continue;
}
int unresolved = (int) persistedRows.values().stream()
.filter(row -> !rowKey(row).isBlank() && !AppearancePatentRowOutcome.isJudged(row)).count();
if (unresolved > 0) {
total += Math.max(1, (unresolved + batchSize - 1) / batchSize);
}
}
return total;
}
private long flushPendingMillis() {
return Math.max(1, properties.getFlushPendingMinutes()) * 60_000L;
}
/** 返回真正落库的行键;没匹配到分片行的键不会出现在里面,调用方据此决定要不要撤销已检测标记。 */
private Set<String> mergeLlmRowsIntoSubmittedChunks(FileTaskEntity task,
List<AppearancePatentResultRowDto> llmRows,
String fallbackScopeHash,
Integer fallbackChunkIndex,
ChunkRowKeyIndex rowKeyIndex) {
if (task == null || llmRows == null || llmRows.isEmpty()) {
return Set.of();
}
List<TaskChunkEntity> chunks = loadSubmittedChunks(task.getId());
if (chunks.isEmpty()) {
return Set.of();
}
Map<String, Set<String>> rowKeysByChunk = new LinkedHashMap<>();
Map<String, TaskChunkEntity> chunkByKey = new LinkedHashMap<>();
for (TaskChunkEntity chunk : chunks) {
String chunkKey = chunkStorageKey(chunk.getScopeHash(), chunk.getChunkIndex());
rowKeysByChunk.put(chunkKey, chunkRowKeySet(rowKeyIndex, chunk));
chunkByKey.put(chunkKey, chunk);
}
Map<String, Map<String, AppearancePatentResultRowDto>> mergeRowsByChunk = new LinkedHashMap<>();
for (AppearancePatentResultRowDto resultRow : llmRows) {
for (AppearancePatentResultRowDto expandedRow : List.of(resultRow)) {
String rowKey = rowKey(expandedRow);
if (rowKey.isBlank()) {
continue;
}
boolean matched = false;
for (Map.Entry<String, Set<String>> entry : rowKeysByChunk.entrySet()) {
if (entry.getValue().contains(rowKey)) {
mergeRowsByChunk.computeIfAbsent(entry.getKey(), ignored -> new LinkedHashMap<>())
.put(rowKey, expandedRow);
matched = true;
}
}
if (!matched && fallbackScopeHash != null && fallbackChunkIndex != null) {
String fallbackKey = chunkStorageKey(fallbackScopeHash, fallbackChunkIndex);
if (chunkByKey.containsKey(fallbackKey)) {
mergeRowsByChunk.computeIfAbsent(fallbackKey, ignored -> new LinkedHashMap<>())
.put(rowKey, expandedRow);
matched = true;
}
}
if (!matched) {
log.warn("[appearance-patent] llm row has no submitted chunk taskId={} rowKey={}",
task.getId(), rowKey);
}
}
}
Set<String> landedKeys = new LinkedHashSet<>();
for (Map.Entry<String, Map<String, AppearancePatentResultRowDto>> entry : mergeRowsByChunk.entrySet()) {
TaskChunkEntity chunk = chunkByKey.get(entry.getKey());
if (chunk == null || entry.getValue().isEmpty()) {
continue;
}
landedKeys.addAll(chunkRowMerger.merge(task.getId(), chunk.getScopeHash(), chunk.getChunkIndex(),
new ArrayList<>(entry.getValue().values())));
}
return landedKeys;
}
private String chunkStorageKey(String scopeHash, Integer chunkIndex) {
return firstNonBlank(scopeHash, "") + ":" + (chunkIndex == null ? 0 : chunkIndex);
}
/**
* 一次 {@link #submitLlmBatches} 内共享的「哪个分片里有哪些行」索引,按 payload_hash 判新鲜。
*
* <p>只存 rowKey 不存整行,索引本身不会把载荷钉在内存里。作用域必须是单次调用(局部变量,随栈丢弃):
* 本服务是单例、多个任务同时在跑批,做成字段就是多线程共享一个裸 LinkedHashMap,而且分片键永不过期、只增不减。
* 数据正确性反过来不依赖局部性——收集候选那一遍每次都会重读并重记全部分片。
*/
public static final class ChunkRowKeyIndex {
private final Map<String, Snapshot> snapshots = new LinkedHashMap<>();
}
/** 把刚解析出来的分片行键记进索引(自己拷一份,不握住整行载荷),返回索引里那份。 */
private Set<String> rememberChunkRowKeys(ChunkRowKeyIndex rowKeyIndex, TaskChunkEntity chunk, Set<String> rowKeys) {
Set<String> copied = new LinkedHashSet<>(rowKeys);
rowKeyIndex.snapshots.put(chunkStorageKey(chunk.getScopeHash(), chunk.getChunkIndex()),
new Snapshot(chunk.getPayloadHash(), copied));
return copied;
}
/** 分片当前载荷里的全部行键;载荷哈希与索引里那次解析一致时直接复用,不重读对象存储。 */
private Set<String> chunkRowKeySet(ChunkRowKeyIndex rowKeyIndex, TaskChunkEntity chunk) {
Snapshot cached = rowKeyIndex.snapshots.get(chunkStorageKey(chunk.getScopeHash(), chunk.getChunkIndex()));
if (cached != null && Objects.equals(cached.payloadHash, chunk.getPayloadHash())) {
return cached.rowKeys;
}
return rememberChunkRowKeys(rowKeyIndex, chunk, readChunkRows(chunk).keySet());
}
private record Snapshot(String payloadHash, Set<String> rowKeys) {
}
private boolean isResultSubmissionComplete(Long taskId) {
return submissionComplete.test(taskId);
}
private void touchJavaSideTaskActivity(Long taskId) {
taskActivityToucher.accept(taskId);
}
private String rowKey(AppearancePatentResultRowDto row) {
return rowKeyer.apply(row);
}
private Map<String, AppearancePatentResultRowDto> readChunkRows(TaskChunkEntity chunk) {
return chunkRowReader.apply(chunk);
}
private List<TaskChunkEntity> loadSubmittedChunks(Long taskId) {
return submittedChunksLoader.apply(taskId);
}
private String firstNonBlank(String preferred, String fallback) {
return firstNonBlankFn.apply(preferred, fallback);
}
}
@@ -0,0 +1,261 @@
package com.nanri.aiimage.modules.appearancepatent.service.support;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.modules.appearancepatent.model.dto.AppearancePatentParsedPayloadDto;
import com.nanri.aiimage.modules.appearancepatent.model.dto.AppearancePatentSourceFileDto;
import com.nanri.aiimage.modules.appearancepatent.model.vo.AppearancePatentParsedGroupVo;
import com.nanri.aiimage.modules.appearancepatent.model.vo.AppearancePatentParsedRowVo;
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
import com.nanri.aiimage.modules.task.mapper.TaskChunkMapper;
import com.nanri.aiimage.modules.task.mapper.TaskScopeStateMapper;
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import com.nanri.aiimage.modules.task.model.entity.TaskChunkEntity;
import com.nanri.aiimage.modules.task.model.entity.TaskScopeStateEntity;
import com.nanri.aiimage.modules.task.service.TransientPayloadStorageService;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
/**
* 外观专利的载荷/JSON 读写(I 聚类),从 {@code AppearancePatentTaskService} <b>原样搬移</b>
* (3A 拆薄第六笔):解析载荷的组装/落库/读取、分片载荷写入、任务载荷指针收集与事务后删除,
* 连同异常文案与删除顺序一个字没改。
*
* <p><b>搬的是载荷读写,不是宿主能力。</b>字符串归一({@code normalize})、解析分组重建
* ({@code buildParsedGroups})、实例 id、归属校验与 afterCommit 调度都还留在服务侧,
* 以回调交进来——它们横跨解析/归属/事务三个面,跟着载荷一起拖出来只会把依赖面放大。
*/
@Slf4j
public class AppearancePatentPayloadSupport {
/** 序列化失败时的统一出口(服务侧 {@code writeJson} 的薄适配)。 */
@FunctionalInterface
public interface JsonWriter {
String write(Object value, String failureMessage);
}
private final String moduleType;
private final ObjectMapper objectMapper;
private final TransientPayloadStorageService transientPayloadStorageService;
private final FileTaskMapper fileTaskMapper;
private final TaskChunkMapper taskChunkMapper;
private final TaskScopeStateMapper taskScopeStateMapper;
private final Function<String, String> normalizer;
private final Function<List<AppearancePatentParsedRowVo>, List<AppearancePatentParsedGroupVo>> groupBuilder;
private final Supplier<String> currentInstanceId;
private final BiConsumer<FileTaskEntity, String> ownershipChecker;
private final Consumer<Runnable> afterCommitRunner;
private final JsonWriter jsonWriter;
public AppearancePatentPayloadSupport(String moduleType,
ObjectMapper objectMapper,
TransientPayloadStorageService transientPayloadStorageService,
FileTaskMapper fileTaskMapper,
TaskChunkMapper taskChunkMapper,
TaskScopeStateMapper taskScopeStateMapper,
Function<String, String> normalizer,
Function<List<AppearancePatentParsedRowVo>, List<AppearancePatentParsedGroupVo>> groupBuilder,
Supplier<String> currentInstanceId,
BiConsumer<FileTaskEntity, String> ownershipChecker,
Consumer<Runnable> afterCommitRunner,
JsonWriter jsonWriter) {
this.moduleType = moduleType;
this.objectMapper = objectMapper;
this.transientPayloadStorageService = transientPayloadStorageService;
this.fileTaskMapper = fileTaskMapper;
this.taskChunkMapper = taskChunkMapper;
this.taskScopeStateMapper = taskScopeStateMapper;
this.normalizer = normalizer;
this.groupBuilder = groupBuilder;
this.currentInstanceId = currentInstanceId;
this.ownershipChecker = ownershipChecker;
this.afterCommitRunner = afterCommitRunner;
this.jsonWriter = jsonWriter;
}
public String buildParsedPayloadJson(String aiPrompt, String apiKey,
List<AppearancePatentSourceFileDto> sourceFiles,
List<String> headers,
List<AppearancePatentParsedRowVo> allRows) {
AppearancePatentParsedPayloadDto payload = new AppearancePatentParsedPayloadDto();
payload.setAiPrompt(normalizer.apply(aiPrompt));
payload.setApiKey(normalizer.apply(apiKey));
payload.setSourceFiles(sourceFiles == null ? List.of() : sourceFiles);
payload.setHeaders(headers == null ? List.of() : headers);
payload.setItems(List.of());
payload.setGroups(List.of());
payload.setAllItems(allRows == null ? List.of() : allRows);
return jsonWriter.write(payload, "保存解析结果失败");
}
public String buildTaskResultJson(String aiPrompt, String apiKey,
List<AppearancePatentSourceFileDto> sourceFiles,
String parsedPayloadPointer) {
Map<String, Object> payload = new LinkedHashMap<>();
payload.put("aiPrompt", normalizer.apply(aiPrompt));
payload.put("apiKey", normalizer.apply(apiKey));
payload.put("sourceFileKeys", sourceFiles == null ? List.of() : sourceFiles.stream()
.map(AppearancePatentSourceFileDto::getFileKey)
.filter(Objects::nonNull)
.toList());
payload.put("parsedPayloadRef", parsedPayloadPointer);
payload.put("ownerInstanceId", currentInstanceId.get());
return jsonWriter.write(payload, "保存任务结果索引失败");
}
public String storeParsedPayload(Long taskId, String scopeHash, String parsedPayloadJson) {
requireSharedTransientPayloadStorage("parsed payload");
return transientPayloadStorageService.storeParsedPayloadFast(moduleType, taskId, scopeHash, parsedPayloadJson, false);
}
public String storeSharedChunkPayload(Long taskId, String scopeHash, Integer chunkIndex, String payloadJson) {
requireSharedTransientPayloadStorage("chunk payload");
return transientPayloadStorageService.storeChunkPayload(moduleType, taskId, scopeHash, chunkIndex, payloadJson);
}
public String storeSharedChunkPayloadVersioned(Long taskId, String scopeHash, Integer chunkIndex, String payloadJson) {
requireSharedTransientPayloadStorage("merged chunk payload");
return transientPayloadStorageService.storeChunkPayloadVersioned(moduleType, taskId, scopeHash, chunkIndex, payloadJson);
}
private void requireSharedTransientPayloadStorage(String payloadType) {
if (!transientPayloadStorageService.isSharedWriteEnabled()) {
throw new BusinessException("外观专利" + payloadType + "必须写入共享临时存储 RustFS,请检查 aiimage.transient-storage 配置");
}
}
public AppearancePatentParsedPayloadDto readParsedPayload(FileTaskEntity task) {
try {
JsonNode root = objectMapper.readTree(task.getResultJson());
String pointer = root.path("parsedPayloadRef").asText("");
if (!pointer.isBlank()) {
String json = transientPayloadStorageService.resolvePayload(pointer, "read appearance patent parsed payload failed");
return hydrateParsedPayloadRows(objectMapper.readValue(json, AppearancePatentParsedPayloadDto.class));
}
if (root.path("allItems").isArray()) {
return hydrateParsedPayloadRows(objectMapper.treeToValue(root, AppearancePatentParsedPayloadDto.class));
}
} catch (Exception ex) {
throw new BusinessException("读取解析载荷失败");
}
return hydrateParsedPayloadRows(new AppearancePatentParsedPayloadDto());
}
public AppearancePatentParsedPayloadDto queuePayload(Long taskId, Long userId) {
FileTaskEntity task = fileTaskMapper.selectById(taskId);
if (task == null || !moduleType.equals(task.getModuleType()) || !Objects.equals(userId, task.getUserId())) {
throw new BusinessException("任务不存在");
}
ownershipChecker.accept(task, "queue payload");
AppearancePatentParsedPayloadDto payload = readParsedPayload(task);
AppearancePatentParsedPayloadDto queuePayload = new AppearancePatentParsedPayloadDto();
queuePayload.setAiPrompt(payload.getAiPrompt());
queuePayload.setApiKey(payload.getApiKey());
queuePayload.setGroups(payload.getGroups() == null ? List.of() : payload.getGroups());
queuePayload.setItems(List.of());
queuePayload.setAllItems(List.of());
queuePayload.setHeaders(List.of());
queuePayload.setSourceFiles(List.of());
return queuePayload;
}
private AppearancePatentParsedPayloadDto hydrateParsedPayloadRows(AppearancePatentParsedPayloadDto payload) {
if (payload == null) {
return new AppearancePatentParsedPayloadDto();
}
List<AppearancePatentParsedRowVo> rows = payload.getAllItems();
if (rows == null || rows.isEmpty()) {
rows = payload.getItems();
}
if ((rows == null || rows.isEmpty()) && payload.getGroups() != null) {
rows = payload.getGroups().stream()
.filter(Objects::nonNull)
.flatMap(group -> group.getItems() == null ? java.util.stream.Stream.empty() : group.getItems().stream())
.toList();
}
if (rows == null) {
rows = List.of();
}
if (payload.getAllItems() == null || payload.getAllItems().isEmpty()) {
payload.setAllItems(rows);
}
if (payload.getItems() == null || payload.getItems().isEmpty()) {
payload.setItems(rows);
}
if ((payload.getGroups() == null || payload.getGroups().isEmpty()) && !rows.isEmpty()) {
payload.setGroups(groupBuilder.apply(rows));
}
return payload;
}
/** 只读收集任务范围/分片载荷指针,供事务提交后做远端删除。 */
public List<String> collectTransientTaskPayloads(Long taskId) {
if (taskId == null || taskId <= 0) {
return List.of();
}
List<String> payloads = new ArrayList<>();
List<TaskScopeStateEntity> scopes = taskScopeStateMapper.selectList(new LambdaQueryWrapper<TaskScopeStateEntity>()
.select(TaskScopeStateEntity::getParsedPayloadJson, TaskScopeStateEntity::getStateJson)
.eq(TaskScopeStateEntity::getTaskId, taskId)
.eq(TaskScopeStateEntity::getModuleType, moduleType));
if (scopes != null) {
for (TaskScopeStateEntity scope : scopes) {
if (scope == null) {
continue;
}
if (scope.getParsedPayloadJson() != null && !scope.getParsedPayloadJson().isBlank()) {
payloads.add(scope.getParsedPayloadJson());
}
if (scope.getStateJson() != null && !scope.getStateJson().isBlank()) {
payloads.add(scope.getStateJson());
}
}
}
List<TaskChunkEntity> chunks = taskChunkMapper.selectList(new LambdaQueryWrapper<TaskChunkEntity>()
.select(TaskChunkEntity::getPayloadJson)
.eq(TaskChunkEntity::getTaskId, taskId)
.eq(TaskChunkEntity::getModuleType, moduleType));
if (chunks != null) {
for (TaskChunkEntity chunk : chunks) {
if (chunk != null && chunk.getPayloadJson() != null && !chunk.getPayloadJson().isBlank()) {
payloads.add(chunk.getPayloadJson());
}
}
}
return payloads;
}
/** 事务提交后逐条删远端载荷;无事务时立即执行(与 TaskResultItemService 同款兜底)。 */
public void deletePayloadsAfterCommit(List<String> payloads, Long taskId) {
if (payloads == null || payloads.isEmpty()) {
return;
}
afterCommitRunner.accept(() -> {
for (String payload : payloads) {
try {
transientPayloadStorageService.deletePayloadIfPresent(payload);
} catch (Exception ex) {
log.warn("[appearance-patent] 载荷删除失败 taskId={} msg={}", taskId, ex.getMessage());
}
}
});
}
/**
* 删除范围/分片的远端载荷(保留给无事务的清理链路调用)。
*/
public void deleteTransientTaskPayloads(Long taskId) {
deletePayloadsAfterCommit(collectTransientTaskPayloads(taskId), taskId);
}
}
@@ -0,0 +1,321 @@
package com.nanri.aiimage.modules.appearancepatent.service.support;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.common.task.TaskStatuses;
import com.nanri.aiimage.modules.appearancepatent.model.vo.AppearancePatentDashboardVo;
import com.nanri.aiimage.modules.appearancepatent.model.vo.AppearancePatentHistoryItemVo;
import com.nanri.aiimage.modules.appearancepatent.model.vo.AppearancePatentHistoryVo;
import com.nanri.aiimage.modules.appearancepatent.model.vo.AppearancePatentTaskBatchVo;
import com.nanri.aiimage.modules.appearancepatent.model.vo.AppearancePatentTaskDetailVo;
import com.nanri.aiimage.modules.appearancepatent.model.vo.AppearancePatentTaskItemVo;
import com.nanri.aiimage.modules.task.mapper.FileResultMapper;
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
import com.nanri.aiimage.modules.task.model.entity.FileResultEntity;
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import com.nanri.aiimage.modules.task.model.entity.TaskFileJobEntity;
import com.nanri.aiimage.modules.task.model.entity.TaskProgressSnapshotEntity;
import com.nanri.aiimage.modules.task.model.vo.TaskProgressLightBatchVo;
import com.nanri.aiimage.modules.task.service.TaskFileJobService;
import com.nanri.aiimage.modules.task.service.TaskProgressLightAssembler;
import com.nanri.aiimage.modules.task.service.TaskProgressSnapshotService;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* 外观专利的进度与视图组装(G 聚类),从 {@code AppearancePatentTaskService} <b>原样搬移</b>
* (3A 拆薄第八笔):看板计数、历史列表、批量进度、文件构建进度百分比与快照节流落库,
* 连同 500ms 节流豁免、终态带真实状态、显示百分比只增不减这些判据一个字没改。
*
* <p>无状态、按调用现取(与 {@code historyAssembler()} 同一先例),不新增 Spring bean。
*/
public class AppearancePatentProgressSupport {
private static final String STATUS_RUNNING = TaskStatuses.FileTask.RUNNING;
private static final String STATUS_SUCCESS = TaskStatuses.FileTask.SUCCESS;
private static final String STATUS_FAILED = TaskStatuses.FileTask.FAILED;
private final String moduleType;
private final TaskProgressLightAssembler taskProgressLightAssembler;
private final FileTaskMapper fileTaskMapper;
private final FileResultMapper fileResultMapper;
private final TaskFileJobService taskFileJobService;
private final TaskProgressSnapshotService taskProgressSnapshotService;
private final ObjectMapper objectMapper;
public AppearancePatentProgressSupport(String moduleType,
TaskProgressLightAssembler taskProgressLightAssembler,
FileTaskMapper fileTaskMapper,
FileResultMapper fileResultMapper,
TaskFileJobService taskFileJobService,
TaskProgressSnapshotService taskProgressSnapshotService,
ObjectMapper objectMapper) {
this.moduleType = moduleType;
this.taskProgressLightAssembler = taskProgressLightAssembler;
this.fileTaskMapper = fileTaskMapper;
this.fileResultMapper = fileResultMapper;
this.taskFileJobService = taskFileJobService;
this.taskProgressSnapshotService = taskProgressSnapshotService;
this.objectMapper = objectMapper;
}
public TaskProgressLightBatchVo progressLight(List<Long> taskIds, Long userId) {
return taskProgressLightAssembler.assemble(moduleType, userId, taskIds);
}
public AppearancePatentDashboardVo dashboard(Long userId) {
AppearancePatentDashboardVo vo = new AppearancePatentDashboardVo();
vo.setPendingTaskCount(countTask(userId, STATUS_RUNNING));
vo.setSuccessTaskCount(countTask(userId, STATUS_SUCCESS));
vo.setFailedTaskCount(countTask(userId, STATUS_FAILED));
vo.setProcessedTaskCount(vo.getSuccessTaskCount() + vo.getFailedTaskCount());
return vo;
}
public AppearancePatentHistoryVo history(Long userId, Integer limit) {
AppearancePatentHistoryVo vo = new AppearancePatentHistoryVo();
int safeLimit = Math.max(1, Math.min(limit == null ? 50 : limit, 100));
List<FileResultEntity> rows = fileResultMapper.selectList(new LambdaQueryWrapper<FileResultEntity>()
.select(FileResultEntity::getId,
FileResultEntity::getTaskId,
FileResultEntity::getSourceFilename,
FileResultEntity::getResultFilename,
FileResultEntity::getResultFileUrl,
FileResultEntity::getRowCount,
FileResultEntity::getSuccess,
FileResultEntity::getErrorMessage,
FileResultEntity::getCreatedAt)
.eq(FileResultEntity::getModuleType, moduleType)
.eq(FileResultEntity::getUserId, userId)
.orderByDesc(FileResultEntity::getCreatedAt)
.last("limit " + safeLimit));
Map<Long, FileTaskEntity> taskMap = new LinkedHashMap<>();
List<Long> taskIds = rows.stream().map(FileResultEntity::getTaskId).filter(Objects::nonNull).distinct().toList();
if (!taskIds.isEmpty()) {
for (FileTaskEntity task : fileTaskMapper.selectList(new LambdaQueryWrapper<FileTaskEntity>()
.select(FileTaskEntity::getId,
FileTaskEntity::getStatus,
FileTaskEntity::getCreatedAt,
FileTaskEntity::getUpdatedAt,
FileTaskEntity::getFinishedAt)
.in(FileTaskEntity::getId, taskIds))) {
taskMap.put(task.getId(), task);
}
}
Map<Long, TaskFileJobEntity> jobMap = taskFileJobService.findAssembleJobsByResultIds(moduleType, rows.stream()
.map(FileResultEntity::getId)
.filter(Objects::nonNull)
.toList());
List<FileResultEntity> sortedRows = new ArrayList<>(rows);
sortedRows.sort(Comparator
.comparingInt((FileResultEntity row) -> historyPriority(row, taskMap.get(row.getTaskId()), jobMap.get(row.getId())))
.thenComparing((FileResultEntity row) -> historyActivityTime(row, taskMap.get(row.getTaskId()), jobMap.get(row.getId())),
Comparator.nullsLast(Comparator.reverseOrder()))
.thenComparing(FileResultEntity::getCreatedAt, Comparator.nullsLast(Comparator.reverseOrder()))
.thenComparing(FileResultEntity::getId, Comparator.nullsLast(Comparator.reverseOrder())));
for (FileResultEntity row : sortedRows) {
FileTaskEntity task = taskMap.get(row.getTaskId());
vo.getItems().add(toHistoryItem(row, task, jobMap.get(row.getId())));
}
return vo;
}
public AppearancePatentTaskBatchVo progressBatch(List<Long> taskIds) {
AppearancePatentTaskBatchVo vo = new AppearancePatentTaskBatchVo();
List<Long> normalizedIds = taskIds == null ? List.of() : taskIds.stream()
.filter(id -> id != null && id > 0)
.distinct()
.toList();
if (normalizedIds.isEmpty()) {
return vo;
}
Map<Long, FileTaskEntity> taskMap = new LinkedHashMap<>();
for (FileTaskEntity task : fileTaskMapper.selectList(new LambdaQueryWrapper<FileTaskEntity>()
.select(FileTaskEntity::getId,
FileTaskEntity::getTaskNo,
FileTaskEntity::getModuleType,
FileTaskEntity::getStatus,
FileTaskEntity::getErrorMessage,
FileTaskEntity::getCreatedAt,
FileTaskEntity::getUpdatedAt,
FileTaskEntity::getFinishedAt)
.in(FileTaskEntity::getId, normalizedIds))) {
if (task != null && moduleType.equals(task.getModuleType())) {
taskMap.put(task.getId(), task);
}
}
List<FileResultEntity> resultRows = fileResultMapper.selectList(new LambdaQueryWrapper<FileResultEntity>()
.select(FileResultEntity::getId,
FileResultEntity::getTaskId,
FileResultEntity::getSourceFilename,
FileResultEntity::getResultFilename,
FileResultEntity::getResultFileUrl,
FileResultEntity::getRowCount,
FileResultEntity::getSuccess,
FileResultEntity::getErrorMessage,
FileResultEntity::getCreatedAt)
.eq(FileResultEntity::getModuleType, moduleType)
.in(FileResultEntity::getTaskId, normalizedIds)
.orderByDesc(FileResultEntity::getCreatedAt));
Map<Long, FileResultEntity> resultByTaskId = new LinkedHashMap<>();
for (FileResultEntity row : resultRows) {
if (row.getTaskId() != null) {
resultByTaskId.putIfAbsent(row.getTaskId(), row);
}
}
Map<Long, TaskFileJobEntity> jobMap = taskFileJobService.findAssembleJobsByResultIds(moduleType, resultRows.stream()
.map(FileResultEntity::getId)
.filter(Objects::nonNull)
.toList());
for (Long taskId : normalizedIds) {
FileTaskEntity task = taskMap.get(taskId);
if (task == null) {
vo.getMissingTaskIds().add(taskId);
continue;
}
AppearancePatentTaskDetailVo detail = new AppearancePatentTaskDetailVo();
detail.setTask(toTaskItem(task));
FileResultEntity resultRow = resultByTaskId.get(taskId);
if (resultRow != null) {
detail.getItems().add(toHistoryItem(resultRow, task, jobMap.get(resultRow.getId())));
}
vo.getItems().add(detail);
}
return vo;
}
public void saveFileBuildProgress(FileTaskEntity task,
TaskFileJobEntity job,
int total,
int completed,
String message) {
if (task == null || task.getId() == null || job == null || job.getId() == null) {
return;
}
int safeTotal = Math.max(1, total);
int safeCompleted = Math.max(0, Math.min(completed, safeTotal));
TaskProgressSnapshotEntity existing = taskProgressSnapshotService.find(task.getId(), moduleType);
int displayPercent = calculateDisplayProgressPercent(safeCompleted, safeTotal, job, LocalDateTime.now());
int previousDisplayPercent = calculateSnapshotDisplayPercent(existing, job);
if (previousDisplayPercent > displayPercent && safeCompleted < safeTotal) {
displayPercent = previousDisplayPercent;
}
// 终态必须带任务真实状态落库:save() 只对终态豁免 500ms 节流,收尾三连写(组装/上传/完成)
// 都在同一次调用里,若全按 RUNNING 写,只有第一条落地,满格「结果文件已生成」必被吞——
// 看板就会永远停在 0/N 或 N-2/N(2026-10-04 生产实测)。对齐货源查询 isTerminalFileBuildProgress。
boolean terminalProgress = safeCompleted >= safeTotal
&& (STATUS_SUCCESS.equals(task.getStatus()) || STATUS_FAILED.equals(task.getStatus()));
if (terminalProgress) {
displayPercent = 100;
}
taskProgressSnapshotService.save(
task.getId(),
moduleType,
terminalProgress ? task.getStatus() : STATUS_RUNNING,
safeTotal,
safeCompleted,
0,
job.getScopeKey(),
message,
Map.of("phase", "RESULT_FILE", "jobId", job.getId(), "displayPercent", displayPercent)
);
}
private int calculateDisplayProgressPercent(int current,
int total,
TaskFileJobEntity job,
LocalDateTime baseTime) {
if (total <= 0) {
return 0;
}
current = Math.max(0, Math.min(current, total));
int percent = Math.max(1, Math.min(99, (int) Math.floor(current * 100.0 / total)));
if (job != null && STATUS_RUNNING.equals(job.getStatus())) {
long elapsedSeconds = baseTime == null ? 0 : Math.max(0, Duration.between(baseTime, LocalDateTime.now()).getSeconds());
if (current <= 0) {
int firstRealProgressPercent = Math.max(1, Math.min(99, (int) Math.floor(100.0 / total)));
int waitingCap = Math.max(8, Math.min(35, firstRealProgressPercent - 1));
percent = Math.max(percent, Math.min(waitingCap, 8 + (int) (elapsedSeconds / 6)));
} else if (current < total) {
percent = Math.max(percent, Math.min(92, percent + (int) (elapsedSeconds / 10)));
}
}
return percent;
}
private int calculateSnapshotDisplayPercent(TaskProgressSnapshotEntity snapshot, TaskFileJobEntity job) {
if (snapshot == null) {
return 0;
}
int total = snapshot.getTotalCount() == null ? 0 : snapshot.getTotalCount();
int current = snapshot.getSuccessCount() == null ? 0 : snapshot.getSuccessCount();
int percent = total <= 0 ? 0 : calculateDisplayProgressPercent(current, total, job, snapshot.getUpdatedAt());
return Math.max(percent, extractSnapshotDisplayPercent(snapshot));
}
private int extractSnapshotDisplayPercent(TaskProgressSnapshotEntity snapshot) {
if (snapshot == null || snapshot.getSnapshotJson() == null || snapshot.getSnapshotJson().isBlank()) {
return 0;
}
try {
JsonNode displayPercent = objectMapper.readTree(snapshot.getSnapshotJson()).path("displayPercent");
if (!displayPercent.isNumber()) {
return 0;
}
return Math.max(0, Math.min(100, displayPercent.asInt()));
} catch (Exception ignored) {
return 0;
}
}
private long countTask(Long userId, String status) {
Long count = fileTaskMapper.selectCount(new LambdaQueryWrapper<FileTaskEntity>()
.eq(FileTaskEntity::getModuleType, moduleType)
.eq(FileTaskEntity::getUserId, userId)
.eq(FileTaskEntity::getStatus, status));
return count == null ? 0L : count;
}
private AppearancePatentTaskItemVo toTaskItem(FileTaskEntity task) {
AppearancePatentTaskItemVo vo = new AppearancePatentTaskItemVo();
vo.setId(task.getId());
vo.setTaskNo(task.getTaskNo());
vo.setStatus(task.getStatus());
vo.setErrorMessage(task.getErrorMessage());
vo.setCreatedAt(fmt(task.getCreatedAt()));
vo.setUpdatedAt(fmt(task.getUpdatedAt()));
vo.setFinishedAt(fmt(task.getFinishedAt()));
return vo;
}
private AppearancePatentHistoryAssembler historyAssembler() {
return new AppearancePatentHistoryAssembler(
taskProgressSnapshotService,
this::calculateDisplayProgressPercent,
this::extractSnapshotDisplayPercent);
}
private AppearancePatentHistoryItemVo toHistoryItem(FileResultEntity row, FileTaskEntity task, TaskFileJobEntity job) {
return historyAssembler().toHistoryItem(row, task, job);
}
private int historyPriority(FileResultEntity row, FileTaskEntity task, TaskFileJobEntity job) {
return historyAssembler().historyPriority(row, task, job);
}
private LocalDateTime historyActivityTime(FileResultEntity row, FileTaskEntity task, TaskFileJobEntity job) {
return historyAssembler().historyActivityTime(row, task, job);
}
private String fmt(LocalDateTime t) {
return t == null ? null : t.toString();
}
}
@@ -0,0 +1,612 @@
package com.nanri.aiimage.modules.appearancepatent.service.support;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.task.TaskStatuses;
import com.nanri.aiimage.common.util.GroupResultPropagator;
import com.nanri.aiimage.config.AppearancePatentProperties;
import com.nanri.aiimage.config.StorageProperties;
import com.nanri.aiimage.modules.appearancepatent.model.dto.AppearancePatentParsedPayloadDto;
import com.nanri.aiimage.modules.appearancepatent.model.dto.AppearancePatentResultRowDto;
import com.nanri.aiimage.modules.appearancepatent.model.dto.AppearancePatentSourceFileDto;
import com.nanri.aiimage.modules.appearancepatent.model.vo.AppearancePatentParsedRowVo;
import com.nanri.aiimage.modules.appearancepatent.service.AppearancePatentTaskCacheService;
import com.nanri.aiimage.modules.file.service.oss.OssStorageService;
import com.nanri.aiimage.modules.task.mapper.FileResultMapper;
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
import com.nanri.aiimage.modules.task.mapper.TaskChunkMapper;
import com.nanri.aiimage.modules.task.mapper.TaskScopeStateMapper;
import com.nanri.aiimage.modules.task.model.entity.FileResultEntity;
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import com.nanri.aiimage.modules.task.model.entity.TaskChunkEntity;
import com.nanri.aiimage.modules.task.model.entity.TaskFileJobEntity;
import com.nanri.aiimage.modules.task.model.entity.TaskScopeStateEntity;
import com.nanri.aiimage.modules.task.service.TaskDistributedLockService;
import com.nanri.aiimage.modules.task.service.TaskFileJobService;
import com.nanri.aiimage.modules.task.service.TaskFinalizeSupport;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import java.io.File;
import java.io.FileOutputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
* 外观专利的结果作业生命周期与出表(E 聚类之二),从 {@code AppearancePatentTaskService}
* <b>原样搬移</b>(3A 拆薄第十一笔):作业取锁/归属/进度、终态收尾与结果记录补建、
* 失败兜底组装、覆盖率校验后的 xlsx/zip 出表与临时文件清理。
*
* <p>无状态、按调用现取(与 {@code historyAssembler()} 同一先例),不新增 Spring bean。
* 取锁、归属、进度、序列化、聚合命名与交付闸门由宿主以回调/委托交出。
*/
@Slf4j
public class AppearancePatentResultJobSupport {
private static final String STATUS_RUNNING = TaskStatuses.FileTask.RUNNING;
private static final String STATUS_FAILED = TaskStatuses.FileTask.FAILED;
private static final String CONTENT_TYPE_XLSX = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
private static final String CONTENT_TYPE_ZIP = "application/zip";
private final String moduleType;
private final long lockWaitMillis;
private final AppearancePatentProperties properties;
private final StorageProperties storageProperties;
private final FileTaskMapper fileTaskMapper;
private final FileResultMapper fileResultMapper;
private final TaskScopeStateMapper taskScopeStateMapper;
private final TaskChunkMapper taskChunkMapper;
private final AppearancePatentTaskCacheService taskCacheService;
private final TaskFileJobService taskFileJobService;
private final OssStorageService ossStorageService;
private final AppearancePatentPayloadSupport payloadSupport;
private final AppearancePatentResultRowReader rowReader;
private final AppearancePatentResultPackager resultPackager;
private final AppearancePatentDeliverySupport deliverySupport;
private final AppearancePatentProgressSupport progressSupport;
private final AppearancePatentLlmBatchPipeline llmBatchPipeline;
private final AppearancePatentTaskOwnership ownership;
private final LockAcquirer lockAcquirer;
private final ActivityToucher activityToucher;
private final StatusResolver statusResolver;
private final FirstNonBlank firstNonBlank;
private final AggregateFilenameBuilder aggregateFilenameBuilder;
private final AggregateScopeKeyBuilder aggregateScopeKeyBuilder;
public interface LockAcquirer {
TaskDistributedLockService.LockHandle acquire(Long taskId, long waitMillis);
}
public interface ActivityToucher {
void touch(Long taskId);
}
public interface StatusResolver {
String resolve(boolean waitingForAssemble, boolean executionFailed);
}
public interface FirstNonBlank {
String pick(String preferred, String fallback);
}
public interface AggregateFilenameBuilder {
String build(List<AppearancePatentSourceFileDto> sourceFiles);
}
public interface AggregateScopeKeyBuilder {
String build(List<AppearancePatentSourceFileDto> sourceFiles);
}
public AppearancePatentResultJobSupport(String moduleType,
long lockWaitMillis,
AppearancePatentProperties properties,
StorageProperties storageProperties,
FileTaskMapper fileTaskMapper,
FileResultMapper fileResultMapper,
TaskScopeStateMapper taskScopeStateMapper,
TaskChunkMapper taskChunkMapper,
AppearancePatentTaskCacheService taskCacheService,
TaskFileJobService taskFileJobService,
OssStorageService ossStorageService,
AppearancePatentPayloadSupport payloadSupport,
AppearancePatentResultRowReader rowReader,
AppearancePatentResultPackager resultPackager,
AppearancePatentDeliverySupport deliverySupport,
AppearancePatentProgressSupport progressSupport,
AppearancePatentLlmBatchPipeline llmBatchPipeline,
AppearancePatentTaskOwnership ownership,
LockAcquirer lockAcquirer,
ActivityToucher activityToucher,
StatusResolver statusResolver,
FirstNonBlank firstNonBlank,
AggregateFilenameBuilder aggregateFilenameBuilder,
AggregateScopeKeyBuilder aggregateScopeKeyBuilder) {
this.moduleType = moduleType;
this.lockWaitMillis = lockWaitMillis;
this.properties = properties;
this.storageProperties = storageProperties;
this.fileTaskMapper = fileTaskMapper;
this.fileResultMapper = fileResultMapper;
this.taskScopeStateMapper = taskScopeStateMapper;
this.taskChunkMapper = taskChunkMapper;
this.taskCacheService = taskCacheService;
this.taskFileJobService = taskFileJobService;
this.ossStorageService = ossStorageService;
this.payloadSupport = payloadSupport;
this.rowReader = rowReader;
this.resultPackager = resultPackager;
this.deliverySupport = deliverySupport;
this.progressSupport = progressSupport;
this.llmBatchPipeline = llmBatchPipeline;
this.ownership = ownership;
this.lockAcquirer = lockAcquirer;
this.activityToucher = activityToucher;
this.statusResolver = statusResolver;
this.firstNonBlank = firstNonBlank;
this.aggregateFilenameBuilder = aggregateFilenameBuilder;
this.aggregateScopeKeyBuilder = aggregateScopeKeyBuilder;
}
public void maybeRecoverTerminalFailedAssemble(Long taskId) {
if (taskId == null || taskId <= 0) {
return;
}
try {
FileResultEntity result = findResultRecord(taskId);
if (result == null) {
return;
}
if (taskFileJobService.hasSuccessfulAssembleJob(taskId, moduleType, result.getId())) {
return;
}
if (!taskFileJobService.isTerminalFailedAssembleJob(taskId, moduleType, result.getId())) {
return;
}
if (!isResultSubmissionComplete(taskId)) {
log.info("[appearance-patent] 组装 job 终态失败但分片仍未补传完整,暂不恢复 taskId={} resultId={}",
taskId, result.getId());
return;
}
log.info("[appearance-patent] 分片已补传完整,恢复终态失败的组装 job taskId={} resultId={}",
taskId, result.getId());
taskFileJobService.resetTerminalFailedForRecovery(taskId, moduleType, result.getId());
} catch (Exception ex) {
log.warn("[appearance-patent] 补传恢复检查失败(不影响本次补传)taskId={} err={}", taskId, ex.getMessage(), ex);
}
}
/** 按 task 取结果行(不创建);不存在返回 null。 */
private FileResultEntity findResultRecord(Long taskId) {
List<FileResultEntity> rows = fileResultMapper.selectList(new LambdaQueryWrapper<FileResultEntity>()
.eq(FileResultEntity::getTaskId, taskId)
.eq(FileResultEntity::getModuleType, moduleType)
.last("limit 1"));
return rows == null || rows.isEmpty() ? null : rows.getFirst();
}
public void finalizeTask(FileTaskEntity task, String error, int rowCount, boolean assembleWorkbook) {
String finalError = error;
AppearancePatentRowOutcome.Facts deliveryFacts = AppearancePatentRowOutcome.Facts.EMPTY;
FileResultEntity result = null;
boolean persistedRowsPresent = rowReader.hasPersistedResultRows(task.getId());
List<FileResultEntity> rows = fileResultMapper.selectList(new LambdaQueryWrapper<FileResultEntity>()
.eq(FileResultEntity::getTaskId, task.getId())
.eq(FileResultEntity::getModuleType, moduleType)
.last("limit 1"));
if (!rows.isEmpty()) {
result = rows.getFirst();
} else if (assembleWorkbook && persistedRowsPresent) {
result = createResultRecordForAssembly(task, rowCount);
}
if (result != null) {
boolean shouldAssembleResult = assembleWorkbook && (finalError == null || finalError.isBlank() || persistedRowsPresent);
if (shouldAssembleResult && shouldAssembleSynchronously()) {
try {
deliveryFacts = assembleResultWorkbook(task, result);
} catch (Exception ex) {
log.warn("[appearance-patent] assemble result workbook failed taskId={} err={}", task.getId(), ex.getMessage());
finalError = firstNonBlank.pick(finalError, "Generate appearance patent result failed");
}
}
}
boolean failed = finalError != null && !finalError.isBlank();
boolean waitingForAssemble = !failed && assembleWorkbook && !shouldAssembleSynchronously();
task.setStatus(statusResolver.resolve(waitingForAssemble, failed));
task.setSuccessFileCount(failed ? 0 : 1);
task.setFailedFileCount(failed ? 1 : 0);
// 缺口只写在消息里,不参与 failed 计算:95% 以上有结论的单仍是成功,但用户要看得见"N 行没检测完"
task.setErrorMessage(deliverySupport.appendDeliveryGapMessage(finalError, deliveryFacts));
task.setUpdatedAt(LocalDateTime.now());
task.setFinishedAt(waitingForAssemble ? null : LocalDateTime.now());
fileTaskMapper.updateById(task);
if (result != null) {
result.setSuccess(failed ? 0 : 1);
result.setErrorMessage(finalError);
result.setRowCount(rowCount > 0 ? rowCount : result.getRowCount());
boolean shouldAssembleResult = assembleWorkbook && (!failed || persistedRowsPresent);
if (shouldAssembleResult) {
result.setResultFilename(resultPackager.safeFileStem(result.getSourceFilename()) + "-result.xlsx");
result.setResultFileUrl(null);
result.setResultFileSize(0L);
result.setResultContentType(CONTENT_TYPE_XLSX);
}
fileResultMapper.updateById(result);
if (shouldAssembleResult) {
enqueueResultAssembly(task, result, true);
} else if (assembleWorkbook && failed) {
log.warn("[appearance-patent] skip failed task workbook assembly because no persisted result rows taskId={}", task.getId());
}
}
taskCacheService.deleteTaskCache(task.getId());
}
public FileResultEntity findOrCreateResultRecordForAssembly(FileTaskEntity task, int rowCount) {
if (task == null || task.getId() == null) {
return null;
}
List<FileResultEntity> rows = fileResultMapper.selectList(new LambdaQueryWrapper<FileResultEntity>()
.eq(FileResultEntity::getTaskId, task.getId())
.eq(FileResultEntity::getModuleType, moduleType)
.last("limit 1"));
if (rows != null && !rows.isEmpty()) {
return rows.getFirst();
}
return createResultRecordForAssembly(task, rowCount);
}
private TaskFileJobEntity enqueueResultAssembly(FileTaskEntity task, FileResultEntity result, boolean dispatchWhenIdle) {
if (task == null || task.getId() == null || result == null || result.getId() == null) {
return null;
}
TaskFileJobEntity job = taskFileJobService.enqueueAssembleResult(
task.getId(), moduleType, result.getId(), ownership.buildTaskOwnerScopeKey(task));
if (dispatchWhenIdle
&& job != null
&& "RUNNING".equals(job.getStatus())) {
taskFileJobService.requeue(job.getId(), "Python upload finished, assembling xlsx");
}
return job;
}
private FileResultEntity createResultRecordForAssembly(FileTaskEntity task, int rowCount) {
AppearancePatentParsedPayloadDto payload = payloadSupport.readParsedPayload(task);
List<AppearancePatentSourceFileDto> sourceFiles = payload.getSourceFiles() == null ? List.of() : payload.getSourceFiles();
FileResultEntity result = new FileResultEntity();
result.setTaskId(task.getId());
result.setModuleType(moduleType);
result.setSourceFilename(aggregateFilenameBuilder.build(sourceFiles));
result.setSourceFileUrl(aggregateScopeKeyBuilder.build(sourceFiles));
result.setRowCount(rowCount > 0 ? rowCount : (payload.getAllItems() == null ? 0 : payload.getAllItems().size()));
result.setUserId(task.getUserId());
result.setCreatedAt(LocalDateTime.now());
fileResultMapper.insert(result);
log.warn("[appearance-patent] recreated missing result record for workbook assembly taskId={} resultId={}",
task.getId(), result.getId());
return result;
}
private boolean shouldAssembleSynchronously() {
return false;
}
public boolean processResultFileJob(TaskFileJobEntity job) {
if (job == null || job.getTaskId() == null || job.getResultId() == null) {
throw new BusinessException("结果文件作业参数不完整");
}
TaskDistributedLockService.LockHandle lockHandle = lockAcquirer.acquire(job.getTaskId(), lockWaitMillis);
if (lockHandle == null) {
taskFileJobService.requeue(job.getId(), "Task is busy, waiting for appearance patent result merge");
activityToucher.touch(job.getTaskId());
return false;
}
try (lockHandle) {
return processResultFileJobLocked(job);
}
}
private boolean processResultFileJobLocked(TaskFileJobEntity job) {
FileTaskEntity task = fileTaskMapper.selectById(job.getTaskId());
if (task == null || !moduleType.equals(task.getModuleType())) {
throw new BusinessException("任务不存在");
}
ownership.rejectIfOwnedByAnotherInstance(task, "assemble result file");
job.setScopeKey(ownership.buildTaskOwnerScopeKey(task));
if (!ownership.isOwnerCurrent(ownership.ownerFromScopeKey(job.getScopeKey()))) {
log.info("[appearance-patent] skip result file job because owner is another instance jobId={} taskId={} owner={} current={}",
job.getId(), job.getTaskId(), ownership.ownerFromScopeKey(job.getScopeKey()), ownership.currentInstanceId());
return false;
}
FileResultEntity result = fileResultMapper.selectById(job.getResultId());
if (result == null || !moduleType.equals(result.getModuleType())) {
throw new BusinessException("结果记录不存在");
}
// 已交付的作业不再重跑。Worker 那三处 SUCCESS 守卫挡不住这一格:结果文件已经挂上、
// 作业却被事件重投时它照样执行,而分片在交付时已被 cleanupResultFileJob 删掉,
// 重跑只能读到 0 行、连抛「结果为空」把 retry 预算烧满(2026-10-19 任务 31527:
// 23:02:35 交付,23:02:40→23:03:20 又跑五次,行账读数 expectedRows=0/coverage=100.00%
// 与那条抛同时出现——空集在闸门里是"通过",出表那边却是"没结果")。
// 与 fallbackAssembleResultFile 同一枚幂等闸。补传恢复不受影响:
// maybeRecoverTerminalFailedAssemble 自带 hasSuccessfulAssembleJob 早退,
// 而交付之后任务已终态,迟到分片被 rejectNotRunning 拒掉,没有合法的第二轮组装。
if (result.getResultFileUrl() != null && !result.getResultFileUrl().isBlank()) {
log.info("[appearance-patent] 结果文件已交付,跳过重复组装 taskId={} resultId={} jobId={}",
task.getId(), result.getId(), job.getId());
return true;
}
List<TaskChunkEntity> chunks = taskChunkMapper.selectList(new LambdaQueryWrapper<TaskChunkEntity>()
.eq(TaskChunkEntity::getTaskId, task.getId())
.eq(TaskChunkEntity::getModuleType, moduleType)
.orderByAsc(TaskChunkEntity::getChunkIndex));
int llmWorkUnits = llmBatchPipeline.countLlmWorkUnits(chunks, Math.max(1, properties.getLlmBatchSize()));
int plannedLlmUnits = Math.max(1, llmWorkUnits);
int totalProgressUnits = Math.max(3, plannedLlmUnits + 3);
progressSupport.saveFileBuildProgress(task, job, totalProgressUnits, 0, "正在提交检测");
llmBatchPipeline.submitLlmBatches(task, result, job, chunks);
if (STATUS_RUNNING.equals(task.getStatus()) && !isResultSubmissionComplete(task.getId())) {
taskFileJobService.touchRunning(job.getId());
activityToucher.touch(task.getId());
progressSupport.saveFileBuildProgress(task, job, totalProgressUnits, Math.max(1, plannedLlmUnits), "等待 Python 继续回传数据");
return false;
}
return completeLlmFileJob(task, result, job, totalProgressUnits);
}
private boolean completeLlmFileJob(FileTaskEntity task,
FileResultEntity result,
TaskFileJobEntity job,
int totalProgressUnits) {
int assembleProgress = Math.max(1, totalProgressUnits - 2);
progressSupport.saveFileBuildProgress(task, job, totalProgressUnits, assembleProgress, "正在组装 xlsx");
// 补检决定必须做在出表之前:assembleResultWorkbook 一跑完就把 xlsx 传上 OSS 并挂好
// resultFileUrl,那时才发现缺口,半张表已经在用户的下载列表里了。
if (deliverySupport.requestRecheckForMissingRows(task, job, deliverySupport.measureDeliveryFacts(task, result))) {
// 半张表先不发出去:撤销未完成行的检测标记、把作业排回队列补检一轮,
// 上限由行级轮次闸(llmRowMaxRounds)与补检轮次闸(recheckMaxRounds)共同兜住。
return false;
}
AppearancePatentRowOutcome.Facts deliveryFacts = assembleResultWorkbook(task, result);
progressSupport.saveFileBuildProgress(task, job, totalProgressUnits, totalProgressUnits - 1, "正在上传结果文件");
fileResultMapper.updateById(result);
boolean taskAlreadyFailed = STATUS_FAILED.equals(task.getStatus())
|| (task.getErrorMessage() != null && !task.getErrorMessage().isBlank());
String existingError = task.getErrorMessage();
task.setStatus(statusResolver.resolve(false, taskAlreadyFailed));
task.setSuccessFileCount(taskAlreadyFailed ? 0 : 1);
task.setFailedFileCount(taskAlreadyFailed ? 1 : 0);
task.setErrorMessage(deliverySupport.appendDeliveryGapMessage(taskAlreadyFailed ? existingError : null, deliveryFacts));
task.setUpdatedAt(LocalDateTime.now());
task.setFinishedAt(LocalDateTime.now());
fileTaskMapper.updateById(task);
taskCacheService.deleteTaskCache(task.getId());
progressSupport.saveFileBuildProgress(task, job, totalProgressUnits, totalProgressUnits, "结果文件已生成");
return true;
}
/**
* 失败兜底:组装作业重试耗尽(WAIT_LLM 停放被 stuck 棘轮判死、或组装异常连吃 5 次重试)后调用,
* 用已回传的分片与已拿到结论的行尽力生成可下载的部分结果文件。
*
* <p>用户线上点名要的保证:「起码失败了也可以下载」。判死时已跑完的检测结论仍挂在分片里,
* 不出表就一张都不剩(线上任务 31302:1196 行成品困在判死作业里零交付)。
*
* <p>覆盖率闸门按「允许部分结果」放行(缺口只记行账);任务状态在这里**不收尾**——判死时
* 任务可能仍在跑、客户端仍在心跳(stuck 棘轮只判作业、不判任务),提前置终态会把活任务误杀;
* 任务终态仍由 stale 收尾链路 / 分片回传链路按既有口径落。文件挂上 result(result_file_url)
* 后前端下载按钮即出现,与任务/作业状态无关({@code AppearancePatentHistoryAssembler#attachFileJobState})。
*
* <p>幂等:结果文件已存在(result_file_url 非空)直接返回 true,不重做组装——stuck 扫描对
* 终态失败作业每轮都会重入兜底钩子,靠这里挡住重复组装。与补传恢复(maybeRecoverTerminalFailedAssemble)
* 的重跑并发时两边都只写合法结果文件,后写者覆盖,无中间态。
*
* <p>实现自吞异常(兜底失败只记日志,不影响作业已终态失败的事实),返回是否有可下载结果。
*/
public boolean fallbackAssembleResultFile(TaskFileJobEntity job) {
if (job == null || job.getTaskId() == null || job.getResultId() == null) {
return false;
}
try {
FileResultEntity result = fileResultMapper.selectById(job.getResultId());
if (result == null || !TaskFinalizeSupport.belongsToModule(moduleType, result.getModuleType())) {
log.warn("[appearance-patent] fallback assemble skipped because result record missing taskId={} resultId={}",
job.getTaskId(), job.getResultId());
return false;
}
if (result.getResultFileUrl() != null && !result.getResultFileUrl().isBlank()) {
log.info("[appearance-patent] fallback assemble skipped because result file already exists taskId={} resultId={} jobStatus={}",
job.getTaskId(), job.getResultId(), job.getStatus());
return true;
}
FileTaskEntity task = fileTaskMapper.selectById(job.getTaskId());
if (task == null || !TaskFinalizeSupport.belongsToModule(moduleType, task.getModuleType())) {
log.warn("[appearance-patent] fallback assemble skipped because task missing taskId={} resultId={}",
job.getTaskId(), job.getResultId());
return false;
}
// 与 processResultFileJobLocked 同一判法:非归属实例让给归属机(stuck 扫描两台都在跑,
// 不挡的话每台都会每 60 秒重入一次兜底钩子)。
job.setScopeKey(ownership.buildTaskOwnerScopeKey(task));
if (!ownership.isOwnerCurrent(ownership.ownerFromScopeKey(job.getScopeKey()))) {
log.info("[appearance-patent] fallback assemble skipped because owner is another instance taskId={} resultId={}",
job.getTaskId(), job.getResultId());
return false;
}
if (deliverySupport.scheduleFallbackRecheck(task, result, deliverySupport.measureDeliveryFacts(task, result))) {
return false;
}
AppearancePatentRowOutcome.Facts facts = assembleResultWorkbook(task, result, true);
fileResultMapper.updateById(result);
log.warn("[appearance-patent] fallback assemble produced partial result taskId={} resultId={} jobStatus={} expectedRows={} judgedRows={} missingRows={} noDataRows={}",
job.getTaskId(), job.getResultId(), job.getStatus(),
facts.expectedRows(), facts.judgedRows(), facts.missingRows(), facts.noDataRows());
return true;
} catch (Exception ex) {
log.warn("[appearance-patent] fallback assemble failed taskId={} resultId={} msg={}",
job.getTaskId(), job.getResultId(), ex.getMessage(), ex);
return false;
}
}
public boolean isResultSubmissionComplete(Long taskId) {
if (taskId == null || taskId <= 0) {
return false;
}
Long count = taskScopeStateMapper.selectCount(new LambdaQueryWrapper<TaskScopeStateEntity>()
.eq(TaskScopeStateEntity::getTaskId, taskId)
.eq(TaskScopeStateEntity::getModuleType, moduleType)
.isNull(TaskScopeStateEntity::getLlmStatus)
.isNotNull(TaskScopeStateEntity::getLastChunkAt)
.eq(TaskScopeStateEntity::getCompleted, 1));
return count != null && count > 0;
}
public void cleanupResultFileJob(TaskFileJobEntity job) {
if (job == null || job.getTaskId() == null) {
return;
}
payloadSupport.deleteTransientTaskPayloads(job.getTaskId());
taskChunkMapper.delete(new LambdaQueryWrapper<TaskChunkEntity>()
.eq(TaskChunkEntity::getTaskId, job.getTaskId())
.eq(TaskChunkEntity::getModuleType, moduleType));
taskScopeStateMapper.delete(new LambdaQueryWrapper<TaskScopeStateEntity>()
.eq(TaskScopeStateEntity::getTaskId, job.getTaskId())
.eq(TaskScopeStateEntity::getModuleType, moduleType));
}
private AppearancePatentRowOutcome.Facts assembleResultWorkbook(FileTaskEntity task, FileResultEntity result) {
return assembleResultWorkbook(task, result, false);
}
/**
* @param allowPartial 供失败兜底路径({@code fallbackAssembleResultFile})使用:
* 覆盖率闸门按「允许部分结果」放行——那条路在调用本方法前已经先问过
* {@code scheduleFallbackRecheck},缺口能补的都补过了、补检预算也见底了,
* 此刻拦下成品只会让用户连半张表都拿不到;缺口仍由行账锚点记数。
*/
private AppearancePatentRowOutcome.Facts assembleResultWorkbook(FileTaskEntity task, FileResultEntity result,
boolean allowPartial) {
AppearancePatentParsedPayloadDto parsed = payloadSupport.readParsedPayload(task);
List<AppearancePatentParsedRowVo> parsedRows = parsed.getAllItems() == null
? List.of() : parsed.getAllItems();
List<AppearancePatentResultPackager.SourceRows> sourceRows = resultPackager.splitRowsBySourceFile(parsed, parsedRows, result.getSourceFilename());
if (sourceRows.isEmpty()) {
throw new BusinessException("外观专利检测结果为空,请稍后重试生成结果文件");
}
int receivedRowCount = 0;
long resolvedRows = 0L;
long reasonRows = 0L;
int conclusionPropagated = 0;
AppearancePatentRowOutcome.Facts deliveryFacts = AppearancePatentRowOutcome.Facts.EMPTY;
File outputDir = new File(storageProperties.getLocalTempDir(), "appearance-patent-result");
if (!outputDir.exists() && !outputDir.mkdirs()) {
throw new BusinessException("创建结果目录失败");
}
List<AppearancePatentResultPackager.SourceResultWorkbook> workbooks = new ArrayList<>();
File zip = null;
try {
for (AppearancePatentResultPackager.SourceRows item : sourceRows) {
Map<String, AppearancePatentResultRowDto> resultMap =
rowReader.loadPersistedResultRowsForRowsWithRetry(task.getId(), item.rows());
// 覆盖率先于「本文件无结果就跳过」判定:整源文件的 LLM 结果全丢(分片被跳过、
// 结果清空)时覆盖率是 0%,必须在这里判掉,不能让 zip 少一个文件还报任务成功。
deliveryFacts = deliveryFacts.plus(
deliverySupport.validateCompleteLlmCoverage(task.getId(), item.rows(), resultMap, allowPartial));
List<AppearancePatentParsedRowVo> receivedRows = rowReader.filterReceivedParsedRows(item.rows(), resultMap);
if (receivedRows.isEmpty()) {
resultMap.clear();
continue;
}
receivedRowCount += receivedRows.size();
resolvedRows += receivedRows.stream()
.filter(row -> rowReader.findResultRow(row, resultMap) != null)
.count();
reasonRows += resultMap.values().stream()
.filter(deliverySupport::hasReasonFields)
.count();
conclusionPropagated += GroupResultPropagator.propagateByGroup(
receivedRows,
AppearancePatentParsedRowVo::getDisplayId,
row -> rowReader.findResultRow(row, resultMap),
AppearancePatentResultRowDto::getConclusion,
AppearancePatentResultRowDto::setConclusion,
List.of("已侵权", "侵权"),
"[appearance-patent] taskId=" + task.getId()
);
String filename = resultPackager.safeFileStem(item.sourceFilename()) + "-result.xlsx";
String tempFilename = resultPackager.safeFileStem(item.sourceFilename())
+ "-" + task.getId()
+ "-" + result.getId()
+ "-" + UUID.randomUUID()
+ "-result.xlsx";
File xlsx = new File(outputDir, tempFilename);
writeResultWorkbook(xlsx, parsed, receivedRows, resultMap);
workbooks.add(new AppearancePatentResultPackager.SourceResultWorkbook(xlsx, filename, receivedRows.size()));
resultMap.clear();
}
if (workbooks.isEmpty()) {
throw new BusinessException("外观专利检测结果为空,请稍后重试生成结果文件");
}
log.info("[appearance-patent] assemble workbook taskId={} parsedRows={} receivedRows={} resultRows={} resolvedRows={} reasonRows={}",
task.getId(), parsedRows.size(), receivedRowCount,
workbooks.stream().mapToInt(AppearancePatentResultPackager.SourceResultWorkbook::rowCount).sum(), resolvedRows, reasonRows);
if (conclusionPropagated > 0) {
log.info("[appearance-patent] group propagate conclusion taskId={} updatedRows={}",
task.getId(), conclusionPropagated);
}
File uploadFile;
String filename;
String contentType;
if (workbooks.size() == 1) {
AppearancePatentResultPackager.SourceResultWorkbook workbook = workbooks.get(0);
uploadFile = workbook.file();
filename = workbook.filename();
contentType = CONTENT_TYPE_XLSX;
} else {
filename = resultPackager.safeFileStem(result.getSourceFilename()) + "-result.zip";
String tempFilename = resultPackager.safeFileStem(result.getSourceFilename())
+ "-" + task.getId()
+ "-" + result.getId()
+ "-" + UUID.randomUUID()
+ "-result.zip";
zip = new File(outputDir, tempFilename);
resultPackager.packageResultWorkbooksAsZip(zip, workbooks);
uploadFile = zip;
contentType = CONTENT_TYPE_ZIP;
}
String objectKey = ossStorageService.uploadResultFile(uploadFile, moduleType);
result.setResultFilename(filename);
result.setResultFileUrl(objectKey);
result.setResultFileSize(uploadFile.length());
result.setResultContentType(contentType);
result.setRowCount(receivedRowCount);
return deliveryFacts;
} finally {
for (AppearancePatentResultPackager.SourceResultWorkbook workbook : workbooks) {
if (workbook.file().exists() && !workbook.file().delete()) {
log.warn("[appearance-patent] delete temp xlsx failed file={}", workbook.file());
}
}
if (zip != null && zip.exists() && !zip.delete()) {
log.warn("[appearance-patent] delete temp zip failed file={}", zip);
}
}
}
public void writeResultWorkbook(File xlsx,
AppearancePatentParsedPayloadDto parsed,
List<AppearancePatentParsedRowVo> receivedRows,
Map<String, AppearancePatentResultRowDto> resultMap) {
try (SXSSFWorkbook workbook = new SXSSFWorkbook(200); FileOutputStream fos = new FileOutputStream(xlsx)) {
AppearancePatentSheetBuilder.buildResultSheet(workbook, receivedRows, resultMap,
parsedRow -> rowReader.findResultRow(parsedRow, resultMap));
workbook.write(fos);
workbook.dispose();
} catch (Exception ex) {
throw new BusinessException("生成外观专利检测结果失败");
}
}
}
@@ -0,0 +1,344 @@
package com.nanri.aiimage.modules.appearancepatent.service.support;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.modules.appearancepatent.model.dto.AppearancePatentParsedPayloadDto;
import com.nanri.aiimage.modules.appearancepatent.model.dto.AppearancePatentResultGroupDto;
import com.nanri.aiimage.modules.appearancepatent.model.dto.AppearancePatentResultRowDto;
import com.nanri.aiimage.modules.appearancepatent.model.dto.AppearancePatentSubmitResultRequest;
import com.nanri.aiimage.modules.appearancepatent.model.vo.AppearancePatentParsedGroupVo;
import com.nanri.aiimage.modules.appearancepatent.model.vo.AppearancePatentParsedRowVo;
import com.nanri.aiimage.modules.task.mapper.TaskChunkMapper;
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import com.nanri.aiimage.modules.task.model.entity.TaskChunkEntity;
import com.nanri.aiimage.modules.task.service.TransientPayloadStorageService;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
/**
* 外观专利的结果行读取(H 聚类),从 {@code AppearancePatentTaskService} <b>原样搬移</b>
* (3A 拆薄第七笔):回传分组展开、解析行计数、分片载荷读取、结果行按键分页读取与行键口径,
* 连同分页大小、重试次数、缺失载荷的跳过判据一个字没改。
*
* <p><b>搬的是读取与行键,不是宿主。</b>解析载荷读取(I 聚类)仍由服务侧传入;
* 字符串归一也以回调交入,避免把解析面的工具再抄一份。分片读取的异常语义保持原样:
* 只有 RustFS 的 "does not exist" 才允许跳过该分片,网络类失败仍抛出以便重试。
*/
@Slf4j
public class AppearancePatentResultRowReader {
/** 结果行读取时 chunk 的 keyset 页大小,与 similarasin 侧 loadChunksKeyset 的 500 同口径。 */
private static final int RESULT_ROWS_CHUNK_PAGE_SIZE = 500;
private static final int RESULT_ROWS_READ_RETRY_LIMIT = 3;
private static final long RESULT_ROWS_READ_RETRY_DELAY_MS = 500L;
private final String moduleType;
private final ObjectMapper objectMapper;
private final TransientPayloadStorageService transientPayloadStorageService;
private final TaskChunkMapper taskChunkMapper;
private final Function<String, String> normalizer;
private final Function<FileTaskEntity, AppearancePatentParsedPayloadDto> parsedPayloadReader;
public AppearancePatentResultRowReader(String moduleType,
ObjectMapper objectMapper,
TransientPayloadStorageService transientPayloadStorageService,
TaskChunkMapper taskChunkMapper,
Function<String, String> normalizer,
Function<FileTaskEntity, AppearancePatentParsedPayloadDto> parsedPayloadReader) {
this.moduleType = moduleType;
this.objectMapper = objectMapper;
this.transientPayloadStorageService = transientPayloadStorageService;
this.taskChunkMapper = taskChunkMapper;
this.normalizer = normalizer;
this.parsedPayloadReader = parsedPayloadReader;
}
public List<AppearancePatentResultRowDto> flattenSubmittedRows(AppearancePatentSubmitResultRequest request) {
if (request == null) {
return List.of();
}
List<AppearancePatentResultGroupDto> groups = request.getGroups();
if (groups != null && !groups.isEmpty()) {
List<AppearancePatentResultRowDto> rows = new ArrayList<>();
for (AppearancePatentResultGroupDto group : groups) {
if (group == null || group.getItems() == null || group.getItems().isEmpty()) {
continue;
}
for (AppearancePatentResultRowDto row : group.getItems()) {
if (row == null) {
continue;
}
if (normalizer.apply(row.getGroupKey()).isBlank()) {
row.setGroupKey(group.getGroupKey());
}
if (normalizer.apply(row.getSourceFileKey()).isBlank()) {
row.setSourceFileKey(group.getSourceFileKey());
}
if (normalizer.apply(row.getSourceFilename()).isBlank()) {
row.setSourceFilename(group.getSourceFilename());
}
rows.add(row);
}
}
return rows;
}
return request.getItems() == null ? List.of() : request.getItems();
}
public int allRowCount(FileTaskEntity task) {
try {
AppearancePatentParsedPayloadDto payload = parsedPayloadReader.apply(task);
if (payload.getAllItems() != null && !payload.getAllItems().isEmpty()) {
return payload.getAllItems().size();
}
if (payload.getItems() != null && !payload.getItems().isEmpty()) {
return payload.getItems().size();
}
if (payload.getGroups() != null && !payload.getGroups().isEmpty()) {
return payload.getGroups().stream()
.map(AppearancePatentParsedGroupVo::getItems)
.filter(Objects::nonNull)
.mapToInt(List::size)
.sum();
}
return 0;
} catch (Exception ex) {
log.warn("[appearance-patent] read all row count failed taskId={} err={}", task.getId(), ex.getMessage());
return 0;
}
}
public List<AppearancePatentParsedRowVo> filterReceivedParsedRows(List<AppearancePatentParsedRowVo> parsedRows,
Map<String, AppearancePatentResultRowDto> resultMap) {
if (parsedRows == null || parsedRows.isEmpty() || resultMap == null || resultMap.isEmpty()) {
return List.of();
}
List<AppearancePatentParsedRowVo> receivedRows = new ArrayList<>();
for (AppearancePatentParsedRowVo parsedRow : parsedRows) {
if (findResultRow(parsedRow, resultMap) != null) {
receivedRows.add(parsedRow);
}
}
return receivedRows;
}
public boolean hasPersistedResultRows(Long taskId) {
if (taskId == null) {
return false;
}
Long count = taskChunkMapper.selectCount(new LambdaQueryWrapper<TaskChunkEntity>()
.eq(TaskChunkEntity::getTaskId, taskId)
.eq(TaskChunkEntity::getModuleType, moduleType));
return count != null && count > 0;
}
public Map<String, AppearancePatentResultRowDto> loadPersistedResultRowsForRowsWithRetry(
Long taskId, List<AppearancePatentParsedRowVo> requestedRows) {
Set<String> requestedKeys = resultLookupKeysForParsedRows(requestedRows);
Map<String, AppearancePatentResultRowDto> result =
loadPersistedResultRowsForKeys(taskId, requestedKeys);
if (requestedKeys.isEmpty() || !result.isEmpty()) {
return result;
}
for (int attempt = 1; attempt <= RESULT_ROWS_READ_RETRY_LIMIT && result.isEmpty(); attempt++) {
sleepBeforeResultRowsRetry(attempt);
result = loadPersistedResultRowsForKeys(taskId, requestedKeys);
if (!result.isEmpty()) {
log.info("[appearance-patent] result rows recovered after retry taskId={} attempt={} rows={}",
taskId, attempt, result.size());
}
}
return result;
}
private Map<String, AppearancePatentResultRowDto> loadPersistedResultRowsForKeys(
Long taskId, Set<String> requestedKeys) {
Map<String, AppearancePatentResultRowDto> result = new LinkedHashMap<>();
if (taskId == null || requestedKeys == null || requestedKeys.isEmpty()) {
return result;
}
Long lastChunkId = null;
while (true) {
LambdaQueryWrapper<TaskChunkEntity> query = new LambdaQueryWrapper<TaskChunkEntity>()
.eq(TaskChunkEntity::getTaskId, taskId)
.eq(TaskChunkEntity::getModuleType, moduleType)
.orderByAsc(TaskChunkEntity::getId)
.last("LIMIT " + RESULT_ROWS_CHUNK_PAGE_SIZE);
if (lastChunkId != null) {
query.gt(TaskChunkEntity::getId, lastChunkId);
}
List<TaskChunkEntity> page = taskChunkMapper.selectList(query);
if (page == null || page.isEmpty()) {
break;
}
// 整页取 chunk 后逐片解载荷:原先每轮 LIMIT 1 只取一行,一个结果文件要把该任务的
// chunk 表逐行翻完,每行一次 SQL + 一次对象读 + 一次整片 JSON 反序列化
for (TaskChunkEntity chunk : page) {
appendRequestedResultRows(result, readChunkRows(chunk).values(), requestedKeys);
}
TaskChunkEntity tail = page.getLast();
lastChunkId = tail == null ? null : tail.getId();
if (lastChunkId == null || page.size() < RESULT_ROWS_CHUNK_PAGE_SIZE) {
break;
}
}
return result;
}
private Set<String> resultLookupKeysForParsedRows(List<AppearancePatentParsedRowVo> rows) {
Set<String> keys = new LinkedHashSet<>();
for (AppearancePatentParsedRowVo row : rows == null ? List.<AppearancePatentParsedRowVo>of() : rows) {
String primary = rowKey(row);
if (!primary.isBlank()) {
keys.add(primary);
}
String legacy = legacyRowKey(row);
if (!legacy.isBlank()) {
keys.add(legacy);
}
}
return keys;
}
private void appendRequestedResultRows(Map<String, AppearancePatentResultRowDto> sink,
Iterable<AppearancePatentResultRowDto> rows,
Set<String> requestedKeys) {
if (rows == null || requestedKeys == null || requestedKeys.isEmpty()) {
return;
}
for (AppearancePatentResultRowDto row : rows) {
if (row == null) {
continue;
}
String primary = rowKey(row);
String legacy = legacyRowKey(row);
String matchedKey = requestedKeys.contains(primary)
? primary : requestedKeys.contains(legacy) ? legacy : "";
if (!matchedKey.isBlank()) {
sink.put(matchedKey, row);
}
}
}
private void sleepBeforeResultRowsRetry(int attempt) {
try {
Thread.sleep(RESULT_ROWS_READ_RETRY_DELAY_MS * attempt);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
public Map<String, AppearancePatentResultRowDto> readChunkRows(TaskChunkEntity chunk) {
Map<String, AppearancePatentResultRowDto> rows = new LinkedHashMap<>();
if (chunk == null || chunk.getPayloadJson() == null || chunk.getPayloadJson().isBlank()) {
return rows;
}
try {
String payloadJson = transientPayloadStorageService.resolvePayload(chunk.getPayloadJson(), "read appearance patent chunk failed");
JsonNode array = objectMapper.readTree(payloadJson);
if (!array.isArray()) {
return rows;
}
for (JsonNode node : array) {
AppearancePatentResultRowDto row = objectMapper.treeToValue(node, AppearancePatentResultRowDto.class);
rows.put(rowKey(row), row);
}
} catch (Exception ex) {
log.warn("[appearance-patent] read chunk payload failed taskId={} chunk={} err={}",
chunk.getTaskId(), chunk.getChunkIndex(), ex.getMessage());
if (isPayloadMissing(ex)) {
// payload 对象已不在(被清理或从未写入):重试多少次都读不回来。继续抛会让
// ASSEMBLE_RESULT job 的终态回调每轮重跑兜底组装 → 再读同一个缺失对象 → 无限循环
// (线上任务 28459 每 10~30 秒重试一次)。跳过该分片,让任务按已有分片出部分结果,
// 与品牌/相似ASIN「失败也产出可下载的部分结果」同一口径。
log.warn("[appearance-patent] chunk payload 已不存在,跳过该分片(任务按已有分片出结果)"
+ " taskId={} chunk={}", chunk.getTaskId(), chunk.getChunkIndex());
return rows;
}
throw new BusinessException("读取外观专利结果分片失败,分片="
+ chunk.getChunkIndex() + ": " + ex.getMessage(), ex);
}
return rows;
}
/** payload 对象已不存在(RustFS 返回 NoSuchKey:message 为 "The specified key does not exist.")。
* 只有这种"重试也没用"的缺失才允许跳过;网络类失败仍照旧抛出以便重试。 */
private static boolean isPayloadMissing(Throwable error) {
Throwable cursor = error;
while (cursor != null) {
String message = cursor.getMessage();
if (message != null && message.contains("does not exist")) {
return true;
}
cursor = cursor.getCause();
}
return false;
}
public String rowKey(AppearancePatentParsedRowVo row) {
if (row == null) {
return "";
}
String rowToken = normalizer.apply(row.getRowToken());
if (!rowToken.isBlank()) {
return rowToken;
}
return legacyRowKey(row);
}
public String rowKey(AppearancePatentResultRowDto row) {
if (row == null) {
return "";
}
String rowToken = normalizer.apply(row.getRowToken());
if (!rowToken.isBlank()) {
return rowToken;
}
return legacyRowKey(row);
}
public AppearancePatentResultRowDto findResultRow(AppearancePatentParsedRowVo parsedRow,
Map<String, AppearancePatentResultRowDto> resultMap) {
if (parsedRow == null || resultMap == null || resultMap.isEmpty()) {
return null;
}
AppearancePatentResultRowDto resultRow = resultMap.get(rowKey(parsedRow));
if (resultRow != null) {
return resultRow;
}
String legacyKey = legacyRowKey(parsedRow);
if (legacyKey.isBlank()) {
return null;
}
return resultMap.get(legacyKey);
}
private String legacyRowKey(AppearancePatentParsedRowVo row) {
if (row == null) {
return "";
}
return rowKey(row.getDisplayId(), row.getAsin(), row.getCountry());
}
private String legacyRowKey(AppearancePatentResultRowDto row) {
if (row == null) {
return "";
}
return rowKey(row.getId(), row.getAsin(), row.getCountry());
}
private String rowKey(String id, String asin, String country) {
return normalizer.apply(id) + "::" + normalizer.apply(asin).toUpperCase(Locale.ROOT) + "::" + normalizer.apply(country);
}
}
@@ -1,5 +1,6 @@
package com.nanri.aiimage.modules.appearancepatent.service.support;
import com.nanri.aiimage.common.util.BrandLabel;
import com.nanri.aiimage.modules.appearancepatent.model.dto.AppearancePatentResultRowDto;
import com.nanri.aiimage.modules.appearancepatent.model.vo.AppearancePatentParsedRowVo;
import org.apache.poi.ss.usermodel.Cell;
@@ -231,10 +232,17 @@ public final class AppearancePatentSheetBuilder {
return "";
}
/**
* 品牌列的唯一取值出口:回传行优先、退回用户上传表的原始列,两条来源都在这里过一遍
* {@link BrandLabel}。清洗必须落在这处而不是 cell 那一行——亚马逊把卖家名渲染成
* "Brand: XXX",用户复制进 Excel 或客户端原样回传就带着标签前缀,带着它去查品牌库会被
* 当 Solr 字段限定符打成上游 500。回传值只剩标签("Brand:")时按"这一行没带品牌"处理,
* 继续回退到源表的品牌列,而不是把一个空标签洗出来的空串当成有效值写进格子。
*/
public static String resolveBrand(AppearancePatentResultRowDto resultRow, AppearancePatentParsedRowVo parsedRow) {
String pythonBrand = resultRow == null ? "" : resultRow.getBrand();
String pythonBrand = resultRow == null ? "" : BrandLabel.strip(resultRow.getBrand());
if (pythonBrand != null && !pythonBrand.isBlank()) {
return pythonBrand.trim();
return pythonBrand;
}
if (parsedRow == null || parsedRow.getValues() == null) {
return "";
@@ -242,7 +250,7 @@ public final class AppearancePatentSheetBuilder {
for (Map.Entry<String, String> entry : parsedRow.getValues().entrySet()) {
String header = entry.getKey() == null ? "" : entry.getKey().trim().toLowerCase(Locale.ROOT);
if (header.contains("品牌") || header.contains("brand")) {
return entry.getValue() == null ? "" : entry.getValue();
return firstNonBlank(BrandLabel.strip(entry.getValue()), "");
}
}
return "";
@@ -1,6 +1,7 @@
package com.nanri.aiimage.modules.asincache.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.common.util.BrandLabel;
import com.nanri.aiimage.modules.asincache.mapper.AsinResultCacheMapper;
import com.nanri.aiimage.modules.asincache.model.dto.AsinCacheWriteRowDto;
import com.nanri.aiimage.modules.asincache.model.entity.AsinResultCacheEntity;
@@ -260,7 +261,9 @@ public class AsinResultCacheService {
entity.setAsin(asin);
entity.setAvailability(availability);
entity.setPrice(clip(row.getPrice(), MAX_PRICE_LENGTH));
entity.setBrand(clip(row.getBrand(), MAX_BRAND_LENGTH));
// 缓存行来自客户端回传的采集结果,品牌那格常常是详情页署名行原样("Brand: XXX"):
// 这一列洗不洗决定了后面多少个任务从缓存里读到脏值,落库前剥一次比在每个下游各剥一次可靠
entity.setBrand(clip(BrandLabel.strip(row.getBrand()), MAX_BRAND_LENGTH));
entity.setDeliveryMethod(clip(row.getDeliveryMethod(), MAX_DELIVERY_LENGTH));
entity.setSellerName(clip(row.getSellerName(), MAX_SELLER_NAME_LENGTH));
entity.setSellerId(clip(row.getSellerId(), MAX_SELLER_ID_LENGTH));
@@ -2,6 +2,8 @@ package com.nanri.aiimage.modules.brand.client;
import com.fasterxml.jackson.annotation.JsonAlias;
import com.nanri.aiimage.config.BrandCheckProperties;
import com.nanri.aiimage.modules.usersecret.service.UserApiSecretService;
import com.nanri.aiimage.modules.usersecret.support.UserSecretModule;
import jakarta.annotation.PreDestroy;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
@@ -35,14 +37,20 @@ public class BrandCheckClient {
/** 品牌检查并发度:避免一次批量检查把第三方服务打满。 */
private static final int BRAND_CHECK_CONCURRENCY = 3;
/** 用户没配代理时交回的原因文案;采集侧与补测队列都按它把行判查询失败。 */
public static final String NO_PROXY_REASON = "用户未配置代理";
private final BrandCheckProperties properties;
private final com.nanri.aiimage.metrics.ExternalCallMetricsRecorder externalCallMetrics;
private final UserApiSecretService userApiSecretService;
private volatile RestClient sharedRestClient;
public BrandCheckClient(BrandCheckProperties properties,
com.nanri.aiimage.metrics.ExternalCallMetricsRecorder externalCallMetrics) {
com.nanri.aiimage.metrics.ExternalCallMetricsRecorder externalCallMetrics,
UserApiSecretService userApiSecretService) {
this.properties = properties;
this.externalCallMetrics = externalCallMetrics;
this.userApiSecretService = userApiSecretService;
}
// 有界队列 + CallerRuns:大批量(几千品牌)检查时队列洪峰不无界堆内存,
@@ -68,18 +76,32 @@ public class BrandCheckClient {
};
}
public BrandCheckResponse check(String brand) {
return check(brand, properties.getDefaultStrategy());
/**
* 单品牌查一次上游。
*
* <p>{@code userId} 决定这次烧谁的代理:16890 不再自带平台 key(那把 key 的套餐
* 2026-10-19 过期,全体用户的品牌检测一起静默失效,而用户在后台只看到「没采到数据」)。
* 用户没配代理时**一次上游都不打**,当场按查询失败交回原因——重试救不回缺代理,
* 十条阶梯只会把一个人的配置问题摊成上游十分钟的重试流量。
*/
public BrandCheckResponse check(String brand, String strategy, Long userId) {
return postCheck(brand, strategy, userId, proxyUrlFor(userId));
}
public BrandCheckResponse check(String brand, String strategy) {
private BrandCheckResponse postCheck(String brand, String strategy, Long userId, String proxyUrl) {
String normalizedBrand = normalize(brand);
if (normalizedBrand.isBlank()) {
return BrandCheckResponse.empty();
}
if (proxyUrl.isBlank()) {
log.warn("[brand-check] {} userId={}(不打上游)", NO_PROXY_REASON, userId);
return BrandCheckResponse.noProxy(normalizedBrand);
}
Map<String, Object> body = new LinkedHashMap<>();
body.put("brand", normalizedBrand);
body.put("strategy", normalize(strategy).isBlank() ? "Terms" : normalize(strategy));
body.put("user_id", userId);
body.put("proxy_url", proxyUrl);
return restClient().post()
.uri(joinUrl(properties.getBaseUrl(), properties.getPath()))
.headers(headers -> {
@@ -94,8 +116,19 @@ public class BrandCheckClient {
.body(BrandCheckResponse.class);
}
public BrandCheckBatchResult checkAll(List<String> brands, String strategy) {
return checkAll(brands, strategy, properties.getTotalTimeoutMillis());
/**
* 该用户的代理提取链接(module=proxy 明文,支持 {@code url;mode;url;mode} 多 key 写法)。
* findPlainValue 自身不抛:未配置/解密失败一律空串。
*/
private String proxyUrlFor(Long userId) {
if (userId == null || userId <= 0L || userApiSecretService == null) {
return "";
}
return normalize(userApiSecretService.findPlainValue(userId, UserSecretModule.PROXY.key()));
}
public BrandCheckBatchResult checkAll(List<String> brands, String strategy, Long userId) {
return checkAll(brands, strategy, properties.getTotalTimeoutMillis(), userId);
}
/**
@@ -106,15 +139,26 @@ public class BrandCheckClient {
* 是给后台批量任务(外观合批、品牌补测调度)的预算,同步等响应的桌面客户端不该替它扛
* ——上游卡死时按批各领一个 90 秒,一个 chunk 十几批能叠到十几分钟。
*/
public BrandCheckBatchResult checkAll(List<String> brands, String strategy, long budgetMillis) {
public BrandCheckBatchResult checkAll(List<String> brands, String strategy,
long budgetMillis, Long userId) {
List<String> distinctBrands = distinctNonBlank(brands);
List<Object> failedData = new ArrayList<>();
List<Object> queryFailedData = new ArrayList<>();
for (BrandCheckOutcome outcome : checkWords(distinctBrands, strategy, deadlineNanos(budgetMillis)).values()) {
Map<String, BrandCheckOutcome> outcomes =
checkWords(distinctBrands, strategy, deadlineNanos(budgetMillis), userId);
List<String> reasons = new ArrayList<>();
for (String brand : distinctBrands) {
BrandCheckOutcome outcome = outcomes.get(brand);
if (outcome == null) {
continue;
}
failedData.addAll(outcome.failedData());
queryFailedData.addAll(outcome.queryFailedData());
if (!outcome.reason().isBlank() && !reasons.contains(outcome.reason())) {
reasons.add(outcome.reason());
}
}
return new BrandCheckBatchResult(distinctBrands, failedData, queryFailedData);
return new BrandCheckBatchResult(distinctBrands, failedData, queryFailedData, String.join(";", reasons));
}
/**
@@ -126,7 +170,7 @@ public class BrandCheckClient {
* 与货源侧 CollectDataBrandBatchFilter 已上线的口径一致。
* 返回值与入参同序同长,空标题行返回空词集合(调用方据此回退成标题原文)。
*/
public List<BrandCheckBatchResult> checkTitleTexts(List<String> titles, String strategy) {
public List<BrandCheckBatchResult> checkTitleTexts(List<String> titles, String strategy, Long userId) {
if (titles == null || titles.isEmpty()) {
return List.of();
}
@@ -138,19 +182,24 @@ public class BrandCheckClient {
distinctWords.addAll(words);
}
Map<String, BrandCheckOutcome> outcomes = checkWords(
new ArrayList<>(distinctWords), strategy, deadlineNanos(properties.getTotalTimeoutMillis()));
new ArrayList<>(distinctWords), strategy,
deadlineNanos(properties.getTotalTimeoutMillis()), userId);
List<BrandCheckBatchResult> results = new ArrayList<>(titles.size());
for (List<String> words : wordsByTitle) {
List<Object> failedData = new ArrayList<>();
List<Object> queryFailedData = new ArrayList<>();
List<String> reasons = new ArrayList<>();
for (String word : words) {
BrandCheckOutcome outcome = outcomes.get(word);
if (outcome != null) {
failedData.addAll(outcome.failedData());
queryFailedData.addAll(outcome.queryFailedData());
if (!outcome.reason().isBlank() && !reasons.contains(outcome.reason())) {
reasons.add(outcome.reason());
}
}
}
results.add(new BrandCheckBatchResult(words, failedData, queryFailedData));
results.add(new BrandCheckBatchResult(words, failedData, queryFailedData, String.join(";", reasons)));
}
return results;
}
@@ -159,17 +208,29 @@ public class BrandCheckClient {
* 并发查一批**已去重**的词,整批共用调用方给定的截止时刻。
* 键顺序即入参顺序,checkAll 的并集顺序因此与改动前一致。
*/
private Map<String, BrandCheckOutcome> checkWords(List<String> brands, String strategy, long deadlineNanos) {
private Map<String, BrandCheckOutcome> checkWords(List<String> brands, String strategy,
long deadlineNanos, Long userId) {
// 整批共用一个耗时预算:上游 16890 卡死时,单品牌 10 次重试曾把一次分片回传拖到
// 103.5 秒(taskId 28599),客户端重试预算耗尽后中止了整个采集。预算用尽即停止重试。
Map<String, BrandCheckOutcome> outcomes = new LinkedHashMap<>();
String proxyUrl = proxyUrlFor(userId);
if (proxyUrl.isBlank()) {
// 缺代理整批一个请求都不发:这是配置问题,十条重试阶梯在这里只会白烧,
// 而 16890 拿不到调用方的代理就只能裸打 WIPO——裸 IP 必被拒(2026-10-19 现网)。
log.warn("[brand-check] {},整批不打上游 userId={} 品牌数={}", NO_PROXY_REASON, userId, brands.size());
for (String brand : brands) {
outcomes.put(brand, new BrandCheckOutcome(List.of(), List.of(brand), NO_PROXY_REASON));
}
return outcomes;
}
List<CompletableFuture<BrandCheckOutcome>> futures = new ArrayList<>(brands.size());
// 一次批量一份判定:本批里只要有一个品牌跑满阶梯仍被判查询失败,其余品牌就不再
// 各自烧完整条重试阶梯(见 checkOneBrand 的短路分支)。
AtomicBoolean upstreamRejecting = new AtomicBoolean(false);
for (String brand : brands) {
futures.add(CompletableFuture.supplyAsync(
() -> checkOneBrand(brand, strategy, deadlineNanos, upstreamRejecting), checkExecutor));
() -> checkOneBrand(brand, strategy, deadlineNanos, upstreamRejecting, proxyUrl, userId),
checkExecutor));
}
for (int index = 0; index < brands.size(); index++) {
outcomes.put(brands.get(index), awaitOutcome(futures.get(index)));
@@ -183,10 +244,11 @@ public class BrandCheckClient {
}
private BrandCheckOutcome checkOneBrand(String brand, String strategy, long deadlineNanos,
AtomicBoolean upstreamRejecting) {
AtomicBoolean upstreamRejecting, String proxyUrl, Long userId) {
int attempts = Math.max(1, properties.getRetryTimes());
BrandCheckResponse response = null;
Exception lastFailure = null;
String reason = "";
// 只有「把整条重试阶梯走完」才算拿到"上游在确定性拒绝"的证据。
// 被预算或短路掐断的轮次不是证据,拿它去短路同批其余品牌会把偶发抖动放大成整批放弃。
boolean ladderCompleted = true;
@@ -212,7 +274,7 @@ public class BrandCheckClient {
break;
}
try {
response = check(brand, strategy);
response = postCheck(brand, strategy, userId, proxyUrl);
} catch (Exception ex) {
lastFailure = ex;
response = null;
@@ -226,7 +288,20 @@ public class BrandCheckClient {
}
if (response != null && nullToEmpty(response.getQueryFaildData()).isEmpty()) {
// 本次查询完成且无失败项:命中侵权(faild_data)属有效结论,不重试。
return new BrandCheckOutcome(nullToEmpty(response.getFaildData()), List.of());
return new BrandCheckOutcome(nullToEmpty(response.getFaildData()), List.of(), "");
}
// 走到这里 response 必非 null:抛异常的那一轮在 catch 里已经 continue 掉了。
if (response.getReason() != null && !response.getReason().isBlank()) {
reason = response.getReason().trim();
}
if (response != null && !response.isRetryable()) {
// 上游当场判定"重试也不会变好"(供应商拒付、套餐过期、这类结论是确定的),
// 阶梯到此为止并把同批一起短路——旧版这里要跑满 10 轮、约 45~65 秒才知道
// 同一个坏消息,而它烧掉的正是后面那些品牌的机会。
upstreamRejecting.set(true);
ladderCompleted = false;
log.warn("[brand-check] 上游判定确定性拒绝,停止重试 brand={} reason={}", brand, reason);
break;
}
if (attempt < attempts) {
long retryDelayMillis = retryDelayMillis(attempt);
@@ -242,11 +317,11 @@ public class BrandCheckClient {
&& !nullToEmpty(response.getQueryFaildData()).isEmpty()) {
upstreamRejecting.set(true);
}
log.warn("[brand-check] 重试耗尽判定查询失败 brand={} attempts={} lastErr={}",
log.warn("[brand-check] 重试耗尽判定查询失败 brand={} attempts={} lastErr={} reason={}",
brand, attempts,
lastFailure == null ? "query_faild_data 持续非空" : lastFailure.getMessage());
lastFailure == null ? "query_faild_data 持续非空" : lastFailure.getMessage(), reason);
return new BrandCheckOutcome(List.of(),
response == null ? List.of(brand) : nullToEmpty(response.getQueryFaildData()));
response == null ? List.of(brand) : nullToEmpty(response.getQueryFaildData()), reason);
}
/**
@@ -278,19 +353,22 @@ public class BrandCheckClient {
} catch (CompletionException ex) {
log.warn("[brand-check] unexpected batch failure err={}",
ex.getCause() == null ? ex.getMessage() : String.valueOf(ex.getCause().getMessage()));
return new BrandCheckOutcome(List.of(), List.of());
return new BrandCheckOutcome(List.of(), List.of(), "");
}
}
private record BrandCheckOutcome(List<Object> failedData, List<Object> queryFailedData) {
/**
* 单个品牌的结论。
*
* @param reason 查询失败时的可展示原因(供应商拒付 / 用户未配置代理 / 上游拒绝代理出口);
* 结论正常时为空串。它存在的意义是让采集侧与补测队列能把「为什么查不了」
* 写进任务,而不是只留一句 {@code query_faild_data 持续非空}。
*/
private record BrandCheckOutcome(List<Object> failedData, List<Object> queryFailedData, String reason) {
}
public BrandCheckBatchResult checkTitleText(String titleText) {
return checkTitleText(titleText, properties.getDefaultStrategy());
}
public BrandCheckBatchResult checkTitleText(String titleText, String strategy) {
return checkAll(splitTitleText(titleText), strategy);
public BrandCheckBatchResult checkTitleText(String titleText, String strategy, Long userId) {
return checkAll(splitTitleText(titleText), strategy, userId);
}
public List<String> splitTitleText(String titleText) {
@@ -392,15 +470,35 @@ public class BrandCheckClient {
@JsonAlias({"query_faild_data", "query_failed_data"})
private List<Object> queryFaildData = new ArrayList<>();
/** 查询失败的可展示原因;上游旧版本不回传该字段时为空串,行为与改造前一致。 */
private String reason = "";
/**
* false=上游判定这个结论重也不会变好(供应商拒付、用户没配代理),
* 重试阶梯应当当场停下。缺省 true 是刻意的:旧版 16890 不带这个字段时,
* 不能把"没带"读成"别重试"。
*/
private boolean retryable = true;
private static BrandCheckResponse empty() {
return new BrandCheckResponse();
}
/** 用户没配代理:Java 侧本地就能定论,一次上游都不该打。 */
private static BrandCheckResponse noProxy(String brand) {
BrandCheckResponse response = new BrandCheckResponse();
response.setQueryFaildData(new ArrayList<>(List.of(brand)));
response.setReason(NO_PROXY_REASON);
response.setRetryable(false);
return response;
}
}
public record BrandCheckBatchResult(
List<String> brands,
List<Object> faildData,
List<Object> queryFaildData
List<Object> queryFaildData,
String reason
) {
public boolean hasFailedData() {
return faildData != null && !faildData.isEmpty();
@@ -409,5 +507,10 @@ public class BrandCheckClient {
public boolean hasQueryFailedData() {
return queryFaildData != null && !queryFaildData.isEmpty();
}
/** 查询失败原因(多个用;拼接);结论正常时为空串。 */
public String reason() {
return reason == null ? "" : reason;
}
}
}
@@ -11,6 +11,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.common.service.DistributedJobLockService;
import com.nanri.aiimage.common.util.BrandLabel;
import com.nanri.aiimage.common.util.ExcelStreamReader;
import com.nanri.aiimage.config.BrandProgressProperties;
import com.nanri.aiimage.config.HttpClientPool;
@@ -770,7 +771,10 @@ public class BrandTaskService {
File sourceLocalFile = resolveSourceFile(sourceFile);
String originalFilename = resolveOriginalFilename(sourceFile, sourceLocalFile);
File outputFile = buildNamedOutputFile(outputDir, buildResultFilename(originalFilename));
writeBrandWorkbook(outputFile, strategy, cachedFile, aggregate, undetectedBrands);
// 出表整读源文件展开全量行:缓存 rows 是按品牌去重的查询集(执行方靠它逐品牌只查一次),
// 同品牌不同 ASIN 是不同商品,结果文件删不得。
List<Map<String, Object>> outputRows = parseBrandFile(sourceLocalFile, false).rows();
writeBrandWorkbook(outputFile, strategy, cachedFile, aggregate, undetectedBrands, outputRows);
outputEntries.add(new OutputEntry(sourceLocalFile, originalFilename, outputFile, originalFilename));
}
if (outputEntries.isEmpty()) {
@@ -813,7 +817,7 @@ public class BrandTaskService {
handled.addAll(normalizeBrandSet(aggregate.getQueryFailedBrands()));
LinkedHashSet<String> undetected = new LinkedHashSet<>();
for (Map<String, Object> rowData : sourceRows) {
String brand = normalizeCellText(Objects.toString(rowData.getOrDefault("品牌", ""), ""));
String brand = BrandLabel.strip(normalizeCellText(Objects.toString(rowData.getOrDefault("品牌", ""), "")));
if (!brand.isBlank() && !handled.contains(brand)) {
undetected.add(brand);
}
@@ -1033,7 +1037,16 @@ public class BrandTaskService {
return blankToDefault(sourceFile.getOriginalFilename(), inputFile.getName());
}
private ParsedBrandFile parseBrandFile(File inputFile) {
ParsedBrandFile parseBrandFile(File inputFile) {
return parseBrandFile(inputFile, true);
}
/**
* @param dedupeRowsByBrand 真=回传执行方的 payload 形态:每品牌只留首行,保证逐品牌只查一次
* (执行方从 rows 提品牌清单,放开会按行重烧按次计费的代理);
* 假=出表形态:同品牌不同 ASIN 是不同商品,结果文件必须每行都在。
*/
ParsedBrandFile parseBrandFile(File inputFile, boolean dedupeRowsByBrand) {
// 2026-09 全维度审查 C5:改逐行流式解析(ExcelStreamReader → EasyExcel SAX)。
// 此前 WorkbookFactory.create 把整表读成 DOM,品牌源文件(几十万行)会整表驻留堆内存。
// 解析结果(columns/rows/uniqueBrands/行号)与错误文案不变,行号沿用 sheet 绝对 0 基行号 +1。
@@ -1041,7 +1054,7 @@ public class BrandTaskService {
log.warn("[brand] 源文件不是 Excel(疑似 CSV/文本),拒绝解析 file={}", inputFile.getName());
throw new BusinessException("读取 Excel 失败");
}
BrandFileSheetContext context = new BrandFileSheetContext();
BrandFileSheetContext context = new BrandFileSheetContext(dedupeRowsByBrand);
try {
ExcelStreamReader.readFirstSheet(inputFile, context);
} catch (BusinessException ex) {
@@ -1072,15 +1085,20 @@ public class BrandTaskService {
}
}
/** 品牌源文件流式解析上下文:表头解析 + 按品牌去重累积结果行(内存不随整表 DOM 放大)。 */
/** 品牌源文件流式解析上下文:表头解析 + 结果行累积(内存不随整表 DOM 放大)。 */
private final class BrandFileSheetContext implements ExcelStreamReader.SheetRowHandler {
private final boolean dedupeRowsByBrand;
private final List<Map<String, Object>> rows = new ArrayList<>();
private final Set<String> uniqueBrands = new LinkedHashSet<>();
private List<String> columns;
private Map<String, Integer> headerIndexes;
private String sheetName = "";
BrandFileSheetContext(boolean dedupeRowsByBrand) {
this.dedupeRowsByBrand = dedupeRowsByBrand;
}
@Override
public void onHeader(String sheetName, Integer sheetNo, Map<Integer, String> headerMap) {
this.sheetName = sheetName == null ? "" : sheetName;
@@ -1130,13 +1148,22 @@ public class BrandTaskService {
String value = index == null ? "" : normalizeCellText(rowMap.get(index));
rowData.put(column, value);
}
String brand = normalizeCellText(Objects.toString(rowData.getOrDefault("品牌", ""), ""));
String brand = BrandLabel.strip(normalizeCellText(Objects.toString(rowData.getOrDefault("品牌", ""), "")));
if (rowData.containsKey("品牌")) {
// 品牌列在解析落 row map 这一处就洗,而不是等出件那一格:查询集 uniqueBrands、
// 与执行方回传值的匹配、结果文件里那一格必须拿到同一个字符串。只在写出端剥会让
// 比对两边分家——判为"不符合"的行剔不掉,用户把没通过的行当成已通过上架。
// 纯标签值("Brand:")洗完即空,与"这行没填品牌"走同一条路径,不再送给上游
// 当 Solr 字段限定符(2026-10-08 单日 19,247 次 500 的起点就是这个)。
rowData.put("品牌", brand);
}
if (brand.isBlank()) {
rowData.put("__rowIndex", rowIndex + 1);
rows.add(rowData);
return;
}
if (uniqueBrands.add(brand)) {
boolean firstSeen = uniqueBrands.add(brand);
if (firstSeen || !dedupeRowsByBrand) {
rowData.put("__rowIndex", rowIndex + 1);
rows.add(rowData);
}
@@ -1188,11 +1215,12 @@ public class BrandTaskService {
.replaceAll("\\s+", " ");
}
private void writeBrandWorkbook(File outputFile,
String strategy,
BrandParsedFileCacheDto cachedFile,
BrandFileAggregateCacheDto resultFile,
List<String> undetectedBrands) throws IOException {
void writeBrandWorkbook(File outputFile,
String strategy,
BrandParsedFileCacheDto cachedFile,
BrandFileAggregateCacheDto resultFile,
List<String> undetectedBrands,
List<Map<String, Object>> outputRows) throws IOException {
String actualStrategy = normalizeStrategy(strategy);
SXSSFWorkbook workbook = new SXSSFWorkbook(200);
workbook.setCompressTempFiles(true);
@@ -1210,10 +1238,10 @@ public class BrandTaskService {
// 避免用户把「没查过」的行误当成「已通过检测」上架
Set<String> undetectedBrandSet = normalizeBrandSet(undetectedBrands);
List<Map<String, Object>> undetectedRows = new ArrayList<>();
List<Map<String, Object>> sourceRows = cachedFile.getRows() == null ? List.of() : cachedFile.getRows();
List<Map<String, Object>> sourceRows = outputRows == null ? List.of() : outputRows;
int writeRowIndex = 1;
for (Map<String, Object> rowData : sourceRows) {
String brand = normalizeCellText(Objects.toString(rowData.getOrDefault("品牌", ""), ""));
String brand = BrandLabel.strip(normalizeCellText(Objects.toString(rowData.getOrDefault("品牌", ""), "")));
if (!brand.isBlank() && invalidBrandSet.contains(brand)) {
continue;
}
@@ -1254,7 +1282,7 @@ public class BrandTaskService {
for (int i = 0; i < invalidBrands.size(); i++) {
var row = invalidSheet.createRow(i + 1);
BrandInvalidBrandDto item = invalidBrands.get(i);
row.createCell(0).setCellValue(blankToDefault(item.getBrand(), ""));
row.createCell(0).setCellValue(BrandLabel.strip(blankToDefault(item.getBrand(), "")));
row.createCell(1).setCellValue(blankToDefault(item.getCountry(), ""));
row.createCell(2).setCellValue(blankToDefault(item.getStatus(), ""));
}
@@ -1267,7 +1295,9 @@ public class BrandTaskService {
String nowText = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yy-MM-dd HH:mm:ss"));
for (int i = 0; i < queryFailedBrands.size(); i++) {
var row = queryFailedSheet.createRow(i + 1);
row.createCell(0).setCellValue(blankToDefault(queryFailedBrands.get(i), ""));
// 这张表本身就是"被打回的品牌"清单,用户改完往往直接再传一次:
// 这一格不剥前缀,下一次上传就把同一个脏值原样送回查询链路,清洗脚本的账也作废。
row.createCell(0).setCellValue(BrandLabel.strip(blankToDefault(queryFailedBrands.get(i), "")));
row.createCell(1).setCellValue(nowText);
}
@@ -1313,7 +1343,9 @@ public class BrandTaskService {
if (invalidBrand == null) {
continue;
}
String normalized = normalizeCellText(invalidBrand.getBrand());
// 执行方刻意回传原值(失败清单要能对得上用户表里那一行),所以匹配键这一侧必须
// 与服务端解析后的品牌取同一个口径:两边都过 BrandLabel,legacy 脏值回传照样命中。
String normalized = BrandLabel.strip(normalizeCellText(invalidBrand.getBrand()));
if (!normalized.isBlank()) {
result.add(normalized);
}
@@ -1327,7 +1359,7 @@ public class BrandTaskService {
return result;
}
for (String brand : brands) {
String normalized = normalizeCellText(brand);
String normalized = BrandLabel.strip(normalizeCellText(brand));
if (!normalized.isBlank()) {
result.add(normalized);
}
@@ -1713,8 +1745,8 @@ public class BrandTaskService {
brandTaskProgressCacheService.markFailed(taskId, message);
}
private record ParsedBrandFile(String sheetName, List<String> columns, List<Map<String, Object>> rows,
List<String> uniqueBrands) {
record ParsedBrandFile(String sheetName, List<String> columns, List<Map<String, Object>> rows,
List<String> uniqueBrands) {
}
private record OutputEntry(File sourceFile, String zipSourceFilename, File resultFile, String zipResultFilename) {
@@ -0,0 +1,91 @@
package com.nanri.aiimage.modules.brand.support;
import com.nanri.aiimage.modules.brand.client.BrandCheckClient;
import java.util.regex.Pattern;
/**
* 把 16890 品牌检测回来的原始原因归成"用户看得懂的那一类",并给出该做的动作。
*
* <p>存在的理由只有一句:2026-10-20 品牌检测改成烧**任务归属用户自己的**代理提取链接后,
* 失败主因从「上游商标库不可用」变成了用户侧套餐问题(现网 12 分钟内 18 条冷却、4 条余额不足),
* 而补测耗尽通知还写着「上游商标库持续不可用」——既冤枉了上游,也让用户照着提示去重跑,
* 重跑当然还是失败。原始原因照旧进 {@code biz_collectdata_brand_recheck.last_error}
* 供后台取证,这里只管对用户说话的那一句。
*/
public final class BrandCheckFailureNotice {
public enum Kind {
/** 没配代理提取链接:不是查不到,是根本没得查,动作最明确。 */
PROXY_NOT_CONFIGURED,
/** 套餐余额不足/过期/未开通:不充值或换链接,重跑多少次都一样。 */
PROXY_PACKAGE_EXHAUSTED,
/** 所有 key 都在拒付冷却窗口里:短时现象,补测轮会自动再来。 */
PROXY_COOLDOWN,
/** 代理出口 IP 被商标库拒绝。 */
PROXY_EGRESS_REJECTED,
/** 提取没返回可用 IP、请求失败、解密失败等本地/链路技术性失败。 */
TECHNICAL,
/** 上游商标库本身不可用,或上游没给原因(含连接层失败)。 */
UPSTREAM
}
/** 供应商拒付类话术(与 16890 侧判拒付用的关键字同一套)。 */
private static final Pattern PACKAGE_EXHAUSTED = Pattern.compile("余额不足|欠费|套餐不存在|套餐已过期|套餐过期|未开通");
private static final Pattern COOLDOWN = Pattern.compile("处于冷却|冷却窗口|冷却");
private static final Pattern EGRESS_REJECTED = Pattern.compile("拒绝代理出口|出口 IP|换 IP 重试");
private static final Pattern TECHNICAL = Pattern.compile(
"查询或解密失败|代理请求失败|未返回可用 IP|提取失败|解密");
private BrandCheckFailureNotice() {
}
/**
* 原始原因 → 类别。空串按「上游」算:Java 自己在连接层失败时拿不到上游的 reason,
* 那种情况下能观测到的事实也只有"没回来"。
*
* <p>拒付判定在冷却之前:一把 key 因余额不足被拒后,随后的整批都写成"处于冷却",
* 但那句是冷却、根因是套餐,两个都命中时取更靠根因的那一类。
*/
public static Kind classify(String rawReason) {
String reason = rawReason == null ? "" : rawReason.trim();
if (reason.isEmpty()) {
return Kind.UPSTREAM;
}
if (BrandCheckClient.NO_PROXY_REASON.equals(reason)) {
return Kind.PROXY_NOT_CONFIGURED;
}
if (PACKAGE_EXHAUSTED.matcher(reason).find()) {
return Kind.PROXY_PACKAGE_EXHAUSTED;
}
if (COOLDOWN.matcher(reason).find()) {
return Kind.PROXY_COOLDOWN;
}
if (EGRESS_REJECTED.matcher(reason).find()) {
return Kind.PROXY_EGRESS_REJECTED;
}
if (TECHNICAL.matcher(reason).find()) {
return Kind.TECHNICAL;
}
return Kind.UPSTREAM;
}
/** 用户可读的那一句:先说发生了什么,再说该做什么。 */
public static String userMessage(Kind kind) {
if (kind == null) {
return "商标库本次未返回结果,系统会在后续补测轮自动重试。";
}
return switch (kind) {
case PROXY_NOT_CONFIGURED -> "这个账号还没配代理提取链接,品牌检测无法发起查询:"
+ "请在「密钥设置」的「代理设置」里补上后重跑这些行。";
case PROXY_PACKAGE_EXHAUSTED -> "你的代理提取套餐余额不足或已过期,"
+ "请在「密钥设置」的「代理设置」里充值或更换提取链接,否则重跑也会同样失败。";
case PROXY_COOLDOWN -> "你的代理提取链接连续被供应商拒绝,短时间内已不再尝试;"
+ "系统会在后续补测轮自动重试,若反复出现请检查「密钥设置」的「代理设置」里的套餐余量。";
case PROXY_EGRESS_REJECTED -> "代理出口 IP 被商标库拒绝,系统会自动换出口并在后续补测轮重试;"
+ "持续如此时请更换「密钥设置」的「代理设置」里的提取链接。";
case TECHNICAL -> "品牌检测本次没取回结果(代理提取或结果解析未成功),系统会在后续补测轮自动重试。";
case UPSTREAM -> "上游商标库暂时不可用,系统会在后续补测轮自动重试。";
};
}
}
@@ -3,6 +3,7 @@ package com.nanri.aiimage.modules.collectdata.service;
import com.nanri.aiimage.common.service.DistributedJobLockService;
import com.nanri.aiimage.config.CollectDataBrandRecheckProperties;
import com.nanri.aiimage.modules.brand.client.BrandCheckClient;
import com.nanri.aiimage.modules.brand.support.BrandCheckFailureNotice;
import com.nanri.aiimage.modules.collectdata.model.entity.CollectDataBrandRecheckEntity;
import com.nanri.aiimage.modules.collectdata.service.CollectDataBrandRecheckInjector.RecheckVerdict;
import com.nanri.aiimage.modules.collectdata.util.CollectDataBrandBatchFilter;
@@ -144,7 +145,7 @@ public class CollectDataBrandRecheckScheduler {
List<String> brands = distinctBrands(entries);
BrandCheckClient.BrandCheckBatchResult check;
try {
check = brandCheckClient.checkAll(brands, "Terms");
check = brandCheckClient.checkAll(brands, "Terms", task.getUserId());
} catch (RuntimeException ex) {
// 整批检查异常(网络/服务级故障):按实测失败计次退避,下轮重试
log.warn("[brand-recheck] 批量品牌检测异常,按失败计次 taskId={} brands={} err={}",
@@ -194,6 +195,10 @@ public class CollectDataBrandRecheckScheduler {
}
int exhaustedThisRound = 0;
// 补测这一轮到底为什么还是查不了:上游给的原因(供应商拒付/用户未配置代理/出口被拒)
// 直接写进条目,收口的条目才读得懂是"查不到"还是"没得查"。上游没给原因时保留旧文案。
String checkReason = check == null ? "" : check.reason();
String stillFailedReason = checkReason.isBlank() ? "query_faild_data 持续非空" : checkReason;
for (CollectDataBrandRecheckEntity entry : cleanEntries) {
recheckService.markInjected(entry);
}
@@ -201,7 +206,7 @@ public class CollectDataBrandRecheckScheduler {
recheckService.markRejected(entry);
}
for (CollectDataBrandRecheckEntity entry : stillFailedEntries) {
if (recheckService.markAttempted(entry, "query_faild_data 持续非空")) {
if (recheckService.markAttempted(entry, stillFailedReason)) {
// updateQuietly 失败时下轮按 PENDING 重放,不算收口
if (CollectDataBrandRecheckEntity.STATUS_EXHAUSTED.equals(entry.getStatus())) {
exhaustedThisRound++;
@@ -216,7 +221,8 @@ public class CollectDataBrandRecheckScheduler {
}
notificationDispatchService.pushRecheckOutcome(task.getUserId(), task.getId(), MODULE_TYPE,
task.getTaskNo(), outcome.acceptedRows(), outcome.rejectedRows(),
stillFailedEntries.size(), exhaustedThisRound);
stillFailedEntries.size(), exhaustedThisRound,
BrandCheckFailureNotice.classify(checkReason));
log.info("[brand-recheck] 任务组完成 taskId={} 品牌={} 净={} 败={} 仍失败={} 收口={} 新增结果行={} 判定无效行={}",
task.getId(), brands.size(), cleanEntries.size(), rejectedEntries.size(),
stillFailedEntries.size(), exhaustedThisRound, outcome.acceptedRows(), outcome.rejectedRows());
@@ -1,5 +1,6 @@
package com.nanri.aiimage.modules.collectdata.service;
import com.nanri.aiimage.common.util.BrandLabel;
import com.nanri.aiimage.common.util.UserMessages;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.util.SxssfWorkbookWriter;
@@ -140,7 +141,9 @@ public class CollectDataExcelAssemblyService {
continue;
}
Row row = sheet.createRow((int) state[0]++);
SxssfWorkbookWriter.setText(row, 0, item.getBrand());
// 出件这一端也要过一遍:干净值不等于干净文件——这份 Excel 是用户的下一份上传物,
// 而改口径之前落库的历史明细 payload 里仍可能带着标签前缀。
SxssfWorkbookWriter.setText(row, 0, BrandLabel.strip(item.getBrand()));
SxssfWorkbookWriter.setText(row, 1, item.getAsin());
SxssfWorkbookWriter.setText(row, 2, item.getPrice());
SxssfWorkbookWriter.setText(row, 3, item.getSellerName());
@@ -9,6 +9,7 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.common.exception.BusinessCodes;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.util.BrandLabel;
import com.nanri.aiimage.common.util.ExcelStreamReader;
import com.nanri.aiimage.modules.asincache.service.AsinResultCacheService;
import com.nanri.aiimage.modules.collectdata.mapper.CollectDataCountryPrefMapper;
@@ -823,9 +824,11 @@ public class CollectDataService extends AbstractFileTaskPipeline<CollectDataResu
// 比对集认任务归属账号那一家:chunk 回传的过滤结果不该受别家导入过什么影响
CollectDataBatchQuery.FilterResult filtered =
collectDataBatchQuery.filter(rowsForFiltering, probe.getUserId());
CollectDataBrandBatchFilter.BrandBatchOutcome brandOutcome = brandBatchFilter.filter(filtered.kept());
log.info("[collect-data] 锁外预处理完成 taskId={} rows={} 去重后={} 品牌检测耗时={}ms",
taskId, rows.size(), filtered.kept().size(), System.currentTimeMillis() - prepareStartAt);
CollectDataBrandBatchFilter.BrandBatchOutcome brandOutcome =
brandBatchFilter.filter(filtered.kept(), probe.getUserId());
log.info("[collect-data] 锁外预处理完成 taskId={} rows={} 去重后={} 品牌检测耗时={}ms 品牌失败原因={}",
taskId, rows.size(), filtered.kept().size(), System.currentTimeMillis() - prepareStartAt,
brandOutcome.reason());
// ASIN 结果缓存旁路写入同样放锁外:这把锁的持有时间是心跳与其他 chunk 的排队预算
// (见上方品牌检测移出的注释),缓存写入再快也不该来挤。缓存是"下次少开一次页"的
@@ -969,7 +972,9 @@ public class CollectDataService extends AbstractFileTaskPipeline<CollectDataResu
continue;
}
CollectDataResultRowVo row = new CollectDataResultRowVo();
row.setBrand(normalize(raw.getBrand()));
// 品牌在前端复制自亚马逊详情页的署名行("Brand: XXX"),客户端原样回传就带着标签前缀:
// 带着它去查品牌库会被当 Solr 字段限定符打成上游 500。剥标签只认 BrandLabel 这一处口径。
row.setBrand(BrandLabel.strip(normalize(raw.getBrand())));
row.setAsin(normalizeAsin(raw.getAsin()));
row.setPrice(normalize(raw.getPrice()));
row.setSellerName(normalize(raw.getSellerName()));
@@ -76,13 +76,17 @@ public class CollectDataBrandBatchFilter {
/**
* 按批次执行品牌检查并分类。null/空输入返回空结果;null 行安全跳过不计数。
*
* @param userId 任务归属用户:品牌检查用的代理是这个用户自己的提取链接
* (16890 不再兜底平台 key),谁的套餐被烧就记在谁头上。
*/
public BrandBatchOutcome filter(List<CollectDataResultRowVo> rows) {
public BrandBatchOutcome filter(List<CollectDataResultRowVo> rows, Long userId) {
List<CollectDataResultRowVo> rejected = new ArrayList<>();
List<CollectDataResultRowVo> queryFailed = new ArrayList<>();
List<CollectDataResultRowVo> accepted = new ArrayList<>();
List<String> reasons = new ArrayList<>();
if (rows == null || rows.isEmpty()) {
return new BrandBatchOutcome(rejected, queryFailed, accepted);
return new BrandBatchOutcome(rejected, queryFailed, accepted, "");
}
long deadlineNanos = chunkBudgetMillis > 0L
? System.nanoTime() + chunkBudgetMillis * 1_000_000L : Long.MAX_VALUE;
@@ -124,9 +128,13 @@ public class CollectDataBrandBatchFilter {
}
Map<String, String> batchVerdicts = new LinkedHashMap<>(cachedVerdicts);
try {
batchVerdicts.putAll(checkAndCache(uncachedBrands, remainingBudgetMillis(deadlineNanos)));
BatchVerdicts checked = checkAndCache(uncachedBrands,
remainingBudgetMillis(deadlineNanos), userId);
batchVerdicts.putAll(checked.verdicts());
addReason(reasons, checked.reason());
} catch (RuntimeException ex) {
log.warn("[collect-data] brand check batch failed, degrade batch to queryFailed err={}", ex.getMessage());
addReason(reasons, "品牌检查批次异常: " + ex.getMessage());
for (CollectDataResultRowVo row : batch) {
if (row != null) {
queryFailed.add(row);
@@ -140,7 +148,14 @@ public class CollectDataBrandBatchFilter {
log.info("[collect-data] 品牌检查预算用尽,剩余批次转入补测队列 预算={}ms 延后行={} 总行={}",
chunkBudgetMillis, budgetCutRows, rows.size());
}
return new BrandBatchOutcome(rejected, queryFailed, accepted);
return new BrandBatchOutcome(rejected, queryFailed, accepted, String.join(";", reasons));
}
/** 原因清单去重累积(同一次任务里同一个坏消息不该在日志里重复三遍)。 */
private static void addReason(List<String> reasons, String reason) {
if (reason != null && !reason.isBlank() && !reasons.contains(reason)) {
reasons.add(reason);
}
}
/** 本批次还能用的毫秒数;0 表示不限制(交给 checkAll 按配置预算走)。 */
@@ -151,9 +166,14 @@ public class CollectDataBrandBatchFilter {
return Math.max(1L, (deadlineNanos - System.nanoTime()) / 1_000_000L);
}
/** 远程检查未缓存品牌并写入缓存;返回新查品牌(小写标准化)→ 判定映射。 */
private Map<String, String> checkAndCache(List<String> uncachedBrands, long budgetMillis) {
BrandCheckClient.BrandCheckBatchResult check = brandCheckClient.checkAll(uncachedBrands, "Terms", budgetMillis);
/** 本批次远程检查的结论与原因(原因=这批为什么查不了,可能为空串)。 */
private record BatchVerdicts(Map<String, String> verdicts, String reason) {
}
/** 远程检查未缓存品牌并写入缓存;返回新查品牌(小写标准化)→ 判定映射与失败原因。 */
private BatchVerdicts checkAndCache(List<String> uncachedBrands, long budgetMillis, Long userId) {
BrandCheckClient.BrandCheckBatchResult check =
brandCheckClient.checkAll(uncachedBrands, "Terms", budgetMillis, userId);
Set<String> failedBrands = normalizeObjectSet(check == null ? null : check.faildData());
Set<String> queryFailedBrands = normalizeObjectSet(check == null ? null : check.queryFaildData());
Map<String, String> verdicts = new LinkedHashMap<>();
@@ -170,7 +190,7 @@ public class CollectDataBrandBatchFilter {
putBounded(normalized, verdict);
verdicts.put(normalized, verdict);
}
return verdicts;
return new BatchVerdicts(verdicts, check == null ? "" : check.reason());
}
private Map<String, String> snapshotVerdicts(List<String> brands) {
@@ -249,10 +269,19 @@ public class CollectDataBrandBatchFilter {
}
}
/** 品牌检查分类结果:三类行互斥,顺序与输入一致。 */
/**
* 品牌检查分类结果:三类行互斥,顺序与输入一致。
*
* @param reason 这批为什么查不了(供应商拒付 / 用户未配置代理 / 批次异常),多个用;拼接;
* 全部有结论时为空串。它存在的意义是让「只看到没采到数据」变成可归因的一句话。
*/
public record BrandBatchOutcome(List<CollectDataResultRowVo> rejected,
List<CollectDataResultRowVo> queryFailed,
List<CollectDataResultRowVo> accepted) {
List<CollectDataResultRowVo> accepted,
String reason) {
public String reason() {
return reason == null ? "" : reason;
}
}
private static List<String> distinctNonBlank(List<String> values) {
@@ -10,6 +10,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.service.CompanyScopeSupport;
import com.nanri.aiimage.common.service.NodeSharedStore;
import com.nanri.aiimage.common.util.BrandLabel;
import com.nanri.aiimage.common.util.ExcelStreamReader;
import com.nanri.aiimage.config.InstanceMetadata;
import com.nanri.aiimage.config.StorageProperties;
@@ -61,6 +62,8 @@ public class DedupeRunService {
private static final String HEADER_SPLIT_MARKER = "idASIN国家状态价格变体数量";
private static final String HEADER_STOP_COLUMN = "缩略图地址8";
private static final List<String> EXPORT_COLUMN_PRIORITY = List.of("id", "ASIN", "国家", "价格", "品牌");
/** 去重源文件的列集由用户勾选,品牌列只能按表头认出来,其余列一律原文透传。 */
private static final String BRAND_COLUMN_HEADER = "品牌";
/** 同时处理的文件数上限,避免多文件并行时打满内存与 OSS 上传带宽 */
private static final int MAX_PARALLEL_FILES = 4;
/** 单用户同时运行中的去重任务数上限 */
@@ -856,7 +859,10 @@ public class DedupeRunService {
List<String> selectedColumns, Integer asinColumnIndex) {
List<String> selectedValues = new ArrayList<>(selectedColumns.size());
for (String selectedColumn : selectedColumns) {
selectedValues.add(normalizeCellText(cellText(rowMap, headerIndex.get(selectedColumn))));
String value = normalizeCellText(cellText(rowMap, headerIndex.get(selectedColumn)));
// 品牌列的值可能是用户从亚马逊详情页复制来的署名("Brand: XXX"):在这里剥一次,
// 下方出件写 cell 用的就是同一个字符串,比对与交付不会拿到两个版本
selectedValues.add(BRAND_COLUMN_HEADER.equals(selectedColumn) ? BrandLabel.strip(value) : value);
}
if (asinColumnIndex == null) {
asinColumnIndex = headerIndex.get("ASIN");
@@ -2,6 +2,7 @@ package com.nanri.aiimage.modules.invalidasin.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.util.BrandLabel;
import com.nanri.aiimage.modules.invalidasin.mapper.InvalidAsinDataMapper;
import com.nanri.aiimage.modules.invalidasin.model.dto.InvalidAsinDataCreateRequest;
import com.nanri.aiimage.modules.invalidasin.model.dto.InvalidAsinDataUpdateRequest;
@@ -83,7 +84,11 @@ public class InvalidAsinDataService {
public InvalidAsinDataItemVo create(InvalidAsinDataCreateRequest request, Long operatorId) {
ShopManageGroupEntity group = requireGroup(request.getGroupId(), operatorId);
String dataValue = normalizeRequired(request.getDataValue(), "ASIN 不能为空");
String brand = normalizeRequired(request.getBrand(), "品牌不能为空").toLowerCase(Locale.ROOT);
// 品牌是这张表的匹配键(下游按它判"这个 ASIN 属于被屏蔽品牌"),键值一律先过 BrandLabel:
// 人工把详情页署名行整段粘进来会存成 "brand: nike",而采集侧现在给 "nike",
// 对不上就是屏蔽静默失效——比脏值出件更坏,因为它不报错。先洗再判空,纯标签值必须拒收。
String brand = normalizeRequired(BrandLabel.strip(request.getBrand()), "品牌不能为空")
.toLowerCase(Locale.ROOT);
ensureUnique(dataValue, null);
InvalidAsinDataEntity entity = new InvalidAsinDataEntity();
entity.setDataValue(dataValue);
@@ -101,7 +106,8 @@ public class InvalidAsinDataService {
// 自动导入的行分组由采集侧决定,这一页不替它重归:沿用改造前口径,与角色无关。
ShopManageGroupEntity writeGroup = isManualRecord(entity) ? requireGroup(request.getGroupId(), operatorId) : null;
String dataValue = normalizeRequired(request.getDataValue(), "ASIN 不能为空");
String brand = normalizeRequired(request.getBrand(), "品牌不能为空").toLowerCase(Locale.ROOT);
String brand = normalizeRequired(BrandLabel.strip(request.getBrand()), "品牌不能为空")
.toLowerCase(Locale.ROOT);
ensureUnique(dataValue, id);
entity.setDataValue(dataValue);
entity.setBrand(brand);
@@ -5,6 +5,7 @@ import com.nanri.aiimage.common.module.TaskModuleRegistry;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.common.mapper.AdminUserMapper;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.modules.brand.support.BrandCheckFailureNotice;
import com.nanri.aiimage.modules.permission.support.UserDataScopeSupport;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@@ -143,7 +144,8 @@ public class NotificationDispatchService {
* 同任务同自然日一条(dedupe_key 带日期):补测按轮推进,同一轮内多品牌合并成一条。
*/
public void pushRecheckOutcome(Long userId, Long taskId, String moduleType, String taskNo,
int injectedRows, int rejectedRows, int pendingRows, int exhaustedRows) {
int injectedRows, int rejectedRows, int pendingRows, int exhaustedRows,
BrandCheckFailureNotice.Kind failureKind) {
if (userId == null || userId <= 0 || taskId == null) {
return;
}
@@ -164,8 +166,11 @@ public class NotificationDispatchService {
+ "。结果文件已更新,可在「历史任务」重新下载。";
} else {
title = label + "任务品牌补测未能完成";
// 这句过去一律写成「上游商标库持续不可用」并建议重跑——2026-10-20 起品牌检测烧的是
// 用户自己的代理提取链接,主因变成套餐/冷却,那句既冤枉上游又把用户推向"重跑还是失败"。
// 原始原因照旧留在补测条目 last_error 里给后台取证。
content = "任务 " + displayTaskNo + ":品牌检测连续多轮自动补测仍未成功,共 " + exhaustedRows
+ " 行未能补出结论(上游商标库持续不可用)。建议稍后重新提交采集任务重跑这些 ASIN。";
+ " 行未能补出结论。" + BrandCheckFailureNotice.userMessage(failureKind);
}
String level = fixed && pendingRows <= 0
? NotificationService.LEVEL_INFO : NotificationService.LEVEL_WARNING;
@@ -10,6 +10,7 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.exception.TaskOwnerMismatchException;
import com.nanri.aiimage.common.util.BrandLabel;
import com.nanri.aiimage.config.InstanceMetadata;
import com.nanri.aiimage.modules.file.service.LocalFileStorageService;
import com.nanri.aiimage.modules.file.service.oss.OssStorageService;
@@ -1830,7 +1831,7 @@ public class PublishTaskService extends AbstractFileTaskPipeline<PublishRowDto>
entity.setSourceId(row.getSourceId());
entity.setAsin(row.getAsin());
entity.setCountry(row.getCountry());
entity.setBrand(PublishBrandLabel.strip(row.getBrand()));
entity.setBrand(BrandLabel.strip(row.getBrand()));
entity.setPriceValue(row.getPrice());
entity.setStatusValue(row.getStatus());
entity.setSyncStatus(row.getSyncStatus());
@@ -1,6 +1,7 @@
package com.nanri.aiimage.modules.publish.service;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.util.BrandLabel;
import com.nanri.aiimage.common.util.ExcelStreamReader;
import com.nanri.aiimage.common.util.SxssfWorkbookWriter;
import com.nanri.aiimage.modules.publish.model.dto.PublishRowDto;
@@ -169,7 +170,7 @@ public class PublishWorkbookService {
row.setSourceId(values.get(0));
row.setAsin(values.get(1));
row.setCountry(values.get(2));
row.setBrand(PublishBrandLabel.strip(values.get(3)));
row.setBrand(BrandLabel.strip(values.get(3)));
row.setPrice(values.get(4));
return row;
}
@@ -194,7 +195,7 @@ public class PublishWorkbookService {
setText(row, 0, value.getSourceId());
setText(row, 1, value.getAsin());
setText(row, 2, publishCountry);
setText(row, 3, value.getBrand());
setText(row, 3, BrandLabel.strip(value.getBrand()));
setPrice(row, 4, value.getPrice());
setText(row, 5, value.getStatus());
setText(row, 6, value.getSyncStatus());
@@ -2,6 +2,7 @@ package com.nanri.aiimage.modules.shopdatacrawl.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.nanri.aiimage.common.util.BrandLabel;
import com.nanri.aiimage.modules.shopdatacrawl.mapper.ShopDataCrawlItemMapper;
import com.nanri.aiimage.modules.shopdatacrawl.model.dto.ShopDataCrawlCountryResultDto;
import com.nanri.aiimage.modules.shopdatacrawl.model.dto.ShopDataCrawlRowDto;
@@ -104,7 +105,9 @@ public class ShopDataCrawlItemStoreService {
entity.setBusinessDate(businessDate);
entity.setCountry(country);
entity.setAsin(item.getAsin().trim());
entity.setBrand(trimToNull(item.getBrand()));
// 明细表这一列是撞款扫描与台账出件唯一的品牌来源,而存量迁移的快照 JSON 不经 copyRow:
// 标签前缀必须在进表这一端剥掉,否则脏值每扫一次就复活一次
entity.setBrand(trimToNull(BrandLabel.strip(item.getBrand())));
entity.setPrice(trimToNull(item.getPrice()));
entity.setItemDate(trimToNull(item.getDate()));
entity.setUnitsSold(trimToNull(item.getUnitsSold()));
@@ -1,5 +1,6 @@
package com.nanri.aiimage.modules.shopdatacrawl.service.support;
import com.nanri.aiimage.common.util.BrandLabel;
import com.nanri.aiimage.modules.shopdatacrawl.model.dto.ShopDataCrawlRowDto;
/**
@@ -21,6 +22,15 @@ public final class ShopDataCrawlRowNormalizer {
return value == null ? "" : value.trim();
}
/**
* 品牌列的唯一取值口径:客户端从亚马逊详情页的署名行原样回传,值里带着 "Brand: " 这类标签前缀。
* 进模型、比相等、算去重键三处必须取同一个字符串 —— 只在写出那一端剥,会让清洗过的存量行与
* 未清洗的回传行算出两个键,跨分片合并时同一行重复出件。
*/
public static String brand(String value) {
return BrandLabel.strip(trim(value));
}
public static boolean blank(String value) {
return value == null || value.isBlank();
}
@@ -56,7 +66,7 @@ public final class ShopDataCrawlRowNormalizer {
ShopDataCrawlRowDto row = new ShopDataCrawlRowDto();
row.setDate(trim(source.getDate()));
row.setAsin(trim(source.getAsin()));
row.setBrand(trim(source.getBrand()));
row.setBrand(brand(source.getBrand()));
row.setCommodityImage(trim(source.getCommodityImage()));
row.setInventorySales(trim(source.getInventorySales()));
row.setSalesRank(trim(source.getSalesRank()));
@@ -77,7 +87,7 @@ public final class ShopDataCrawlRowNormalizer {
return left != null && right != null
&& java.util.Objects.equals(trim(left.getDate()), trim(right.getDate()))
&& java.util.Objects.equals(trim(left.getAsin()), trim(right.getAsin()))
&& java.util.Objects.equals(trim(left.getBrand()), trim(right.getBrand()))
&& java.util.Objects.equals(brand(left.getBrand()), brand(right.getBrand()))
&& java.util.Objects.equals(trim(left.getCommodityImage()), trim(right.getCommodityImage()))
&& java.util.Objects.equals(trim(left.getInventorySales()), trim(right.getInventorySales()))
&& java.util.Objects.equals(trim(left.getSalesRank()), trim(right.getSalesRank()))
@@ -92,7 +102,7 @@ public final class ShopDataCrawlRowNormalizer {
if (row == null) {
return null;
}
return trim(row.getDate()) + ROW_KEY_SEPARATOR + trim(row.getAsin()) + ROW_KEY_SEPARATOR + trim(row.getBrand())
return trim(row.getDate()) + ROW_KEY_SEPARATOR + trim(row.getAsin()) + ROW_KEY_SEPARATOR + brand(row.getBrand())
+ ROW_KEY_SEPARATOR + trim(row.getCommodityImage()) + ROW_KEY_SEPARATOR + trim(row.getInventorySales())
+ ROW_KEY_SEPARATOR + trim(row.getSalesRank()) + ROW_KEY_SEPARATOR + trim(row.getPageViews())
+ ROW_KEY_SEPARATOR + trim(row.getUnitsSold()) + ROW_KEY_SEPARATOR + trim(row.getPrice())
@@ -1,6 +1,7 @@
package com.nanri.aiimage.modules.shopdatacrawl.service.support;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.util.BrandLabel;
import com.nanri.aiimage.modules.shopdatacrawl.model.dto.ShopDataCrawlCountryResultDto;
import com.nanri.aiimage.modules.shopdatacrawl.model.dto.ShopDataCrawlRowDto;
import com.nanri.aiimage.modules.shopdatacrawl.model.vo.ShopDataCrawlResultItemVo;
@@ -128,7 +129,10 @@ public final class ShopDataCrawlSheetBuilder {
/** 数据行 10 列值布局 + 样式应用(图片嵌入由调用方负责)。 */
public static void writeDataRowValues(Row row, ShopDataCrawlRowDto value, CellStyle[] styles) {
String[] values = {value.getDate(), value.getAsin(), "", value.getInventorySales(), value.getSalesRank(),
value.getPageViews(), value.getUnitsSold(), value.getPrice(), value.getRecommendedOffer(), value.getBrand()};
// 出件是用户的下一份上传物:改口径之前落库的累计文件快照与 row_payload 仍带 "Brand:" 前缀,
// 这一格不剥,下载再上传就把脏值送回链路里
value.getPageViews(), value.getUnitsSold(), value.getPrice(), value.getRecommendedOffer(),
BrandLabel.strip(value.getBrand())};
for (int column = 0; column < values.length; column++) {
Cell cell = row.createCell(column);
if (styles[column] != null) cell.setCellStyle(styles[column]);
@@ -1,5 +1,6 @@
package com.nanri.aiimage.modules.shopduplicatecheck.service;
import com.nanri.aiimage.common.util.BrandLabel;
import com.nanri.aiimage.common.util.UserMessages;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.common.exception.BusinessException;
@@ -105,8 +106,10 @@ public class ShopDataDuplicateCheckImportService {
}
for (DuplicateItem item : base.items()) {
for (DuplicateOccurrence occ : item.occurrences()) {
// 基线行读自上一份落库 payload(改口径之前可能是脏值),这里不剥就直接把脏值重插回扫描表
rowsByShop.computeIfAbsent(occ.shopName(), k -> new ArrayList<>())
.add(new RawRow(occ.asin(), occ.date(), occ.price(), occ.brand(), occ.country()));
.add(new RawRow(occ.asin(), occ.date(), occ.price(),
BrandLabel.strip(occ.brand()), occ.country()));
}
}
List<ShopParsed> baseParsed = new ArrayList<>();
@@ -1,5 +1,6 @@
package com.nanri.aiimage.modules.shopduplicatecheck.service;
import com.nanri.aiimage.common.util.BrandLabel;
import com.nanri.aiimage.modules.shopduplicatecheck.mapper.ShopDuplicateCheckSourceMapper;
import com.nanri.aiimage.modules.shopduplicatecheck.model.payload.DuplicateItem;
import com.nanri.aiimage.modules.shopduplicatecheck.model.payload.DuplicateOccurrence;
@@ -433,8 +434,10 @@ public class ShopDataDuplicateCheckQueryService {
for (DuplicateItem item : matched) {
String shopCount = String.valueOf(item.shopCount());
for (DuplicateOccurrence occ : item.occurrences()) {
// 出件是用户的下一份上传物:库里的历史 payload 仍可能带标签前缀,最后一列(品牌)在此剥掉
flat.add(new Object[]{item.asin(), shopCount, occ.shopName(), occ.groupName(),
effectiveCountryCn(occ), safe(occ.date()), safe(occ.price()), safe(occ.brand())});
effectiveCountryCn(occ), safe(occ.date()), safe(occ.price()),
BrandLabel.strip(safe(occ.brand()))});
}
}
flat.sort(flatExportComparator());
@@ -1,5 +1,6 @@
package com.nanri.aiimage.modules.shopduplicatecheck.service;
import com.nanri.aiimage.common.util.BrandLabel;
import com.nanri.aiimage.common.util.UserMessages;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -325,7 +326,9 @@ public class ShopDataDuplicateCheckScanService implements DuplicateCheckRefreshP
row.asin().trim(),
nvl(row.itemDate()),
nvl(row.price()),
nvl(row.brand()),
// 明细表里的品牌是改口径之前写进去的,标签前缀在进聚合这一端剥,
// 落库 payload 与页面、出件拿到的才是同一个干净值
BrandLabel.strip(nvl(row.brand())),
country));
if (!country.isEmpty()) {
countries.add(country);
@@ -1,5 +1,6 @@
package com.nanri.aiimage.modules.shopduplicatecheck.service.support;
import com.nanri.aiimage.common.util.BrandLabel;
import com.nanri.aiimage.common.util.ExcelStreamReader;
import java.io.ByteArrayInputStream;
@@ -105,7 +106,8 @@ public final class DuplicateCheckWorkbookParser {
asin,
cell(rowMap.get(dateCol)),
cell(rowMap.get(priceCol)),
cell(rowMap.get(brandCol)),
// 上传文件的品牌列是亚马逊详情页复制来的署名("Brand: XXX"),标签前缀只能在这一处剥
BrandLabel.strip(cell(rowMap.get(brandCol))),
sheetCountry));
}
}
@@ -4,6 +4,7 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.util.BrandLabel;
import com.nanri.aiimage.common.util.GroupResultPropagator;
import com.nanri.aiimage.config.SimilarAsinProperties;
import com.nanri.aiimage.config.StorageProperties;
@@ -901,7 +902,8 @@ public class SimilarAsinResultWorkbookAssembler {
resultRow.getPrice(),
firstNonBlank(parsedRow.getPrice(), readValueByHeader(parsedRow, "价格", "price"))));
row.createCell(col++).setCellValue(readValueByHeader(parsedRow, "卖家名称", "卖家名", "卖家", "店铺名称", "店铺名", "seller name", "seller_name", "seller-name", "sellername", "store name", "shop name"));
row.createCell(col++).setCellValue(readValueByHeader(parsedRow, "品牌", "brand"));
// 与 SheetBuilder 同口径:结果文件的品牌列必须剥掉页面复制带上的标签前缀,否则二次上传把脏值带回链路
row.createCell(col++).setCellValue(BrandLabel.strip(readValueByHeader(parsedRow, "品牌", "brand")));
String isStock = resultRow == null ? "" : SimilarAsinResultTextSupport.userFacingLlmCellValue(resultRow, resultRow.getIsStock());
String similarity = resultRow == null ? "" : SimilarAsinResultTextSupport.userFacingLlmCellValue(resultRow, resultRow.getSimilarity());
String isConform = resultRow == null ? "" : SimilarAsinResultTextSupport.userFacingLlmCellValue(resultRow, resultRow.getIsConform());
@@ -1,5 +1,6 @@
package com.nanri.aiimage.modules.similarasin.service.support;
import com.nanri.aiimage.common.util.BrandLabel;
import com.nanri.aiimage.modules.similarasin.model.vo.SimilarAsinParsedRowVo;
import com.nanri.aiimage.modules.similarasin.util.SimilarAsinImageEmbedder;
import org.apache.poi.ss.usermodel.Cell;
@@ -84,7 +85,8 @@ public final class SimilarAsinSheetBuilder {
row.createCell(col++).setCellValue(readValueByHeader(
parsedRow, "卖家名称", "卖家名", "卖家", "店铺名称", "店铺名", "seller name", "seller_name",
"seller-name", "sellername", "store name", "shop name"));
row.createCell(col).setCellValue(readValueByHeader(parsedRow, "品牌", "brand"));
// 出件是用户的下一份上传物:品牌列带 "Brand:" 标签前缀不剥,下载再上传就把脏值送回链路(清洗出口唯 BrandLabel)
row.createCell(col).setCellValue(BrandLabel.strip(readValueByHeader(parsedRow, "品牌", "brand")));
row.setHeightInPoints(SimilarAsinImageEmbedder.IMAGE_ROW_HEIGHT_POINTS);
rowIndex++;
}
@@ -45,6 +45,12 @@ public final class SecretUsageContext {
return context != null && context.usable() ? context : null;
}
/** 当前归属用户 id;无任务上下文时为 null——调用方据此拒绝打上游,别拿别人的套餐。 */
public static Long currentUserId() {
Context context = current();
return context == null ? null : context.userId();
}
/** 捕获当前上下文快照,供工作线程恢复;无上下文时返回 null。 */
public static Context snapshot() {
return HOLDER.get();
@@ -1,4 +1,4 @@
package com.nanri.aiimage.modules.publish.service;
package com.nanri.aiimage.common.util;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
@@ -14,7 +14,7 @@ import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
/**
* 上架品牌值的清洗出口。
* 品牌标签前缀清洗出口。
*
* <p>2026-10-08 的事故链是:Excel 里带 "Brand:" 标签前缀 → WIPO 把它当 Solr 字段限定符
* ({@code undefined field Brand},单日 19,247 次 500)→ 上游错误信封不是合法 Base64、被客户端
@@ -24,29 +24,32 @@ import org.junit.jupiter.api.Test;
* {@code PublishTaskService.replaceRows} 会用客户端回传的分片整表删后重插,
* 脏值照样落库(现网 7 个脏值来源任务里 5 个的行创建时间 == 任务完成时刻,即由这条路径写入)。
* 所以护栏从"注释里提醒调用方"改成"落在唯一写库出口 + 可实跑的用例"。
*
* <p>本类原在 {@code modules/publish/service} 下,因品牌列的读写两端散在多个模块而出搬为公共件;
* 三条守卫尺子(唯一副本、出口不被绕过、解析端不重复实现)随迁。
*/
class PublishBrandLabelTest {
class BrandLabelTest {
private static final String OUTLET_CLASS = "PublishBrandLabel.java";
private static final String OUTLET_CLASS = "BrandLabel.java";
/** 标签正则的特征片段:出现第二处就等于开了第二条会漂移的副本。 */
private static final String REGEX_SIGNATURE = "marque|marka";
@Test
void stripsLabelPrefixButKeepsLookalikes() {
assertThat(PublishBrandLabel.strip("Brand: NIKE")).isEqualTo("NIKE");
assertThat(PublishBrandLabel.strip(" brand : NIKE ")).isEqualTo("NIKE");
assertThat(PublishBrandLabel.strip("品牌:耐克")).isEqualTo("耐克");
assertThat(PublishBrandLabel.strip("MARCA: X")).isEqualTo("X");
assertThat(BrandLabel.strip("Brand: NIKE")).isEqualTo("NIKE");
assertThat(BrandLabel.strip(" brand : NIKE ")).isEqualTo("NIKE");
assertThat(BrandLabel.strip("品牌:耐克")).isEqualTo("耐克");
assertThat(BrandLabel.strip("MARCA: X")).isEqualTo("X");
// "Brands:" 不是标签;值中间的冒号属于品牌自身内容,只剥行首一次
assertThat(PublishBrandLabel.strip("Brands: NIKE")).isEqualTo("Brands: NIKE");
assertThat(PublishBrandLabel.strip("Brand: NIKE: X")).isEqualTo("NIKE: X");
assertThat(PublishBrandLabel.strip("NIKE Brand")).isEqualTo("NIKE Brand");
assertThat(BrandLabel.strip("Brands: NIKE")).isEqualTo("Brands: NIKE");
assertThat(BrandLabel.strip("Brand: NIKE: X")).isEqualTo("NIKE: X");
assertThat(BrandLabel.strip("NIKE Brand")).isEqualTo("NIKE Brand");
// 标签只有出现在行首才是"字段名";句中出现的要原样留着,否则把 ^ 锚摘掉(变成"逢 Brand: 就裁")这条就会红
assertThat(PublishBrandLabel.strip("Super Brand: Nike"))
assertThat(BrandLabel.strip("Super Brand: Nike"))
.isEqualTo("Super Brand: Nike");
assertThat(PublishBrandLabel.strip("BrandNIKE")).isEqualTo("BrandNIKE");
assertThat(PublishBrandLabel.strip("")).isEmpty();
assertThat(PublishBrandLabel.strip(null)).isNull();
assertThat(BrandLabel.strip("BrandNIKE")).isEqualTo("BrandNIKE");
assertThat(BrandLabel.strip("")).isEmpty();
assertThat(BrandLabel.strip(null)).isNull();
}
@Test
@@ -54,8 +57,8 @@ class PublishBrandLabelTest {
// 现网 1,533 个脏值清洗后 0 个变空串(实测),但 "Brand:" 这种纯标签值确实会洗成空。
// 钉住这一条是因为 PublishTaskService.isBlankRow 要求八个字段同时为空才算空行,
// 单靠 brand 变空不会让一行消失 —— 改了这条判据就会静默丢行。
assertThat(PublishBrandLabel.strip("Brand:")).isEmpty();
assertThat(PublishBrandLabel.strip("Brand: ")).isEmpty();
assertThat(BrandLabel.strip("Brand:")).isEmpty();
assertThat(BrandLabel.strip("Brand: ")).isEmpty();
}
@Test
@@ -74,7 +77,7 @@ class PublishBrandLabelTest {
// 只有写进实体的那一行算出口;DTO 之间的搬运(copyRow/toRowDto)不是
if (line.matches("^entity\\.setBrand\\(.*\\);")) {
written.add(file.getFileName() + ": " + line);
if (!line.contains("PublishBrandLabel.strip(")) {
if (!line.contains("BrandLabel.strip(")) {
offenders.add(file.getFileName() + ": " + line);
}
}
@@ -83,7 +86,7 @@ class PublishBrandLabelTest {
// 取样集非空自检:扫描 0 命中时下面这条恒绿,等于没护栏
assertThat(written).as("publish 模块里写 PublishItemEntity.brand 的行应被扫到").isNotEmpty();
assertThat(offenders)
.as("绕过 PublishBrandLabel.strip 的 brand 写入点(客户端回传 replaceRows 会整表重插,"
.as("绕过 BrandLabel.strip 的 brand 写入点(客户端回传 replaceRows 会整表重插,"
+ "少堵一处就等于每完成一个任务把脏值写回去一次)")
.isEmpty();
}
@@ -104,7 +107,7 @@ class PublishBrandLabelTest {
@Test
void parseSideAlsoDelegatesInsteadOfReimplementing() throws IOException {
String text = read(sourceOf("PublishWorkbookService.java"));
assertThat(text).contains("row.setBrand(PublishBrandLabel.strip(values.get(3)));");
assertThat(text).contains("row.setBrand(BrandLabel.strip(values.get(3)));");
assertThat(text).doesNotContain("stripBrandLabel");
}
@@ -96,8 +96,8 @@ class HttpClientConnectionReuseTest {
void test_task_077_brand_normal_default_path() throws Exception {
// 默认路径:品牌检查客户端通过共享池创建单例 RestClient,
// 工厂为带 keep-alive 连接池的 JdkClientHttpRequestFactory。
BrandCheckClient client = new BrandCheckClient(new BrandCheckProperties(), null);
BrandCheckBatchResult result = client.checkTitleText(" ");
BrandCheckClient client = new BrandCheckClient(new BrandCheckProperties(), null, null);
BrandCheckBatchResult result = client.checkTitleText(" ", null, null);
assertTrue(result.brands().isEmpty(), "空标题安全跳过,不创建无效资源");
assertPooled(factoryOf(restClientOf(client)));
@@ -108,7 +108,7 @@ class HttpClientConnectionReuseTest {
// 批量场景:LLM/品牌/紫鸟三个客户端各自持有独立 RestClient,
// 但底层连接池共用同一 HttpClient 实例,不重复创建。
SimilarAsinLlmClient llm = new SimilarAsinLlmClient(new SimilarAsinProperties(), new ObjectMapper(), null, null);
BrandCheckClient brand = new BrandCheckClient(new BrandCheckProperties(), null);
BrandCheckClient brand = new BrandCheckClient(new BrandCheckProperties(), null, null);
ZiniaoClientImpl ziniao = new ZiniaoClientImpl(new ZiniaoProperties(), new ObjectMapper());
HttpClient llmClient = clientOf(factoryOf(restClientOf(llm)));
@@ -124,7 +124,7 @@ class HttpClientConnectionReuseTest {
void test_task_077_brand_normal_repeated_operation_is_idempotent() throws Exception {
// 幂等:同一客户端重复触发请求创建逻辑只产生一个 RestClient,
// 重复调用返回同一实例,不重复创建客户端对象。
BrandCheckClient brand = new BrandCheckClient(new BrandCheckProperties(), null);
BrandCheckClient brand = new BrandCheckClient(new BrandCheckProperties(), null, null);
assertSame(restClientOf(brand), restClientOf(brand), "品牌客户端复用同一 RestClient");
ZiniaoClientImpl ziniao = new ZiniaoClientImpl(new ZiniaoProperties(), new ObjectMapper());
@@ -134,8 +134,8 @@ class HttpClientConnectionReuseTest {
@Test
void test_task_077_brand_boundary_empty_input() throws Exception {
// 空输入:空品牌列表不发起任何 HTTP 请求、不创建客户端资源。
BrandCheckClient brand = new BrandCheckClient(new BrandCheckProperties(), null);
BrandCheckBatchResult result = brand.checkAll(List.of(), "Terms");
BrandCheckClient brand = new BrandCheckClient(new BrandCheckProperties(), null, null);
BrandCheckBatchResult result = brand.checkAll(List.of(), "Terms", null);
assertTrue(result.brands().isEmpty());
assertTrue(result.faildData().isEmpty());
@@ -145,7 +145,7 @@ class HttpClientConnectionReuseTest {
@Test
void test_task_077_brand_boundary_single_item() throws Exception {
// 单元素:单客户端单请求走共享池,工厂带连接池,行为与批量一致。
BrandCheckClient brand = new BrandCheckClient(new BrandCheckProperties(), null);
BrandCheckClient brand = new BrandCheckClient(new BrandCheckProperties(), null, null);
assertPooled(factoryOf(restClientOf(brand)));
}
@@ -155,7 +155,7 @@ class HttpClientConnectionReuseTest {
// 不随实例数量线性增长连接资源。
int instances = 8;
for (int i = 0; i < instances; i++) {
restClientOf(new BrandCheckClient(new BrandCheckProperties(), null));
restClientOf(new BrandCheckClient(new BrandCheckProperties(), null, null));
restClientOf(new ZiniaoClientImpl(new ZiniaoProperties(), new ObjectMapper()));
}
assertSame(HttpClientPool.sharedHttpClient(), HttpClientPool.sharedHttpClient(),
@@ -7,6 +7,7 @@ import com.nanri.aiimage.config.ZiniaoProperties;
import com.nanri.aiimage.metrics.ExternalCallMetricsRecorder;
import com.nanri.aiimage.modules.brand.client.BrandCheckClient;
import com.nanri.aiimage.modules.similarasin.client.SimilarAsinLlmClient;
import com.nanri.aiimage.modules.usersecret.service.UserApiSecretService;
import com.nanri.aiimage.modules.ziniao.client.ZiniaoClientImpl;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
@@ -34,6 +35,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.nanri.aiimage.modules.usersecret.service.UserSecretUsageService;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Task 78:为所有外部调用(LLM / 品牌检查 / 紫鸟)统一增加耗时、重试、
@@ -190,8 +192,8 @@ class ExternalCallMetricsRecorderTest {
"client", "llm", "result", "success"), "三次成功全部记录");
// 全部外部客户端(LLM / 品牌检查 / 紫鸟)在同一次批量中各自记录指标
BrandCheckClient brand = new BrandCheckClient(brandProps(), new ExternalCallMetricsRecorder(registry));
brand.checkAll(List.of("Nintendo", "LEGO", "Sony"), "Terms");
BrandCheckClient brand = new BrandCheckClient(brandProps(), new ExternalCallMetricsRecorder(registry), stubbedUserSecrets());
brand.checkAll(List.of("Nintendo", "LEGO", "Sony"), "Terms", 7L);
ZiniaoClientImpl ziniao = new ZiniaoClientImpl(ziniaoProps(), objectMapper, new ExternalCallMetricsRecorder(registry));
assertEquals(1001L, ziniao.getCompanyIdByApiKey("test-api-key"));
@@ -208,10 +210,10 @@ class ExternalCallMetricsRecorderTest {
@Test
void test_task_078_payload_metrics_normal_repeated_operation_is_idempotent() throws Exception {
BrandCheckProperties props = brandProps();
BrandCheckClient client = new BrandCheckClient(props, new ExternalCallMetricsRecorder(registry));
BrandCheckClient client = new BrandCheckClient(props, new ExternalCallMetricsRecorder(registry), stubbedUserSecrets());
client.check("Nintendo");
client.check("Nintendo");
client.check("Nintendo", "Terms", 7L);
client.check("Nintendo", "Terms", 7L);
assertEquals(2, brandCount.get(), "两次请求真实发出");
assertEquals(2.0, counterCount("aiimage.external-call.total",
@@ -225,9 +227,9 @@ class ExternalCallMetricsRecorderTest {
@Test
void test_task_078_payload_metrics_boundary_empty_input() throws Exception {
BrandCheckProperties props = brandProps();
BrandCheckClient client = new BrandCheckClient(props, new ExternalCallMetricsRecorder(registry));
BrandCheckClient client = new BrandCheckClient(props, new ExternalCallMetricsRecorder(registry), stubbedUserSecrets());
BrandCheckClient.BrandCheckBatchResult result = client.checkAll(List.of(), "Terms");
BrandCheckClient.BrandCheckBatchResult result = client.checkAll(List.of(), "Terms", 7L);
assertEquals(0, brandCount.get(), "空输入不发起外部调用");
assertTrue(result.brands().isEmpty());
@@ -240,9 +242,9 @@ class ExternalCallMetricsRecorderTest {
@Test
void test_task_078_payload_metrics_boundary_single_item() throws Exception {
BrandCheckProperties props = brandProps();
BrandCheckClient client = new BrandCheckClient(props, new ExternalCallMetricsRecorder(registry));
BrandCheckClient client = new BrandCheckClient(props, new ExternalCallMetricsRecorder(registry), stubbedUserSecrets());
BrandCheckClient.BrandCheckResponse response = client.check("LEGO");
BrandCheckClient.BrandCheckResponse response = client.check("LEGO", "Terms", 7L);
assertNotNull(response);
awaitMetric("aiimage.external-call.duration", "client", "brand");
@@ -295,9 +297,9 @@ class ExternalCallMetricsRecorderTest {
@Test
void test_task_078_payload_metrics_invalid_input_rejected() throws Exception {
BrandCheckProperties props = brandProps();
BrandCheckClient client = new BrandCheckClient(props, new ExternalCallMetricsRecorder(registry));
BrandCheckClient client = new BrandCheckClient(props, new ExternalCallMetricsRecorder(registry), stubbedUserSecrets());
BrandCheckClient.BrandCheckBatchResult result = client.checkAll(null, "Terms");
BrandCheckClient.BrandCheckBatchResult result = client.checkAll(null, "Terms", 7L);
assertTrue(result.brands().isEmpty(), "null 列表安全跳过");
assertEquals(0, brandCount.get(), "非法输入不发起外部调用");
@@ -345,6 +347,14 @@ class ExternalCallMetricsRecorderTest {
return props;
}
/** 品牌检查按 userId 取用户自己的代理:不桩一个非空代理就一次上游都不会打。 */
private UserApiSecretService stubbedUserSecrets() {
UserApiSecretService secrets = mock(UserApiSecretService.class);
when(secrets.findPlainValue(org.mockito.ArgumentMatchers.anyLong(),
org.mockito.ArgumentMatchers.anyString())).thenReturn("http://user:pass@127.0.0.1:9");
return secrets;
}
private ZiniaoProperties ziniaoProps() {
ZiniaoProperties props = new ZiniaoProperties();
props.setBaseUrl("http://127.0.0.1:" + port);
@@ -17,6 +17,7 @@ import java.util.ArrayList;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
@@ -50,12 +51,12 @@ class AppearancePatentBrandBatchTest {
@Test
void mergedBatchAsksBrandCheckOnceAndAttributesPerRow() throws Exception {
// 桩按「本行的词」返回:含阿凡达的行 failedData 非空,另一行为空。
when(brandCheckClient.checkTitleTexts(anyList(), eq("Terms"))).thenAnswer(invocation -> {
when(brandCheckClient.checkTitleTexts(anyList(), eq("Terms"), any())).thenAnswer(invocation -> {
List<String> titles = invocation.getArgument(0);
List<BrandCheckClient.BrandCheckBatchResult> results = new ArrayList<>();
for (String title : titles) {
List<Object> failed = title.contains("阿凡达") ? List.of("阿凡达") : List.of();
results.add(new BrandCheckClient.BrandCheckBatchResult(List.of(title), failed, List.of()));
results.add(new BrandCheckClient.BrandCheckBatchResult(List.of(title), failed, List.of(), ""));
}
return results;
});
@@ -69,8 +70,8 @@ class AppearancePatentBrandBatchTest {
List<AppearancePatentResultRowDto> merged = client.mergeRowsFromDataText(rows, dataText);
verify(brandCheckClient, times(1)).checkTitleTexts(anyList(), eq("Terms"));
verify(brandCheckClient, never()).checkTitleText(anyString(), anyString());
verify(brandCheckClient, times(1)).checkTitleTexts(anyList(), eq("Terms"), any());
verify(brandCheckClient, never()).checkTitleText(anyString(), anyString(), any());
assertThat(merged).hasSize(2);
assertThat(merged.get(0).getTitleRisk()).isEqualTo("侵权");
assertThat(merged.get(1).getTitleRisk()).as("干净行不得继承别行的侵权词").isEqualTo("无侵权");
@@ -85,8 +86,8 @@ class AppearancePatentBrandBatchTest {
client.mergeRowsFromDataText(rows, dataText);
verify(brandCheckClient, never()).checkTitleTexts(anyList(), anyString());
verify(brandCheckClient, never()).checkTitleText(anyString(), anyString());
verify(brandCheckClient, never()).checkTitleTexts(anyList(), anyString(), any());
verify(brandCheckClient, never()).checkTitleText(anyString(), anyString(), any());
}
/**
@@ -98,12 +99,12 @@ class AppearancePatentBrandBatchTest {
*/
@Test
void fallbackRowsAlsoAskBrandCheckOnceForTheWholeBatch() throws Exception {
when(brandCheckClient.checkTitleTexts(anyList(), eq("Terms"))).thenAnswer(invocation -> {
when(brandCheckClient.checkTitleTexts(anyList(), eq("Terms"), any())).thenAnswer(invocation -> {
List<String> titles = invocation.getArgument(0);
List<BrandCheckClient.BrandCheckBatchResult> results = new ArrayList<>();
for (String title : titles) {
List<Object> failed = title.contains("阿凡达") ? List.of("阿凡达") : List.of();
results.add(new BrandCheckClient.BrandCheckBatchResult(List.of(title), failed, List.of()));
results.add(new BrandCheckClient.BrandCheckBatchResult(List.of(title), failed, List.of(), ""));
}
return results;
});
@@ -126,8 +127,8 @@ class AppearancePatentBrandBatchTest {
@SuppressWarnings("unchecked")
ArgumentCaptor<List<String>> titlesCaptor = ArgumentCaptor.forClass(List.class);
verify(brandCheckClient, times(1)).checkTitleTexts(titlesCaptor.capture(), eq("Terms"));
verify(brandCheckClient, never()).checkTitleText(anyString(), anyString());
verify(brandCheckClient, times(1)).checkTitleTexts(titlesCaptor.capture(), eq("Terms"), any());
verify(brandCheckClient, never()).checkTitleText(anyString(), anyString(), any());
assertThat(titlesCaptor.getValue())
.containsExactly("阿凡达 玩具 手办 正版", "小米 充电宝 20000mAh 快充");
assertThat(rows).hasSize(2);
@@ -85,7 +85,7 @@ class AppearancePatentLlmClientHttpTest {
brand.setRetryTimes(1);
brand.setRetryIntervalMillis(0);
brand.setTotalTimeoutMillis(5000);
return new BrandCheckClient(brand, null);
return new BrandCheckClient(brand, null, null);
}
private void handleBrandCheck(HttpExchange exchange) throws IOException {
@@ -77,7 +77,7 @@ class AppearancePatentLlmClientImageDedupeTest {
brand.setRetryTimes(1);
brand.setRetryIntervalMillis(0);
brand.setTotalTimeoutMillis(5000);
return new BrandCheckClient(brand, null);
return new BrandCheckClient(brand, null, null);
}
@AfterEach
@@ -10,6 +10,7 @@ import org.junit.jupiter.api.Test;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
@@ -25,7 +26,7 @@ class AppearancePatentLlmClientTest {
new AppearancePatentProperties(),
new ObjectMapper(),
null,
new BrandCheckClient(new BrandCheckProperties(), null),
new BrandCheckClient(new BrandCheckProperties(), null, null),
mock(UserSecretUsageService.class)
);
@@ -50,7 +51,7 @@ class AppearancePatentLlmClientTest {
@Test
void titleRiskIsInfringementWhenBrandCheckHasFailedData() {
BrandCheckClient.BrandCheckBatchResult result =
new BrandCheckClient.BrandCheckBatchResult(List.of("阿凡达"), List.of("阿凡达"), List.of());
new BrandCheckClient.BrandCheckBatchResult(List.of("阿凡达"), List.of("阿凡达"), List.of(), "");
assertThat(client.buildTitleRisk("阿凡达", result)).isEqualTo("侵权");
}
@@ -88,7 +89,7 @@ class AppearancePatentLlmClientTest {
@Test
void titleRiskNamesUpstreamOutageOnlyWhenWholeBatchFailed() {
BrandCheckClient.BrandCheckBatchResult failed =
new BrandCheckClient.BrandCheckBatchResult(List.of("nike"), List.of(), List.of("nike"));
new BrandCheckClient.BrandCheckBatchResult(List.of("nike"), List.of(), List.of("nike"), "");
assertThat(client.buildTitleRisk("nike air", failed, true))
.isEqualTo(AppearancePatentLlmClient.BRAND_UPSTREAM_UNAVAILABLE);
@@ -100,7 +101,7 @@ class AppearancePatentLlmClientTest {
@Test
void infringementStillWinsOverWholeBatchOutageMessage() {
BrandCheckClient.BrandCheckBatchResult hit =
new BrandCheckClient.BrandCheckBatchResult(List.of("阿凡达"), List.of("阿凡达"), List.of());
new BrandCheckClient.BrandCheckBatchResult(List.of("阿凡达"), List.of("阿凡达"), List.of(), "");
assertThat(client.buildTitleRisk("阿凡达 联名", hit, true)).isEqualTo("侵权");
}
@@ -134,7 +135,7 @@ class AppearancePatentLlmClientTest {
assertThat(merged).hasSize(1);
assertThat(merged.get(0).getTitleRisk()).isEqualTo("无侵权");
assertThat(merged.get(0).getConclusion()).isEqualTo("无侵权");
verify(brandCheckClient, never()).checkTitleText(anyString(), anyString());
verify(brandCheckClient, never()).checkTitleText(anyString(), anyString(), any());
}
private static AppearancePatentLlmClient clientWith(BrandCheckClient brandCheckClient) {
@@ -152,9 +153,9 @@ class AppearancePatentLlmClientTest {
@Test
void wholeBatchQueryFailureEscalatesEveryRow() throws Exception {
BrandCheckClient brandCheckClient = mock(BrandCheckClient.class);
when(brandCheckClient.checkTitleTexts(anyList(), eq("Terms"))).thenReturn(List.of(
new BrandCheckClient.BrandCheckBatchResult(List.of("nike"), List.of(), List.of("nike")),
new BrandCheckClient.BrandCheckBatchResult(List.of("puma"), List.of(), List.of("puma"))));
when(brandCheckClient.checkTitleTexts(anyList(), eq("Terms"), any())).thenReturn(List.of(
new BrandCheckClient.BrandCheckBatchResult(List.of("nike"), List.of(), List.of("nike"), ""),
new BrandCheckClient.BrandCheckBatchResult(List.of("puma"), List.of(), List.of("puma"), "")));
String dataText = """
{"data":[{"row_id":"1","title":"nike","title_reason":"nike","appearance":"外观识别异常","result":""},
{"row_id":"2","title":"puma","title_reason":"puma","appearance":"外观识别异常","result":""}]}
@@ -175,9 +176,9 @@ class AppearancePatentLlmClientTest {
@Test
void oneSuccessfulRowKeepsOthersOnPerRowFailureText() throws Exception {
BrandCheckClient brandCheckClient = mock(BrandCheckClient.class);
when(brandCheckClient.checkTitleTexts(anyList(), eq("Terms"))).thenReturn(List.of(
new BrandCheckClient.BrandCheckBatchResult(List.of("nike"), List.of(), List.of("nike")),
new BrandCheckClient.BrandCheckBatchResult(List.of("puma"), List.of(), List.of())));
when(brandCheckClient.checkTitleTexts(anyList(), eq("Terms"), any())).thenReturn(List.of(
new BrandCheckClient.BrandCheckBatchResult(List.of("nike"), List.of(), List.of("nike"), ""),
new BrandCheckClient.BrandCheckBatchResult(List.of("puma"), List.of(), List.of(), "")));
String dataText = """
{"data":[{"row_id":"1","title":"nike","title_reason":"nike","appearance":"外观识别异常","result":""},
{"row_id":"2","title":"puma","title_reason":"puma","appearance":"外观识别异常","result":""}]}
@@ -194,9 +195,9 @@ class AppearancePatentLlmClientTest {
void callBrandCheckOnlyWhenTitleAndAppearanceArePresent() throws Exception {
BrandCheckClient brandCheckClient = mock(BrandCheckClient.class);
// 一行也走批接口:逐行调用等于把 90 秒耗时预算按行复制
when(brandCheckClient.checkTitleTexts(anyList(), eq("Terms")))
when(brandCheckClient.checkTitleTexts(anyList(), eq("Terms"), any()))
.thenReturn(List.of(new BrandCheckClient.BrandCheckBatchResult(
List.of("阿凡达"), List.of(), List.of())));
List.of("阿凡达"), List.of(), List.of(), "")));
AppearancePatentLlmClient llmClient = new AppearancePatentLlmClient(
new AppearancePatentProperties(),
new ObjectMapper(),
@@ -214,8 +215,8 @@ class AppearancePatentLlmClientTest {
assertThat(merged).hasSize(1);
assertThat(merged.get(0).getTitleRisk()).isEqualTo("无侵权");
verify(brandCheckClient).checkTitleTexts(List.of("阿凡达"), "Terms");
verify(brandCheckClient, never()).checkTitleText(anyString(), anyString());
verify(brandCheckClient).checkTitleTexts(eq(List.of("阿凡达")), eq("Terms"), any());
verify(brandCheckClient, never()).checkTitleText(anyString(), anyString(), any());
}
@Test
@@ -238,7 +239,7 @@ class AppearancePatentLlmClientTest {
assertThat(merged).hasSize(1);
assertThat(merged.get(0).getTitleRisk()).isEmpty();
verify(brandCheckClient, never()).checkTitleText(anyString(), anyString());
verify(brandCheckClient, never()).checkTitleText(anyString(), anyString(), any());
}
@Test
@@ -262,7 +263,7 @@ class AppearancePatentLlmClientTest {
assertThat(merged).hasSize(1);
assertThat(merged.get(0).getTitleRisk()).isEmpty();
assertThat(merged.get(0).getAppearanceRisk()).isNullOrEmpty();
verify(brandCheckClient, never()).checkTitleText(anyString(), anyString());
verify(brandCheckClient, never()).checkTitleText(anyString(), anyString(), any());
}
@Test
@@ -68,7 +68,7 @@ class AppearancePatentLlmClientTokenUsageTest {
brand.setRetryTimes(1);
brand.setRetryIntervalMillis(0);
brand.setTotalTimeoutMillis(5000);
return new BrandCheckClient(brand, null);
return new BrandCheckClient(brand, null, null);
}
@AfterEach
@@ -10,6 +10,7 @@ import com.nanri.aiimage.config.InstanceMetadata;
import com.nanri.aiimage.config.StorageProperties;
import com.nanri.aiimage.modules.appearancepatent.client.AppearancePatentLlmClient;
import com.nanri.aiimage.modules.appearancepatent.model.dto.AppearancePatentResultRowDto;
import com.nanri.aiimage.modules.appearancepatent.service.support.AppearancePatentLlmBatchPipeline;
import com.nanri.aiimage.modules.file.service.LocalFileStorageService;
import com.nanri.aiimage.modules.file.service.oss.OssStorageService;
import com.nanri.aiimage.modules.task.mapper.FileResultMapper;
@@ -137,7 +138,7 @@ class AppearancePatentRowMarkTimingTest {
when(taskCacheService.beginRowInspection(eq(TASK_ID), anyString())).thenReturn(true);
List<AppearancePatentResultRowDto> candidates = (List<AppearancePatentResultRowDto>) ReflectionTestUtils
.invokeMethod(service, "collectPendingLlmCandidates", List.of(chunk()), new AppearancePatentTaskService.ChunkRowKeyIndex());
.invokeMethod(service, "collectPendingLlmCandidates", List.of(chunk()), new AppearancePatentLlmBatchPipeline.ChunkRowKeyIndex());
assertEquals(2, candidates.size());
verify(taskCacheService).beginRowInspection(TASK_ID, "r1");
@@ -153,7 +154,7 @@ class AppearancePatentRowMarkTimingTest {
when(taskCacheService.beginRowInspection(eq(TASK_ID), eq("r2"))).thenReturn(false);
List<AppearancePatentResultRowDto> candidates = (List<AppearancePatentResultRowDto>) ReflectionTestUtils
.invokeMethod(service, "collectPendingLlmCandidates", List.of(chunk()), new AppearancePatentTaskService.ChunkRowKeyIndex());
.invokeMethod(service, "collectPendingLlmCandidates", List.of(chunk()), new AppearancePatentLlmBatchPipeline.ChunkRowKeyIndex());
assertEquals(1, candidates.size());
assertEquals("r1", candidates.get(0).getRowToken());
@@ -362,7 +363,7 @@ class AppearancePatentRowMarkTimingTest {
when(taskCacheService.beginRowInspection(eq(TASK_ID), anyString())).thenReturn(true);
List<AppearancePatentResultRowDto> candidates = (List<AppearancePatentResultRowDto>) ReflectionTestUtils
.invokeMethod(service, "collectPendingLlmCandidates", List.of(chunk()), new AppearancePatentTaskService.ChunkRowKeyIndex());
.invokeMethod(service, "collectPendingLlmCandidates", List.of(chunk()), new AppearancePatentLlmBatchPipeline.ChunkRowKeyIndex());
assertEquals(1, candidates.size());
assertEquals("r3", candidates.get(0).getRowToken());
@@ -387,7 +388,7 @@ class AppearancePatentRowMarkTimingTest {
List<AppearancePatentResultRowDto> candidates = (List<AppearancePatentResultRowDto>) ReflectionTestUtils
.invokeMethod(service, "collectPendingLlmCandidates", List.of(chunk()),
new AppearancePatentTaskService.ChunkRowKeyIndex());
new AppearancePatentLlmBatchPipeline.ChunkRowKeyIndex());
assertEquals(3, candidates.size(), "同父号三行必须都进候选,不能只检一行");
verify(taskCacheService).beginRowInspection(TASK_ID, "r21");
@@ -409,7 +410,7 @@ class AppearancePatentRowMarkTimingTest {
List<AppearancePatentResultRowDto> candidates = (List<AppearancePatentResultRowDto>) ReflectionTestUtils
.invokeMethod(service, "collectPendingLlmCandidates", List.of(chunk()),
new AppearancePatentTaskService.ChunkRowKeyIndex());
new AppearancePatentLlmBatchPipeline.ChunkRowKeyIndex());
assertEquals(1, candidates.size());
assertEquals("r22", candidates.get(0).getRowToken(), "该检的是没结论的那一行,不是已经检过的");
@@ -435,7 +436,7 @@ class AppearancePatentRowMarkTimingTest {
landed.setConclusion("无侵权");
ReflectionTestUtils.invokeMethod(service, "mergeLlmRowsIntoChunks",
task(), List.of(landed), List.of(landed), new AppearancePatentTaskService.ChunkRowKeyIndex());
task(), List.of(landed), List.of(landed), new AppearancePatentLlmBatchPipeline.ChunkRowKeyIndex());
ArgumentCaptor<String> written = ArgumentCaptor.forClass(String.class);
verify(transientPayloadStorageService, org.mockito.Mockito.atLeastOnce()).storeChunkPayloadVersioned(
@@ -29,6 +29,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
*/
class AppearancePatentRowOutcomeTest {
private static final int COL_BRAND = 4;
private static final int COL_TITLE = 6;
private static final int COL_URL = 7;
private static final int COL_TITLE_RISK = 9;
@@ -355,4 +356,36 @@ class AppearancePatentRowOutcomeTest {
}
throw new AssertionError("原因 sheet 里没有 ASIN=" + asin + " 的行");
}
// ---------- 4. 品牌列只认洗过标签前缀的值 ----------
@Test
void brandCellNeverCarriesTheAmazonBylinePrefix() throws Exception {
// 品牌列有两个来源:用户上传表的「品牌」列(这里就是 "Brand: Acme")与客户端回传行的 Brand,
// 详情页整行复制来的署名前缀既脏出件、又会在品牌库查询里被当字段限定符打成上游 500。
List<AppearancePatentParsedRowVo> all = List.of(sheetRowOnlyId("1", "B0A"));
AppearancePatentResultRowDto resultRow = judgedRow("1", "B0A", "T", "https://img/1.jpg");
Map<String, AppearancePatentResultRowDto> byRowKey = new LinkedHashMap<>();
byRowKey.put(AppearancePatentSheetBuilder.rowKey(all.get(0)), resultRow);
assertEquals("Acme", brandCell(all, byRowKey), "回传行没带品牌时,源表值也要剥掉标签");
resultRow.setBrand("Brand: Nike");
assertEquals("Nike", brandCell(all, byRowKey));
// "Brands:" 是真实品牌写法、不是字段标签;值中间的冒号属于品牌本体,只能剥行首一次
resultRow.setBrand("Brands: Nike");
assertEquals("Brands: Nike", brandCell(all, byRowKey));
// 只剩标签的回传值等于这行没带品牌:回退源表列,而不是把洗出来的空串当成有效值写进格子
resultRow.setBrand("Brand:");
assertEquals("Acme", brandCell(all, byRowKey));
}
private static String brandCell(List<AppearancePatentParsedRowVo> rows,
Map<String, AppearancePatentResultRowDto> byRowKey) throws Exception {
try (Workbook workbook = render(rows, byRowKey)) {
return cell(workbook.getSheet("外观专利检测结果"), 1, COL_BRAND);
}
}
}
@@ -175,6 +175,23 @@ class AsinResultCacheServiceTest {
assertEquals(255, captor.getValue().get(0).getBrand().length());
}
/**
* 缓存行来自客户端回传的采集结果,品牌那格常常是亚马逊详情页署名行原样("Brand: XXX")。
* 这张缓存之后被 AsinCacheHitVo 喂给多个下游任务,入库前不剥一次,脏值就从这里向下游复播。
*/
@Test
@SuppressWarnings({"rawtypes", "unchecked"})
void writeStoresBrandWithoutTheBylineLabel() {
AsinCacheWriteRowDto dto = writeRow("OK", "9.90");
dto.setBrand("Brand: NIKE");
service.write(List.of(dto));
ArgumentCaptor<List<AsinResultCacheEntity>> captor = ArgumentCaptor.forClass(List.class);
verify(mapper).upsertBatch(captor.capture());
assertEquals("NIKE", captor.getValue().get(0).getBrand());
}
@Test
void writeSplitsByBatchSizeAndSurvivesFailingBatch() {
when(mapper.upsertBatch(anyList())).thenReturn(100).thenThrow(new RuntimeException("锁等待超时"));
@@ -1,6 +1,7 @@
package com.nanri.aiimage.modules.brand.client;
import com.nanri.aiimage.config.BrandCheckProperties;
import com.nanri.aiimage.modules.usersecret.service.UserApiSecretService;
import com.sun.net.httpserver.HttpServer;
import org.junit.jupiter.api.Test;
@@ -12,12 +13,16 @@ import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class BrandCheckClientTest {
@Test
void splitTitleTextSupportsCommonSeparatorsAndQuotes() {
BrandCheckClient client = new BrandCheckClient(new BrandCheckProperties(), null);
BrandCheckClient client = new BrandCheckClient(new BrandCheckProperties(), null, null);
List<String> brands = client.splitTitleText("'阿凡达,任天堂'; Disney、LEGO\nSony");
@@ -26,7 +31,7 @@ class BrandCheckClientTest {
@Test
void splitTitleTextDeduplicatesBlankValues() {
BrandCheckClient client = new BrandCheckClient(new BrandCheckProperties(), null);
BrandCheckClient client = new BrandCheckClient(new BrandCheckProperties(), null, null);
List<String> brands = client.splitTitleText(" 任天堂, ,任天堂,Sony ");
@@ -46,7 +51,7 @@ class BrandCheckClientTest {
try {
BrandCheckClient client = newClient(server, 3);
BrandCheckClient.BrandCheckBatchResult result = client.checkAll(List.of("Apple"), "Terms");
BrandCheckClient.BrandCheckBatchResult result = client.checkAll(List.of("Apple"), "Terms", 7L);
assertThat(attempts.get()).as("前两次失败后应重试到成功").isEqualTo(3);
assertThat(result.hasFailedData()).isFalse();
@@ -66,7 +71,7 @@ class BrandCheckClientTest {
try {
BrandCheckClient client = newClient(server, 3);
BrandCheckClient.BrandCheckBatchResult result = client.checkAll(List.of("Apple"), "Terms");
BrandCheckClient.BrandCheckBatchResult result = client.checkAll(List.of("Apple"), "Terms", 7L);
assertThat(attempts.get()).as("持续失败应耗尽重试次数").isEqualTo(3);
assertThat(result.hasFailedData()).isFalse();
@@ -87,7 +92,7 @@ class BrandCheckClientTest {
try {
BrandCheckClient client = newClient(server, 3);
BrandCheckClient.BrandCheckBatchResult result = client.checkAll(List.of("Apple"), "Terms");
BrandCheckClient.BrandCheckBatchResult result = client.checkAll(List.of("Apple"), "Terms", 7L);
assertThat(attempts.get()).as("命中侵权属有效结论,不应重试").isEqualTo(1);
assertThat(result.hasFailedData()).isTrue();
@@ -115,7 +120,7 @@ class BrandCheckClientTest {
BrandCheckClient client = newClient(server, 3);
List<String> brands = List.of("b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8");
BrandCheckClient.BrandCheckBatchResult result = client.checkAll(brands, "Terms");
BrandCheckClient.BrandCheckBatchResult result = client.checkAll(brands, "Terms", 7L);
assertThat(requests.get()).as("首轮始终执行:短路不许让任何品牌一次都没被查过")
.isGreaterThanOrEqualTo(brands.size());
@@ -149,7 +154,7 @@ class BrandCheckClientTest {
BrandCheckClient client = newClient(server, 3);
BrandCheckClient.BrandCheckBatchResult result =
client.checkAll(List.of("ok1", "bad", "ok2", "ok3"), "Terms");
client.checkAll(List.of("ok1", "bad", "ok2", "ok3"), "Terms", 7L);
assertThat(badAttempts.get()).as("同批有成功品牌时,失败品牌仍跑满整条阶梯").isEqualTo(3);
assertThat(result.queryFaildData()).containsExactly("bad");
@@ -164,7 +169,7 @@ class BrandCheckClientTest {
props.setPath("/brand_check");
props.setRetryTimes(retryTimes);
props.setRetryIntervalMillis(1);
return new BrandCheckClient(props, null);
return new BrandCheckClient(props, null, stubbedUserSecrets());
}
/** 重试阶梯可调的构造:用于验证「耗时预算掐的是重试,不是首轮」。 */
@@ -175,7 +180,14 @@ class BrandCheckClientTest {
props.setRetryTimes(retryTimes);
props.setRetryIntervalMillis(retryIntervalMillis);
props.setTotalTimeoutMillis(totalTimeoutMillis);
return new BrandCheckClient(props, null);
return new BrandCheckClient(props, null, stubbedUserSecrets());
}
/** 有真实 HTTP 断言的用例必须桩出非空代理,否则客户端零请求短路、阶梯与指标全测不到。 */
private UserApiSecretService stubbedUserSecrets() {
UserApiSecretService secrets = mock(UserApiSecretService.class);
when(secrets.findPlainValue(anyLong(), anyString())).thenReturn("http://user:pass@127.0.0.1:9");
return secrets;
}
@Test
@@ -188,12 +200,12 @@ class BrandCheckClientTest {
try {
// 阶梯 20/40/60…:跑满 10 次要 0.9 秒,60ms 预算只够跑到第 2~3 次。
BrandCheckClient unlimited = newClient(server, 10, 20, 0);
unlimited.checkAll(List.of("Apple"), "Terms");
unlimited.checkAll(List.of("Apple"), "Terms", 7L);
int attemptsWithoutBudget = attempts.get();
attempts.set(0);
BrandCheckClient client = newClient(server, 10, 20, 0);
BrandCheckClient.BrandCheckBatchResult result = client.checkAll(List.of("Apple"), "Terms", 60L);
BrandCheckClient.BrandCheckBatchResult result = client.checkAll(List.of("Apple"), "Terms", 60L, 7L);
assertThat(attemptsWithoutBudget).as("不限制时跑满整条重试阶梯").isEqualTo(10);
assertThat(attempts.get()).as("预算用尽即停重试,但首轮始终执行")
@@ -215,7 +227,7 @@ class BrandCheckClientTest {
try {
BrandCheckClient client = newClient(server, 10, 20, 60);
client.checkAll(List.of("Apple"), "Terms");
client.checkAll(List.of("Apple"), "Terms", 7L);
assertThat(attempts.get()).as("两参重载按 total-timeout-millis 兜底,未退化也不越界")
.isBetween(1, 9);
@@ -238,7 +250,7 @@ class BrandCheckClientTest {
BrandCheckClient client = newClient(server, 3, 200, 0);
List<String> brands = List.of("b1", "b2", "b3", "b4");
BrandCheckClient.BrandCheckBatchResult result = client.checkAll(brands, "Terms", 1L);
BrandCheckClient.BrandCheckBatchResult result = client.checkAll(brands, "Terms", 1L, 7L);
assertThat(requests.get()).as("预算过期后每个品牌仍各发一次真实请求").isEqualTo(brands.size());
assertThat(result.brands()).as("降级不丢品牌,入参集合原样带回").containsExactlyElementsOf(brands);
@@ -1,6 +1,7 @@
package com.nanri.aiimage.modules.brand.client;
import com.nanri.aiimage.config.BrandCheckProperties;
import com.nanri.aiimage.modules.usersecret.service.UserApiSecretService;
import com.sun.net.httpserver.HttpServer;
import org.junit.jupiter.api.Test;
@@ -14,6 +15,10 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* 一批标题的品牌校验(外观专利热路径:原先每行各调一次 checkTitleText,
@@ -34,7 +39,7 @@ class BrandCheckClientTitleBatchTest {
HttpServer server = startBrandCheckServer(brandResponses(hits));
try {
List<BrandCheckClient.BrandCheckBatchResult> results =
newClient(server, 3).checkTitleTexts(List.of("阿凡达,玩具", "小米,充电宝"), "Terms");
newClient(server, 3).checkTitleTexts(List.of("阿凡达,玩具", "小米,充电宝"), "Terms", 7L);
assertThat(results).hasSize(2);
assertThat(results.get(0).hasFailedData()).as("第 1 行含侵权词").isTrue();
@@ -59,7 +64,7 @@ class BrandCheckClientTitleBatchTest {
});
try {
List<BrandCheckClient.BrandCheckBatchResult> results =
newClient(server, 3).checkTitleTexts(List.of("阿凡达,玩具", "阿凡达,手机", "阿凡达,周边"), "Terms");
newClient(server, 3).checkTitleTexts(List.of("阿凡达,玩具", "阿凡达,手机", "阿凡达,周边"), "Terms", 7L);
assertThat(counters.get("阿凡达").get()).as("跨行同一个词只查一次").isEqualTo(1);
assertThat(counters).hasSize(4);
@@ -80,7 +85,7 @@ class BrandCheckClientTitleBatchTest {
Map.of("阿凡达", "{\"faild_data\":[\"阿凡达\"],\"query_faild_data\":[]}")));
try {
List<BrandCheckClient.BrandCheckBatchResult> results =
newClient(server, 3).checkTitleTexts(List.of("", "阿凡达"), "Terms");
newClient(server, 3).checkTitleTexts(List.of("", "阿凡达"), "Terms", 7L);
assertThat(results.get(0).brands()).as("空标题行的词集合必须为空,否则判定从标题原文变成无侵权").isEmpty();
assertThat(results.get(0).hasFailedData()).isFalse();
@@ -100,7 +105,7 @@ class BrandCheckClientTitleBatchTest {
HttpServer server = startBrandCheckServer(brandResponses(hits));
try {
List<BrandCheckClient.BrandCheckBatchResult> results =
newClient(server, 2).checkTitleTexts(List.of("任天堂,主机", "小米,充电宝"), "Terms");
newClient(server, 2).checkTitleTexts(List.of("任天堂,主机", "小米,充电宝"), "Terms", 7L);
assertThat(results.get(0).hasQueryFailedData()).isTrue();
assertThat(results.get(1).hasQueryFailedData()).as("别行的查询失败不得扩散").isFalse();
@@ -130,7 +135,9 @@ class BrandCheckClientTitleBatchTest {
props.setPath("/brand_check");
props.setRetryTimes(retryTimes);
props.setRetryIntervalMillis(1);
return new BrandCheckClient(props, null);
UserApiSecretService secrets = mock(UserApiSecretService.class);
when(secrets.findPlainValue(anyLong(), anyString())).thenReturn("http://user:pass@127.0.0.1:9");
return new BrandCheckClient(props, null, secrets);
}
private HttpServer startBrandCheckServer(com.sun.net.httpserver.HttpHandler handler) throws IOException {
@@ -27,7 +27,6 @@ import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.LinkedHashMap;
@@ -171,7 +170,13 @@ class BrandTaskAbortServiceTest {
private void assertPartialAssembly(String initialStatus) throws Exception {
File sourceFile = tempDir.resolve("source.xlsx").toFile();
Files.write(sourceFile.toPath(), new byte[]{1, 2, 3});
writeSourceWorkbook(sourceFile, new String[][]{
{"品牌", "ASIN"},
{"A", "B0A1"},
{"A", "B0A2"},
{"B", "B0B1"},
{"C", "B0C1"},
});
String fileUrl = sourceFile.getAbsolutePath();
when(brandCrawlTaskMapper.selectById(2309L)).thenReturn(task(initialStatus, fileUrl));
TaskDistributedLockService.LockHandle handle = mock(TaskDistributedLockService.LockHandle.class);
@@ -222,7 +227,26 @@ class BrandTaskAbortServiceTest {
assertNotNull(undetected, "部分结果应包含「未检测品牌」sheet");
assertEquals("B", undetected.getRow(1).getCell(0).getStringCellValue());
assertEquals("C", undetected.getRow(2).getCell(0).getStringCellValue());
assertEquals(1, workbook.getSheet("Sheet1").getLastRowNum(), "主 sheet 只剩表头 + 已检测品牌 A 一行");
org.apache.poi.ss.usermodel.Sheet main = workbook.getSheet("Sheet1");
assertEquals(2, main.getLastRowNum(),
"主 sheet = 表头 + 已检测品牌 A 的全部行:同品牌两个 ASIN 都必须在(2735 复盘)");
assertEquals("B0A1", main.getRow(1).getCell(1).getStringCellValue());
assertEquals("B0A2", main.getRow(2).getCell(1).getStringCellValue());
}
private void writeSourceWorkbook(File file, String[][] data) throws Exception {
try (org.apache.poi.xssf.usermodel.XSSFWorkbook workbook = new org.apache.poi.xssf.usermodel.XSSFWorkbook()) {
org.apache.poi.ss.usermodel.Sheet sheet = workbook.createSheet("Sheet1");
for (int r = 0; r < data.length; r++) {
org.apache.poi.ss.usermodel.Row row = sheet.createRow(r);
for (int c = 0; c < data[r].length; c++) {
row.createCell(c).setCellValue(data[r][c]);
}
}
try (java.io.FileOutputStream out = new java.io.FileOutputStream(file)) {
workbook.write(out);
}
}
}
@Test
@@ -0,0 +1,260 @@
package com.nanri.aiimage.modules.brand.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.nanri.aiimage.common.service.DistributedJobLockService;
import com.nanri.aiimage.config.BrandProgressProperties;
import com.nanri.aiimage.config.StorageProperties;
import com.nanri.aiimage.modules.brand.mapper.BrandCrawlTaskMapper;
import com.nanri.aiimage.modules.brand.model.dto.BrandFileAggregateCacheDto;
import com.nanri.aiimage.modules.brand.model.dto.BrandInvalidBrandDto;
import com.nanri.aiimage.modules.brand.model.dto.BrandParsedFileCacheDto;
import com.nanri.aiimage.modules.brand.model.entity.BrandCrawlTaskEntity;
import com.nanri.aiimage.modules.file.service.oss.OssStorageService;
import com.nanri.aiimage.modules.task.service.TaskDistributedLockService;
import com.nanri.aiimage.modules.task.service.TaskFileJobService;
import com.nanri.aiimage.modules.task.service.TaskProgressSnapshotService;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.Mockito.mock;
/**
* 品牌检测结果出表的行数契约(任务 2735 复盘):查询按品牌去重(同品牌只查一次 WIPO),
* 但同品牌不同 ASIN 是不同商品行,结果文件一行都不能少。
*/
@ExtendWith(MockitoExtension.class)
class BrandTaskServiceResultRowsTest {
@Mock private BrandCrawlTaskMapper brandCrawlTaskMapper;
@Mock private OssStorageService ossStorageService;
@Mock private StorageProperties storageProperties;
@Mock private BrandProgressProperties brandProgressProperties;
@Mock private BrandTaskProgressCacheService brandTaskProgressCacheService;
@Mock private BrandTaskStorageService brandTaskStorageService;
@Mock private DistributedJobLockService distributedJobLockService;
@Mock private TaskDistributedLockService taskDistributedLockService;
@Mock private TaskFileJobService taskFileJobService;
@Mock private TaskProgressSnapshotService taskProgressSnapshotService;
@TempDir
Path tempDir;
@BeforeAll
static void initializeTableInfo() {
TableInfoHelper.initTableInfo(
new MapperBuilderAssistant(new MybatisConfiguration(), ""),
BrandCrawlTaskEntity.class);
}
private BrandTaskService service() {
return new BrandTaskService(brandCrawlTaskMapper, ossStorageService, storageProperties,
brandProgressProperties, brandTaskProgressCacheService,
mock(com.nanri.aiimage.modules.task.service.TaskHeartbeatPositionService.class),
brandTaskStorageService,
distributedJobLockService, taskDistributedLockService, new ObjectMapper(),
taskFileJobService, taskProgressSnapshotService,
mock(com.nanri.aiimage.modules.notification.service.NotificationDispatchService.class));
}
/** 4 数据行:AA 两个不同 ASIN(同品牌)、BB、CC 各一行 */
private File sourceWorkbook() throws Exception {
File file = tempDir.resolve("brand-source.xlsx").toFile();
try (XSSFWorkbook workbook = new XSSFWorkbook()) {
Sheet sheet = workbook.createSheet("Sheet1");
String[][] data = {
{"品牌", "ASIH", "状态", "时间"},
{"Brand: AA", "B001", "", ""},
{"Brand: AA", "B002", "", ""},
{"Brand: BB", "B003", "", ""},
{"Brand: CC", "B004", "", ""},
};
for (int r = 0; r < data.length; r++) {
Row row = sheet.createRow(r);
for (int c = 0; c < data[r].length; c++) {
row.createCell(c).setCellValue(data[r][c]);
}
}
try (FileOutputStream out = new FileOutputStream(file)) {
workbook.write(out);
}
}
return file;
}
private BrandParsedFileCacheDto cachedFile(BrandTaskService.ParsedBrandFile deduped) {
BrandParsedFileCacheDto dto = new BrandParsedFileCacheDto();
dto.setFileUrl("https://oss.example/brand-source.xlsx");
dto.setSheetName(deduped.sheetName());
dto.setColumns(deduped.columns());
dto.setRows(deduped.rows());
return dto;
}
private BrandFileAggregateCacheDto aggregateWithInvalid(String brand) {
BrandFileAggregateCacheDto dto = new BrandFileAggregateCacheDto();
dto.setFileUrl("https://oss.example/brand-source.xlsx");
BrandInvalidBrandDto invalid = new BrandInvalidBrandDto();
invalid.setBrand(brand);
invalid.setCountry("英国");
invalid.setStatus("已注册");
dto.setInvalidBrands(new ArrayList<>(List.of(invalid)));
return dto;
}
private List<String> sheetValues(Sheet sheet, int column) {
List<String> values = new ArrayList<>();
for (int r = 1; r <= sheet.getLastRowNum(); r++) {
Row row = sheet.getRow(r);
if (row != null && row.getCell(column) != null) {
values.add(row.getCell(column).getStringCellValue());
}
}
return values;
}
@Test
void payloadParseDedupesRowsButExpansionParseKeepsEveryRow() throws Exception {
File file = sourceWorkbook();
BrandTaskService service = service();
BrandTaskService.ParsedBrandFile forPayload = service.parseBrandFile(file);
assertEquals(3, forPayload.rows().size(), "回传执行方的行集必须每品牌一行,防按行重查烧代理");
assertEquals(3, forPayload.uniqueBrands().size());
BrandTaskService.ParsedBrandFile forOutput = service.parseBrandFile(file, false);
assertEquals(4, forOutput.rows().size(), "出表行集要保留同品牌不同 ASIN 的全部行");
assertEquals(3, forOutput.uniqueBrands().size(), "查询集仍按品牌去重,与出表模式一致");
}
@Test
void resultWorkbookKeepsEveryAsinRowAndOnlyRemovesJudgedBrands() throws Exception {
File file = sourceWorkbook();
BrandTaskService service = service();
BrandTaskService.ParsedBrandFile deduped = service.parseBrandFile(file);
BrandTaskService.ParsedBrandFile expanded = service.parseBrandFile(file, false);
File output = tempDir.resolve("brand-result.xlsx").toFile();
service.writeBrandWorkbook(output, "Simple", cachedFile(deduped), aggregateWithInvalid("Brand: CC"),
List.of(), expanded.rows());
try (Workbook workbook = WorkbookFactory.create(output)) {
Sheet main = workbook.getSheet("Sheet1");
assertNotNull(main);
List<String> asins = sheetValues(main, 1);
assertEquals(List.of("B001", "B002", "B003"), asins,
"同品牌不同 ASIN 的行都要出;仅不符合品牌 CC 的行移出主表");
Sheet invalid = workbook.getSheet("不符合品牌");
assertNotNull(invalid);
// 这张表用户会直接再传一次,所以出件里的品牌不带 "Brand: " 前缀;
// 上一行 aggregateWithInvalid("Brand: CC") 给的是回传原值(执行方刻意保留),
// 两侧都过 BrandLabel 才命中——摘掉 normalizeBrandSetFromInvalids 里的 strip,
// B004 会留在主表里,用户把"判为不符合"的品牌当成已通过。
assertEquals(List.of("CC"), sheetValues(invalid, 0));
assertNull(workbook.getSheet("未检测品牌"), "成功收尾没有未检测 sheet");
}
}
@Test
void partialResultMovesAllUndetectedRowsToTheirOwnSheet() throws Exception {
File file = sourceWorkbook();
BrandTaskService service = service();
BrandTaskService.ParsedBrandFile deduped = service.parseBrandFile(file);
BrandTaskService.ParsedBrandFile expanded = service.parseBrandFile(file, false);
File output = tempDir.resolve("brand-partial.xlsx").toFile();
service.writeBrandWorkbook(output, "Simple", cachedFile(deduped), aggregateWithInvalid("Brand: CC"),
List.of("Brand: BB"), expanded.rows());
try (Workbook workbook = WorkbookFactory.create(output)) {
Sheet main = workbook.getSheet("Sheet1");
assertEquals(List.of("B001", "B002"), sheetValues(main, 1));
Sheet undetected = workbook.getSheet("未检测品牌");
assertNotNull(undetected, "未检测品牌的行要整行挪进独立 sheet");
assertEquals(List.of("B003"), sheetValues(undetected, 1));
}
}
@Test
void blankBrandRowsAreAlwaysKeptInBothModes() throws Exception {
File file = tempDir.resolve("brand-blank.xlsx").toFile();
try (XSSFWorkbook workbook = new XSSFWorkbook()) {
Sheet sheet = workbook.createSheet("Sheet1");
String[][] data = {
{"品牌", "ASIH", "状态", "时间"},
{"", "B001", "", ""},
{"", "B002", "", ""},
};
for (int r = 0; r < data.length; r++) {
Row row = sheet.createRow(r);
for (int c = 0; c < data[r].length; c++) {
row.createCell(c).setCellValue(data[r][c]);
}
}
try (FileOutputStream out = new FileOutputStream(file)) {
workbook.write(out);
}
}
BrandTaskService service = service();
assertEquals(2, service.parseBrandFile(file).rows().size(), "空品牌行不参与品牌去重,两种模式都保留");
assertEquals(2, service.parseBrandFile(file, false).rows().size());
assertEquals(0, service.parseBrandFile(file).uniqueBrands().size());
}
/**
* 品牌列在解析落 row map 那一处就洗一次:查询集 uniqueBrands、与执行方回传值的匹配、
* 出件里那一格拿到的必须是同一个字符串(只在写出端剥会让比对两边分家)。
* 摘掉 onRow 里的 BrandLabel.strip,前两条会各自读到 "Brand: AA";第三条更糟——
* 纯标签值被当成一个可查询的品牌送进上游,正是 2026-10-08 那批 {@code undefined field Brand}
* 500 的来源(单日 19,247 次)。
*/
@Test
void parseStripsTheBylineLabelOnceSoQueryAndOutputShareOneValue() throws Exception {
File file = tempDir.resolve("brand-label-mix.xlsx").toFile();
try (XSSFWorkbook workbook = new XSSFWorkbook()) {
Sheet sheet = workbook.createSheet("Sheet1");
String[][] data = {
{"品牌", "ASIH", "状态", "时间"},
{"Brand: AA", "B001", "", ""},
{"Brands: BB", "B002", "", ""},
{"Brand:", "B003", "", ""},
};
for (int r = 0; r < data.length; r++) {
Row row = sheet.createRow(r);
for (int c = 0; c < data[r].length; c++) {
row.createCell(c).setCellValue(data[r][c]);
}
}
try (FileOutputStream out = new FileOutputStream(file)) {
workbook.write(out);
}
}
BrandTaskService service = service();
BrandTaskService.ParsedBrandFile parsed = service.parseBrandFile(file);
assertEquals(List.of("AA", "Brands: BB"), parsed.uniqueBrands(),
"行首标签剥掉;复数 Brands: 是真实品牌写法要原样留;纯标签值不算一个品牌");
assertEquals("AA", parsed.rows().get(0).get("品牌"), "出件那一格与查询集同口径");
assertEquals(3, parsed.rows().size(), "纯标签行照常出件,只是不拿空品牌去查询");
}
}
@@ -0,0 +1,99 @@
package com.nanri.aiimage.modules.brand.support;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* 品牌检测失败原因的分类与用户文案:判据全部取自 2026-10-20 现网真出现过的句子
* ({@code biz_collectdata_brand_recheck.last_error} 与 Java brand-check warn 日志),
* 不是设想出来的样例。
*
* <p>这条链要守住的只有一件事:**代理侧的原因不许说成上游的锅**。改之前补测耗尽通知一律写
* 「上游商标库持续不可用,建议稍后重跑」,而现网 12 分钟内 18 条是"key 处于冷却"、4 条是
* 「余额不足」——都是用户自己的套餐,重跑必然还是失败。
*/
class BrandCheckFailureNoticeTest {
@Test
void 空原因按上游算_连接层失败拿不到上游原话() {
assertThat(BrandCheckFailureNotice.classify(null)).isEqualTo(BrandCheckFailureNotice.Kind.UPSTREAM);
assertThat(BrandCheckFailureNotice.classify(" ")).isEqualTo(BrandCheckFailureNotice.Kind.UPSTREAM);
assertThat(BrandCheckFailureNotice.classify("socket timeout")).isEqualTo(BrandCheckFailureNotice.Kind.UPSTREAM);
}
@Test
void 未配置代理是独立一类() {
assertThat(BrandCheckFailureNotice.classify("用户未配置代理"))
.isEqualTo(BrandCheckFailureNotice.Kind.PROXY_NOT_CONFIGURED);
}
@Test
void 供应商拒付类话术归到套餐() {
assertThat(BrandCheckFailureNotice.classify("余额不足"))
.isEqualTo(BrandCheckFailureNotice.Kind.PROXY_PACKAGE_EXHAUSTED);
assertThat(BrandCheckFailureNotice.classify("代理提取失败(套餐已过期)"))
.isEqualTo(BrandCheckFailureNotice.Kind.PROXY_PACKAGE_EXHAUSTED);
assertThat(BrandCheckFailureNotice.classify("代理提取失败(套餐不存在)"))
.isEqualTo(BrandCheckFailureNotice.Kind.PROXY_PACKAGE_EXHAUSTED);
assertThat(BrandCheckFailureNotice.classify("账户欠费"))
.isEqualTo(BrandCheckFailureNotice.Kind.PROXY_PACKAGE_EXHAUSTED);
}
@Test
void 冷却窗口归到冷却() {
assertThat(BrandCheckFailureNotice.classify("全部 1 把代理 key 处于冷却,最早还要等 299 秒"))
.isEqualTo(BrandCheckFailureNotice.Kind.PROXY_COOLDOWN);
}
@Test
void 冷却里带着拒付根因时取根因那一类() {
// 一把 key 因余额不足被拒后,整批都写成"处于冷却":只报冷却会把用户引向"等一等",
// 而真动作是充值/换链接。
assertThat(BrandCheckFailureNotice.classify("全部 2 把代理 key 处于冷却(余额不足),最早还要等 299 秒"))
.isEqualTo(BrandCheckFailureNotice.Kind.PROXY_PACKAGE_EXHAUSTED);
}
@Test
void 出口被上游拒单独一类因为它要换的是链接不是套餐() {
assertThat(BrandCheckFailureNotice.classify("上游拒绝代理出口 IP,换 IP 重试仍未放行"))
.isEqualTo(BrandCheckFailureNotice.Kind.PROXY_EGRESS_REJECTED);
}
@Test
void 技术性失败_提取没结果_请求失败_解密失败() {
assertThat(BrandCheckFailureNotice.classify("代理提取未返回可用 IP"))
.isEqualTo(BrandCheckFailureNotice.Kind.TECHNICAL);
assertThat(BrandCheckFailureNotice.classify("代理请求失败: connection reset"))
.isEqualTo(BrandCheckFailureNotice.Kind.TECHNICAL);
assertThat(BrandCheckFailureNotice.classify(
"查询或解密失败: 未找到 node 命令,请确保已安装 Node.js 并添加到 PATH"))
.isEqualTo(BrandCheckFailureNotice.Kind.TECHNICAL);
}
@Test
void 每一类都给得出可执行动作() {
for (BrandCheckFailureNotice.Kind kind : BrandCheckFailureNotice.Kind.values()) {
String message = BrandCheckFailureNotice.userMessage(kind);
assertThat(message).as("类别 %s 必须有话术", kind).isNotBlank();
if (kind.name().startsWith("PROXY_")) {
assertThat(message).as("代理侧的类别必须把用户带到「代理设置」门口:%s", message)
.contains("代理设置");
// 禁的是"把账算到别人头上"这两句:不许说成上游的锅,也不许说成库坏了让用户白等。
// 「代理出口 IP 被商标库拒绝」里出现"商标库"是事实陈述(拒绝的就是那个库),
// 动作仍然指向换提取链接,所以不在禁列——旧文案的毛病是说库「持续不可用」。
assertThat(message).as("代理侧的原因不许说成上游的锅:%s", message)
.doesNotContain("上游")
.doesNotContain("不可用");
} else {
assertThat(message).as("非代理类别应当给出自动补测的兜底:%s", message)
.contains("自动重试");
}
}
}
@Test
void 类别缺失时退回上游那句而不是空话() {
assertThat(BrandCheckFailureNotice.userMessage(null)).contains("自动重试");
}
}
@@ -3,6 +3,7 @@ package com.nanri.aiimage.modules.collectdata.service;
import com.nanri.aiimage.common.service.DistributedJobLockService;
import com.nanri.aiimage.config.CollectDataBrandRecheckProperties;
import com.nanri.aiimage.modules.brand.client.BrandCheckClient;
import com.nanri.aiimage.modules.brand.support.BrandCheckFailureNotice;
import com.nanri.aiimage.modules.collectdata.model.entity.CollectDataBrandRecheckEntity;
import com.nanri.aiimage.modules.collectdata.service.CollectDataBrandRecheckInjector.GroupOutcome;
import com.nanri.aiimage.modules.notification.service.NotificationDispatchService;
@@ -117,9 +118,9 @@ class CollectDataBrandRecheckSchedulerTest {
scheduler.runRound();
verify(recheckService).postponeWithoutAttempt(List.of(e1), 30);
verify(brandCheckClient, never()).checkAll(anyList(), anyString());
verify(brandCheckClient, never()).checkAll(anyList(), anyString(), any());
verify(notificationDispatchService, never()).pushRecheckOutcome(
any(), any(), anyString(), anyString(), anyInt(), anyInt(), anyInt(), anyInt());
any(), any(), anyString(), anyString(), anyInt(), anyInt(), anyInt(), anyInt(), any());
}
@Test
@@ -131,7 +132,7 @@ class CollectDataBrandRecheckSchedulerTest {
scheduler.runRound();
verify(recheckService).markExhausted(e1, "任务不存在(可能已被清理)");
verify(brandCheckClient, never()).checkAll(anyList(), anyString());
verify(brandCheckClient, never()).checkAll(anyList(), anyString(), any());
}
@Test
@@ -144,7 +145,7 @@ class CollectDataBrandRecheckSchedulerTest {
scheduler.runRound();
verify(recheckService).postponeWithoutAttempt(List.of(e1), 30);
verify(brandCheckClient, never()).checkAll(anyList(), anyString());
verify(brandCheckClient, never()).checkAll(anyList(), anyString(), any());
}
@Test
@@ -155,8 +156,8 @@ class CollectDataBrandRecheckSchedulerTest {
when(fileTaskMapper.selectById(100L)).thenReturn(task(100L, "SUCCESS"));
when(taskDistributedLockService.acquire("COLLECT_DATA", 100L, 2000L)).thenReturn(taskLock);
// "Nike " 带尾随空格:验证取品牌时按归一化口径去查(入队时已归一化,防御性兜底)
when(brandCheckClient.checkAll(anyList(), eq("Terms"))).thenReturn(
new BrandCheckClient.BrandCheckBatchResult(List.of(), List.of("Zara"), List.of()));
when(brandCheckClient.checkAll(anyList(), eq("Terms"), any())).thenReturn(
new BrandCheckClient.BrandCheckBatchResult(List.of(), List.of("Zara"), List.of(), ""));
when(injector.apply(any(FileTaskEntity.class), any())).thenReturn(
new GroupOutcome(9L, 3, 1));
@@ -167,7 +168,28 @@ class CollectDataBrandRecheckSchedulerTest {
verify(recheckService, never()).markAttempted(any(), anyString());
verify(taskFileJobService).enqueueAssembleResult(100L, "COLLECT_DATA", 9L, "task:100");
verify(notificationDispatchService).pushRecheckOutcome(
961L, 100L, "COLLECT_DATA", "COLLECT_DATA-100", 3, 1, 0, 0);
961L, 100L, "COLLECT_DATA", "COLLECT_DATA-100", 3, 1, 0, 0,
BrandCheckFailureNotice.Kind.UPSTREAM);
}
@Test
void runRoundPassesProxyCooldownKindThroughToNotification() {
// 上游回来的原因就是"全部 key 处于冷却"时,通知必须拿到冷却这一类,
// 而不是继续按"上游商标库不可用"对用户说话。
CollectDataBrandRecheckEntity e1 = entry(1, 100L, "zara");
when(recheckService.listDue(any(), anyInt())).thenReturn(List.of(e1));
when(fileTaskMapper.selectById(100L)).thenReturn(task(100L, "SUCCESS"));
when(taskDistributedLockService.acquire("COLLECT_DATA", 100L, 2000L)).thenReturn(taskLock);
when(brandCheckClient.checkAll(anyList(), eq("Terms"), any())).thenReturn(
new BrandCheckClient.BrandCheckBatchResult(List.of(), List.of(), List.of("zara"),
"全部 1 把代理 key 处于冷却,最早还要等 299 秒"));
scheduler.runRound();
verify(recheckService).markAttempted(e1, "全部 1 把代理 key 处于冷却,最早还要等 299 秒");
verify(notificationDispatchService).pushRecheckOutcome(
961L, 100L, "COLLECT_DATA", "COLLECT_DATA-100", 0, 0, 1, 0,
BrandCheckFailureNotice.Kind.PROXY_COOLDOWN);
}
@Test
@@ -176,8 +198,8 @@ class CollectDataBrandRecheckSchedulerTest {
when(recheckService.listDue(any(), anyInt())).thenReturn(List.of(e1));
when(fileTaskMapper.selectById(100L)).thenReturn(task(100L, "SUCCESS"));
when(taskDistributedLockService.acquire("COLLECT_DATA", 100L, 2000L)).thenReturn(taskLock);
when(brandCheckClient.checkAll(anyList(), eq("Terms"))).thenReturn(
new BrandCheckClient.BrandCheckBatchResult(List.of(), List.of(), List.of("zara")));
when(brandCheckClient.checkAll(anyList(), eq("Terms"), any())).thenReturn(
new BrandCheckClient.BrandCheckBatchResult(List.of(), List.of(), List.of("zara"), ""));
scheduler.runRound();
@@ -185,7 +207,8 @@ class CollectDataBrandRecheckSchedulerTest {
verify(injector, never()).apply(any(), any());
verify(taskFileJobService, never()).enqueueAssembleResult(anyLong(), anyString(), anyLong(), anyString());
verify(notificationDispatchService).pushRecheckOutcome(
961L, 100L, "COLLECT_DATA", "COLLECT_DATA-100", 0, 0, 1, 0);
961L, 100L, "COLLECT_DATA", "COLLECT_DATA-100", 0, 0, 1, 0,
BrandCheckFailureNotice.Kind.UPSTREAM);
}
@Test
@@ -194,7 +217,7 @@ class CollectDataBrandRecheckSchedulerTest {
when(recheckService.listDue(any(), anyInt())).thenReturn(List.of(e1));
when(fileTaskMapper.selectById(100L)).thenReturn(task(100L, "FAILED"));
when(taskDistributedLockService.acquire("COLLECT_DATA", 100L, 2000L)).thenReturn(taskLock);
when(brandCheckClient.checkAll(anyList(), eq("Terms")))
when(brandCheckClient.checkAll(anyList(), eq("Terms"), any()))
.thenThrow(new RuntimeException("connection reset"));
scheduler.runRound();
@@ -209,8 +232,8 @@ class CollectDataBrandRecheckSchedulerTest {
when(recheckService.listDue(any(), anyInt())).thenReturn(List.of(e1));
when(fileTaskMapper.selectById(100L)).thenReturn(task(100L, "SUCCESS"));
when(taskDistributedLockService.acquire("COLLECT_DATA", 100L, 2000L)).thenReturn(taskLock);
when(brandCheckClient.checkAll(anyList(), eq("Terms"))).thenReturn(
new BrandCheckClient.BrandCheckBatchResult(List.of(), List.of(), List.of()));
when(brandCheckClient.checkAll(anyList(), eq("Terms"), any())).thenReturn(
new BrandCheckClient.BrandCheckBatchResult(List.of(), List.of(), List.of(), ""));
when(injector.apply(any(FileTaskEntity.class), any()))
.thenThrow(new RuntimeException("结果明细写入失败"));
@@ -220,7 +243,7 @@ class CollectDataBrandRecheckSchedulerTest {
verify(taskFileJobService, never()).enqueueAssembleResult(anyLong(), anyString(), anyLong(), anyString());
// 注入失败:无修复、无收口,不打扰用户
verify(notificationDispatchService, never()).pushRecheckOutcome(
any(), any(), anyString(), anyString(), anyInt(), anyInt(), anyInt(), anyInt());
any(), any(), anyString(), anyString(), anyInt(), anyInt(), anyInt(), anyInt(), any());
}
@Test
@@ -232,9 +255,9 @@ class CollectDataBrandRecheckSchedulerTest {
when(recheckService.listDue(any(), anyInt())).thenReturn(List.of(f1, f2, f3, later));
when(fileTaskMapper.selectById(100L)).thenReturn(task(100L, "SUCCESS"));
when(taskDistributedLockService.acquire("COLLECT_DATA", 100L, 2000L)).thenReturn(taskLock);
when(brandCheckClient.checkAll(anyList(), eq("Terms"))).thenReturn(
when(brandCheckClient.checkAll(anyList(), eq("Terms"), any())).thenReturn(
new BrandCheckClient.BrandCheckBatchResult(List.of(), List.of(),
List.of("bad-one", "bad-two", "bad-three")));
List.of("bad-one", "bad-two", "bad-three"), ""));
scheduler.runRound();
@@ -243,7 +266,7 @@ class CollectDataBrandRecheckSchedulerTest {
verify(recheckService).markAttempted(f2, "query_faild_data 持续非空");
verify(recheckService).markAttempted(f3, "query_faild_data 持续非空");
// 第二组整组顺延:不实测、不计数
verify(brandCheckClient, org.mockito.Mockito.times(1)).checkAll(anyList(), anyString());
verify(brandCheckClient, org.mockito.Mockito.times(1)).checkAll(anyList(), anyString(), any());
verify(recheckService).postponeWithoutAttempt(List.of(later), 30);
verify(recheckService, never()).markInjected(any());
verify(recheckService, never()).markRejected(any());
@@ -2,6 +2,7 @@ package com.nanri.aiimage.modules.collectdata.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.modules.collectdata.model.dto.CollectDataSummaryRowDto;
import com.nanri.aiimage.modules.collectdata.model.vo.CollectDataResultRowVo;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
@@ -34,4 +35,30 @@ class CollectDataExcelAssemblyServiceTest {
assertThat(sheet.getRow(1).getCell(6).getNumericCellValue()).isEqualTo(3);
}
}
/**
* 出件这一端的品牌列必须是没有标签前缀的:这份结果文件是用户的下一份上传物,
* 漏剥一次就把脏值送回链路里,清洗的账也随之作废;改口径之前落库的历史明细里也仍带着前缀。
*/
@Test
void stripsAmazonBylinePrefixFromBrandColumn() throws Exception {
File output = tempDir.resolve("collect-data-brand-label.xlsx").toFile();
new CollectDataExcelAssemblyService().writeWorkbook(output,
List.of(row("Brand: Nike", "B000000001"), row("品牌:耐克", "B000000002")),
List.of(), List.of());
try (Workbook workbook = WorkbookFactory.create(output)) {
Sheet detail = workbook.getSheet("采集数据结果");
assertThat(detail.getRow(1).getCell(0).getStringCellValue()).isEqualTo("Nike");
assertThat(detail.getRow(2).getCell(0).getStringCellValue()).isEqualTo("耐克");
}
}
private static CollectDataResultRowVo row(String brand, String asin) {
CollectDataResultRowVo row = new CollectDataResultRowVo();
row.setBrand(brand);
row.setAsin(asin);
return row;
}
}
@@ -5,6 +5,8 @@ import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import com.nanri.aiimage.modules.collectdata.model.dto.CollectDataSubmitRowDto;
import com.nanri.aiimage.modules.collectdata.model.vo.CollectDataResultRowVo;
import com.nanri.aiimage.modules.collectdata.model.vo.CollectDataDashboardVo;
import com.nanri.aiimage.modules.collectdata.model.vo.CollectDataTaskBatchVo;
import com.nanri.aiimage.modules.task.mapper.FileResultMapper;
@@ -219,6 +221,25 @@ class CollectDataServiceTest {
verify(taskFileJobService, never()).enqueueAssembleResult(any(), any(), any(), any());
}
// 亚马逊详情页把卖家名渲染成 "Brand: XXX",用户复制、客户端就原样回传这种署名值。
// 分片回传是脏值进服务端的唯一入口:品牌检查、结果明细落库、出件读的都是这里产出的 VO,
// 所以标签必须在进模型这一端就被剥掉(口径只在 BrandLabel 一处)。
@Test
void submittedBrandLosesTheAmazonBylinePrefixAtIngest() throws Exception {
CollectDataSubmitRowDto byline = objectMapper.readValue(
"{\"品牌\":\"Brand: NIKE\"}", CollectDataSubmitRowDto.class);
CollectDataSubmitRowDto lookalike = objectMapper.readValue(
"{\"brand_name\":\"Brands: Nike\"}", CollectDataSubmitRowDto.class);
List<CollectDataResultRowVo> rows = ReflectionTestUtils.invokeMethod(
service, "normalizeSubmitRows", List.of(byline, lookalike));
assertThat(rows).hasSize(2);
assertThat(rows.get(0).getBrand()).isEqualTo("NIKE");
// "Brands:" 是真实品牌写法,不是字段标签
assertThat(rows.get(1).getBrand()).isEqualTo("Brands: Nike");
}
private static FileTaskEntity staleTask(long taskId) {
FileTaskEntity task = new FileTaskEntity();
task.setId(taskId);
@@ -143,8 +143,8 @@ class CollectDataServiceTxBoundaryTest {
row.setAsin("B0COLLECT1");
lenient().when(collectDataBatchQuery.filter(any(), any())).thenReturn(
new CollectDataBatchQuery.FilterResult(List.of(row), 0, 0));
lenient().when(brandBatchFilter.filter(any())).thenReturn(
new CollectDataBrandBatchFilter.BrandBatchOutcome(List.of(), List.of(), List.of(row)));
lenient().when(brandBatchFilter.filter(any(), any())).thenReturn(
new CollectDataBrandBatchFilter.BrandBatchOutcome(List.of(), List.of(), List.of(row), ""));
lenient().when(resultItemBatchWriter.upsertAccepted(anyLong(), anyLong(), anyString(), anyInt(), any(), anyString()))
.thenReturn(new CollectDataResultItemBatchWriter.UpsertCounts(1, 0, 1));
lenient().when(resultDetailCodec.encodeChunk(any())).thenReturn("{\"chunk\":1}");
@@ -199,8 +199,8 @@ class CollectDataServiceTxBoundaryTest {
void brandRejectedRowsWrittenToInvalidWriter() {
CollectDataResultRowVo bad = new CollectDataResultRowVo();
bad.setAsin("B0INVALID");
when(brandBatchFilter.filter(any())).thenReturn(
new CollectDataBrandBatchFilter.BrandBatchOutcome(List.of(bad), List.of(), List.of()));
when(brandBatchFilter.filter(any(), any())).thenReturn(
new CollectDataBrandBatchFilter.BrandBatchOutcome(List.of(bad), List.of(), List.of(), ""));
service.submitResult(TASK_ID, submitRequest());
@@ -211,8 +211,8 @@ class CollectDataServiceTxBoundaryTest {
void brandQueryFailedRowsNotWrittenToInvalidWriter() {
CollectDataResultRowVo queryFailed = new CollectDataResultRowVo();
queryFailed.setAsin("B0QUERYFAIL");
when(brandBatchFilter.filter(any())).thenReturn(
new CollectDataBrandBatchFilter.BrandBatchOutcome(List.of(), List.of(queryFailed), List.of()));
when(brandBatchFilter.filter(any(), any())).thenReturn(
new CollectDataBrandBatchFilter.BrandBatchOutcome(List.of(), List.of(queryFailed), List.of(), ""));
service.submitResult(TASK_ID, submitRequest());
@@ -223,8 +223,8 @@ class CollectDataServiceTxBoundaryTest {
void emptyRejectedOutcomeSkipsInvalidWriter() {
CollectDataResultRowVo accepted = new CollectDataResultRowVo();
accepted.setAsin("B0OK");
when(brandBatchFilter.filter(any())).thenReturn(
new CollectDataBrandBatchFilter.BrandBatchOutcome(List.of(), List.of(), List.of(accepted)));
when(brandBatchFilter.filter(any(), any())).thenReturn(
new CollectDataBrandBatchFilter.BrandBatchOutcome(List.of(), List.of(), List.of(accepted), ""));
service.submitResult(TASK_ID, submitRequest());
@@ -337,11 +337,11 @@ class CollectDataSubmitResultSnapshotTest {
+ " dedupe=0 invalid=0");
return new CollectDataBatchQuery.FilterResult(kept, 0, 0);
});
when(brandFilter.filter(anyList())).thenAnswer(invocation -> {
when(brandFilter.filter(anyList(), any())).thenAnswer(invocation -> {
@SuppressWarnings("unchecked")
List<CollectDataResultRowVo> rows = invocation.getArgument(0);
f.events.add("outsideLock brandFilter accepted=" + rows.size() + " rejected=0 queryFailed=0");
return new CollectDataBrandBatchFilter.BrandBatchOutcome(List.of(), List.of(), rows);
return new CollectDataBrandBatchFilter.BrandBatchOutcome(List.of(), List.of(), rows, "");
});
doAnswer(invocation -> {
@SuppressWarnings("unchecked")
@@ -42,22 +42,22 @@ class CollectDataBrandBatchFilterTest {
@Test
void test_task_046_brand_normal_default_path() {
// 正常输入:非空品牌批次发起检查,失败品牌行 rejected、其余 accepted。
when(brandCheckClient.checkAll(anyList(), any(), anyLong())).thenReturn(
when(brandCheckClient.checkAll(anyList(), any(), anyLong(), any())).thenReturn(
new BrandCheckClient.BrandCheckBatchResult(
List.of(), List.of("Zara"), List.of()));
List.of(), List.of("Zara"), List.of(), ""));
CollectDataBrandBatchFilter.BrandBatchOutcome outcome = filter.filter(List.of(
row("B000000001", "Zara"),
row("B000000002", "Nike"),
row("B000000003", "H&M")
));
), 7L);
assertEquals(1, outcome.rejected().size(), "失败品牌行进入 rejected");
assertEquals("B000000001", outcome.rejected().get(0).getAsin());
assertEquals(2, outcome.accepted().size(), "其余行 accepted");
assertEquals("B000000002", outcome.accepted().get(0).getAsin(), "accepted 顺序稳定");
assertEquals(0, outcome.queryFailed().size(), "无查询失败行");
verify(brandCheckClient).checkAll(anyList(), any(), anyLong());
verify(brandCheckClient).checkAll(anyList(), any(), anyLong(), any());
}
@Test
@@ -67,74 +67,74 @@ class CollectDataBrandBatchFilterTest {
for (int i = 0; i < 120; i++) {
rows.add(row("B" + String.format("%09d", i + 1), i % 10 == 0 ? "bad-brand" : "good-" + (i / 10)));
}
when(brandCheckClient.checkAll(anyList(), any(), anyLong())).thenReturn(
when(brandCheckClient.checkAll(anyList(), any(), anyLong(), any())).thenReturn(
new BrandCheckClient.BrandCheckBatchResult(
List.of(), List.of("bad-brand"), List.of()));
List.of(), List.of("bad-brand"), List.of(), ""));
CollectDataBrandBatchFilter.BrandBatchOutcome outcome = filter.filter(rows);
CollectDataBrandBatchFilter.BrandBatchOutcome outcome = filter.filter(rows, 7L);
assertEquals(12, outcome.rejected().size(), "每批次 1 个失败品牌行");
assertEquals(108, outcome.accepted().size(), "其余行 accepted");
assertEquals("B000000001", outcome.rejected().get(0).getAsin(), "rejected 顺序稳定");
assertEquals("B000000002", outcome.accepted().get(0).getAsin(), "accepted 顺序稳定");
verify(brandCheckClient, times(12)).checkAll(anyList(), any(), anyLong());
verify(brandCheckClient, times(12)).checkAll(anyList(), any(), anyLong(), any());
}
@Test
void test_task_046_brand_normal_repeated_operation_is_idempotent() {
// 幂等:同一输入重复执行结果一致,不产生重复对象。
when(brandCheckClient.checkAll(anyList(), any(), anyLong())).thenReturn(
when(brandCheckClient.checkAll(anyList(), any(), anyLong(), any())).thenReturn(
new BrandCheckClient.BrandCheckBatchResult(
List.of(), List.of("Nike"), List.of()));
List.of(), List.of("Nike"), List.of(), ""));
List<CollectDataResultRowVo> rows = List.of(
row("B000000001", "Nike"),
row("B000000002", "Adidas")
);
CollectDataBrandBatchFilter.BrandBatchOutcome first = filter.filter(rows);
CollectDataBrandBatchFilter.BrandBatchOutcome second = filter.filter(rows);
CollectDataBrandBatchFilter.BrandBatchOutcome first = filter.filter(rows, 7L);
CollectDataBrandBatchFilter.BrandBatchOutcome second = filter.filter(rows, 7L);
assertEquals(first.rejected(), second.rejected(), "重复执行 rejected 一致");
assertEquals(first.accepted(), second.accepted(), "重复执行 accepted 一致");
// 缓存生效:第二次执行全部命中缓存,不再发起远程调用。
verify(brandCheckClient, times(1)).checkAll(anyList(), any(), anyLong());
verify(brandCheckClient, times(1)).checkAll(anyList(), any(), anyLong(), any());
}
@Test
void test_task_046_brand_boundary_empty_input() {
// 空输入:空列表返回空结果;全空品牌批次不发起远程检查,行全部 rejected。
CollectDataBrandBatchFilter.BrandBatchOutcome empty = filter.filter(List.of());
CollectDataBrandBatchFilter.BrandBatchOutcome empty = filter.filter(List.of(), 7L);
assertEquals(0, empty.rejected().size() + empty.accepted().size() + empty.queryFailed().size(),
"空列表返回空结果");
verify(brandCheckClient, never()).checkAll(anyList(), any(), anyLong());
verify(brandCheckClient, never()).checkAll(anyList(), any(), anyLong(), any());
CollectDataBrandBatchFilter.BrandBatchOutcome blankBatch = filter.filter(List.of(
row("B000000001", ""), row("B000000002", null), row("B000000003", " ")
));
), 7L);
assertEquals(3, blankBatch.rejected().size(), "空品牌批次行全部 rejected");
assertEquals(0, blankBatch.accepted().size(), "空品牌批次无 accepted");
verify(brandCheckClient, never()).checkAll(anyList(), any(), anyLong());
verify(brandCheckClient, never()).checkAll(anyList(), any(), anyLong(), any());
}
@Test
void test_task_046_brand_boundary_single_item() {
// 单元素:单行单品牌批次正常检查;单行空品牌批次不发远程调用。
when(brandCheckClient.checkAll(anyList(), any(), anyLong())).thenReturn(
when(brandCheckClient.checkAll(anyList(), any(), anyLong(), any())).thenReturn(
new BrandCheckClient.BrandCheckBatchResult(
List.of(), List.of(), List.of()));
List.of(), List.of(), List.of(), ""));
CollectDataBrandBatchFilter.BrandBatchOutcome single = filter.filter(List.of(
row("B000000001", "solo")
));
), 7L);
assertEquals(1, single.accepted().size(), "单行未命中失败归 accepted");
verify(brandCheckClient).checkAll(anyList(), any(), anyLong());
verify(brandCheckClient).checkAll(anyList(), any(), anyLong(), any());
CollectDataBrandBatchFilter.BrandBatchOutcome blank = filter.filter(List.of(
row("B000000002", "")
));
), 7L);
assertEquals(1, blank.rejected().size(), "单行空品牌归 rejected");
// 同实例缓存生效:solo 已查过,空品牌批次无远程调用,总调用保持 1 次。
verify(brandCheckClient, times(1)).checkAll(anyList(), any(), anyLong());
verify(brandCheckClient, times(1)).checkAll(anyList(), any(), anyLong(), any());
}
@Test
@@ -145,50 +145,50 @@ class CollectDataBrandBatchFilterTest {
rows.add(row("B" + String.format("%09d", i + 1), "brand-" + (i % 100)));
}
rows.add(row("B999999999", " "));
when(brandCheckClient.checkAll(anyList(), any(), anyLong())).thenReturn(
when(brandCheckClient.checkAll(anyList(), any(), anyLong(), any())).thenReturn(
new BrandCheckClient.BrandCheckBatchResult(
List.of(), List.of(), List.of()));
List.of(), List.of(), List.of(), ""));
CollectDataBrandBatchFilter.BrandBatchOutcome outcome = filter.filter(rows);
CollectDataBrandBatchFilter.BrandBatchOutcome outcome = filter.filter(rows, 7L);
assertEquals(1, outcome.rejected().size(), "空品牌行归 rejected");
assertEquals(5000, outcome.accepted().size(), "非空品牌行全 accepted");
// 每批次 10 行恰好引入 10 个新品牌,10 批次后 100 品牌全部缓存,后续批次零调用。
verify(brandCheckClient, times(10)).checkAll(anyList(), any(), anyLong());
verify(brandCheckClient, times(10)).checkAll(anyList(), any(), anyLong(), any());
}
@Test
void test_task_046_brand_invalid_input_rejected() {
// 非法参数:checkAll 返回 null 按无失败处理;null 行安全跳过不计数。
when(brandCheckClient.checkAll(anyList(), any(), anyLong())).thenReturn(null);
when(brandCheckClient.checkAll(anyList(), any(), anyLong(), any())).thenReturn(null);
List<CollectDataResultRowVo> rows = new ArrayList<>();
rows.add(null);
rows.add(row("B000000001", "Nike"));
rows.add(row("B000000002", "Zara"));
CollectDataBrandBatchFilter.BrandBatchOutcome outcome = filter.filter(rows);
CollectDataBrandBatchFilter.BrandBatchOutcome outcome = filter.filter(rows, 7L);
assertEquals(2, outcome.accepted().size(), "null 结果按无失败处理,行全 accepted");
assertEquals(0, outcome.rejected().size(), "null 行不计数");
verify(brandCheckClient).checkAll(anyList(), any(), anyLong());
verify(brandCheckClient).checkAll(anyList(), any(), anyLong(), any());
}
@Test
void test_task_046_brand_dependency_failure_releases_resources() {
// 依赖失败:远程检查抛错时批次整组降级 queryFailed,可恢复;恢复后重新检查成功。
when(brandCheckClient.checkAll(anyList(), any(), anyLong()))
when(brandCheckClient.checkAll(anyList(), any(), anyLong(), any()))
.thenThrow(new RuntimeException("brand service down"))
.thenReturn(new BrandCheckClient.BrandCheckBatchResult(
List.of(), List.of("Zara"), List.of()));
List.of(), List.of("Zara"), List.of(), ""));
List<CollectDataResultRowVo> rows = List.of(
row("B000000001", "Zara"), row("B000000002", "Nike"));
CollectDataBrandBatchFilter.BrandBatchOutcome failed = filter.filter(rows);
CollectDataBrandBatchFilter.BrandBatchOutcome failed = filter.filter(rows, 7L);
assertEquals(2, failed.queryFailed().size(), "依赖失败批次整组降级 queryFailed");
assertEquals(0, failed.accepted().size() + failed.rejected().size(), "降级后无其他分类");
CollectDataBrandBatchFilter.BrandBatchOutcome recovered = filter.filter(rows);
CollectDataBrandBatchFilter.BrandBatchOutcome recovered = filter.filter(rows, 7L);
assertEquals(1, recovered.rejected().size(), "恢复后失败品牌重新分类");
assertEquals(1, recovered.accepted().size(), "恢复后其余行 accepted");
assertTrue(recovered.queryFailed().isEmpty(), "恢复后无残留 queryFailed");
@@ -202,17 +202,17 @@ class CollectDataBrandBatchFilterTest {
@Test
void test_chunk_budget_exhausted_stops_calling_upstream() {
AtomicInteger calls = new AtomicInteger();
when(brandCheckClient.checkAll(anyList(), any(), anyLong())).thenAnswer(invocation -> {
when(brandCheckClient.checkAll(anyList(), any(), anyLong(), any())).thenAnswer(invocation -> {
calls.incrementAndGet();
Thread.sleep(30);
return new BrandCheckClient.BrandCheckBatchResult(List.of(), List.of(), List.of());
return new BrandCheckClient.BrandCheckBatchResult(List.of(), List.of(), List.of(), "");
});
CollectDataBrandBatchFilter tight = new CollectDataBrandBatchFilter(brandCheckClient, 2, 512, 1L);
CollectDataBrandBatchFilter.BrandBatchOutcome outcome = tight.filter(List.of(
row("B000000001", "brand-1"), row("B000000002", "brand-2"),
row("B000000003", "brand-3"), row("B000000004", "brand-4"),
row("B000000005", "brand-5"), row("B000000006", "brand-6")));
row("B000000005", "brand-5"), row("B000000006", "brand-6")), 7L);
assertEquals(1, calls.get(), "预算用尽后不再为剩余批次发起远程检查");
assertEquals(2, outcome.accepted().size(), "首个已检查批次照常分类");
@@ -224,18 +224,18 @@ class CollectDataBrandBatchFilterTest {
void test_cached_verdict_still_applies_and_blank_brand_rejects_after_budget_exhausted() {
// 预算用尽只做「不再花代价」,不改分类口径:缓存里有结论的仍按结论走,
// 空品牌行仍归 rejected(补测队列按品牌入队,空品牌进去就永远回不来)。
when(brandCheckClient.checkAll(anyList(), any(), anyLong())).thenAnswer(invocation -> {
when(brandCheckClient.checkAll(anyList(), any(), anyLong(), any())).thenAnswer(invocation -> {
Thread.sleep(30);
List<String> brands = invocation.getArgument(0);
List<Object> hits = new ArrayList<>(brands.stream().filter("bad-brand"::equals).toList());
return new BrandCheckClient.BrandCheckBatchResult(List.of(), hits, List.of());
return new BrandCheckClient.BrandCheckBatchResult(List.of(), hits, List.of(), "");
});
CollectDataBrandBatchFilter tight = new CollectDataBrandBatchFilter(brandCheckClient, 2, 512, 1L);
CollectDataBrandBatchFilter.BrandBatchOutcome outcome = tight.filter(List.of(
row("B000000001", "bad-brand"), row("B000000002", "seen-ok"),
row("B000000003", "bad-brand"), row("B000000004", "brand-4"),
row("B000000005", "brand-5"), row("B000000006", " ")));
row("B000000005", "brand-5"), row("B000000006", " ")), 7L);
assertEquals(List.of("B000000001", "B000000003", "B000000006"), asins(outcome.rejected()),
"侵权品牌与空品牌行归 rejected");
@@ -247,19 +247,19 @@ class CollectDataBrandBatchFilterTest {
@Test
void test_each_batch_gets_only_the_remaining_chunk_budget() {
// 共用一个截止时刻,而不是每批各领一份预算。
when(brandCheckClient.checkAll(anyList(), any(), anyLong())).thenAnswer(invocation -> {
when(brandCheckClient.checkAll(anyList(), any(), anyLong(), any())).thenAnswer(invocation -> {
Thread.sleep(40);
return new BrandCheckClient.BrandCheckBatchResult(List.of(), List.of(), List.of());
return new BrandCheckClient.BrandCheckBatchResult(List.of(), List.of(), List.of(), "");
});
CollectDataBrandBatchFilter bounded = new CollectDataBrandBatchFilter(brandCheckClient, 2, 512, 5_000L);
bounded.filter(List.of(
row("B000000001", "brand-1"), row("B000000002", "brand-2"),
row("B000000003", "brand-3"), row("B000000004", "brand-4"),
row("B000000005", "brand-5"), row("B000000006", "brand-6")));
row("B000000005", "brand-5"), row("B000000006", "brand-6")), 7L);
ArgumentCaptor<Long> budgets = ArgumentCaptor.forClass(Long.class);
verify(brandCheckClient, times(3)).checkAll(anyList(), any(), budgets.capture());
verify(brandCheckClient, times(3)).checkAll(anyList(), any(), budgets.capture(), any());
List<Long> values = budgets.getAllValues();
assertTrue(values.get(0) <= 5_000L, "首批拿到的不超过 chunk 预算");
assertTrue(values.get(1) < values.get(0), "第二批只能用剩余的");
@@ -269,15 +269,15 @@ class CollectDataBrandBatchFilterTest {
@Test
void test_zero_budget_passes_through_as_unlimited() {
// 逃生阀:预算配 0 表示不掐批间,把每批的预算交给 checkAll 按配置走(旧口径)。
when(brandCheckClient.checkAll(anyList(), any(), anyLong())).thenReturn(
new BrandCheckClient.BrandCheckBatchResult(List.of(), List.of(), List.of()));
when(brandCheckClient.checkAll(anyList(), any(), anyLong(), any())).thenReturn(
new BrandCheckClient.BrandCheckBatchResult(List.of(), List.of(), List.of(), ""));
CollectDataBrandBatchFilter unbounded = new CollectDataBrandBatchFilter(brandCheckClient, 2, 512, 0L);
CollectDataBrandBatchFilter.BrandBatchOutcome outcome = unbounded.filter(List.of(
row("B000000001", "brand-1"), row("B000000002", "brand-2"), row("B000000003", "brand-3")));
row("B000000001", "brand-1"), row("B000000002", "brand-2"), row("B000000003", "brand-3")), 7L);
ArgumentCaptor<Long> budgets = ArgumentCaptor.forClass(Long.class);
verify(brandCheckClient, times(2)).checkAll(anyList(), any(), budgets.capture());
verify(brandCheckClient, times(2)).checkAll(anyList(), any(), budgets.capture(), any());
assertEquals(List.of(0L, 0L), budgets.getAllValues(), "预算 0 逐批透传 0(不限制)");
assertEquals(3, outcome.accepted().size(), "不限制时没有行被延后");
}
@@ -41,100 +41,100 @@ class CollectDataBrandCacheTest {
@Test
void test_task_047_cache_brand_normal_default_path() {
// 正常输入:首查品牌发起远程检查并缓存判定,分类正确。
when(brandCheckClient.checkAll(anyList(), any(), anyLong())).thenReturn(
when(brandCheckClient.checkAll(anyList(), any(), anyLong(), any())).thenReturn(
new BrandCheckClient.BrandCheckBatchResult(
List.of(), List.of("Zara"), List.of()));
List.of(), List.of("Zara"), List.of(), ""));
CollectDataBrandBatchFilter.BrandBatchOutcome outcome = filter.filter(List.of(
row("B000000001", "Zara"),
row("B000000002", "Nike")
));
), 7L);
assertEquals(1, outcome.rejected().size(), "失败品牌行 rejected");
assertEquals("B000000001", outcome.rejected().get(0).getAsin());
assertEquals(1, outcome.accepted().size(), "其余行 accepted");
verify(brandCheckClient).checkAll(anyList(), any(), anyLong());
verify(brandCheckClient).checkAll(anyList(), any(), anyLong(), any());
}
@Test
void test_task_047_cache_brand_normal_multiple_items() {
// 批量场景:多 chunk 提交时同品牌只远程检查一次,每 chunk 只查未缓存品牌。
when(brandCheckClient.checkAll(anyList(), any(), anyLong())).thenReturn(
when(brandCheckClient.checkAll(anyList(), any(), anyLong(), any())).thenReturn(
new BrandCheckClient.BrandCheckBatchResult(
List.of(), List.of("Zara"), List.of()));
filter.filter(List.of(row("B000000001", "Zara"), row("B000000002", "Nike")));
List.of(), List.of("Zara"), List.of(), ""));
filter.filter(List.of(row("B000000001", "Zara"), row("B000000002", "Nike")), 7L);
CollectDataBrandBatchFilter.BrandBatchOutcome second = filter.filter(List.of(
row("B000000001", "Zara"),
row("B000000003", "Adidas")
));
), 7L);
assertEquals(1, second.rejected().size(), "chunk2 Zara 命中缓存仍 rejected");
assertEquals(1, second.accepted().size(), "chunk2 新品牌 Adidas accepted");
ArgumentCaptor<List> captor = ArgumentCaptor.forClass(List.class);
verify(brandCheckClient, times(2)).checkAll(captor.capture(), any(), anyLong());
verify(brandCheckClient, times(2)).checkAll(captor.capture(), any(), anyLong(), any());
assertEquals(List.of("Adidas"), captor.getAllValues().get(1), "第二次只查未缓存品牌");
}
@Test
void test_task_047_cache_brand_normal_repeated_operation_is_idempotent() {
// 幂等:同一输入重复执行结果一致,第二次全部命中缓存不发远程调用。
when(brandCheckClient.checkAll(anyList(), any(), anyLong())).thenReturn(
when(brandCheckClient.checkAll(anyList(), any(), anyLong(), any())).thenReturn(
new BrandCheckClient.BrandCheckBatchResult(
List.of(), List.of("Nike"), List.of()));
List.of(), List.of("Nike"), List.of(), ""));
List<CollectDataResultRowVo> rows = List.of(
row("B000000001", "Nike"),
row("B000000002", "Adidas")
);
CollectDataBrandBatchFilter.BrandBatchOutcome first = filter.filter(rows);
CollectDataBrandBatchFilter.BrandBatchOutcome second = filter.filter(rows);
CollectDataBrandBatchFilter.BrandBatchOutcome first = filter.filter(rows, 7L);
CollectDataBrandBatchFilter.BrandBatchOutcome second = filter.filter(rows, 7L);
assertEquals(first.rejected(), second.rejected(), "重复执行 rejected 一致");
assertEquals(first.accepted(), second.accepted(), "重复执行 accepted 一致");
verify(brandCheckClient, times(1)).checkAll(anyList(), any(), anyLong());
verify(brandCheckClient, times(1)).checkAll(anyList(), any(), anyLong(), any());
}
@Test
void test_task_047_cache_brand_boundary_empty_input() {
// 空输入:空列表与全空品牌批次均不发起远程调用,也不写缓存。
CollectDataBrandBatchFilter.BrandBatchOutcome empty = filter.filter(List.of());
CollectDataBrandBatchFilter.BrandBatchOutcome empty = filter.filter(List.of(), 7L);
assertEquals(0, empty.rejected().size() + empty.accepted().size() + empty.queryFailed().size(),
"空列表返回空结果");
verify(brandCheckClient, never()).checkAll(anyList(), any(), anyLong());
verify(brandCheckClient, never()).checkAll(anyList(), any(), anyLong(), any());
CollectDataBrandBatchFilter.BrandBatchOutcome blank = filter.filter(List.of(
row("B000000001", "")
));
), 7L);
assertEquals(1, blank.rejected().size(), "空品牌行 rejected");
verify(brandCheckClient, never()).checkAll(anyList(), any(), anyLong());
verify(brandCheckClient, never()).checkAll(anyList(), any(), anyLong(), any());
}
@Test
void test_task_047_cache_brand_boundary_single_item() {
// 单元素:单品牌首查一次;同品牌再出现时命中缓存零调用。
when(brandCheckClient.checkAll(anyList(), any(), anyLong())).thenReturn(
when(brandCheckClient.checkAll(anyList(), any(), anyLong(), any())).thenReturn(
new BrandCheckClient.BrandCheckBatchResult(
List.of(), List.of(), List.of()));
List.of(), List.of(), List.of(), ""));
CollectDataBrandBatchFilter.BrandBatchOutcome single = filter.filter(List.of(
row("B000000001", "solo")
));
), 7L);
assertEquals(1, single.accepted().size(), "单品牌未命中失败 accepted");
CollectDataBrandBatchFilter.BrandBatchOutcome again = filter.filter(List.of(
row("B000000002", "solo")
));
), 7L);
assertEquals(1, again.accepted().size(), "同品牌再次出现结果一致");
verify(brandCheckClient, times(1)).checkAll(anyList(), any(), anyLong());
verify(brandCheckClient, times(1)).checkAll(anyList(), any(), anyLong(), any());
}
@Test
void test_task_047_cache_brand_boundary_limit_and_overflow() {
// 上限/超限:缓存容量 8,首批 10 个品牌淘汰最旧 2 个;第二批同品牌
// 只重查被淘汰的 2 个,其余 8 个命中缓存;无无界增长。
when(brandCheckClient.checkAll(anyList(), any(), anyLong())).thenReturn(
when(brandCheckClient.checkAll(anyList(), any(), anyLong(), any())).thenReturn(
new BrandCheckClient.BrandCheckBatchResult(
List.of(), List.of(), List.of()));
List.of(), List.of(), List.of(), ""));
CollectDataBrandBatchFilter smallCache = new CollectDataBrandBatchFilter(brandCheckClient, 10, 8);
List<CollectDataResultRowVo> first = new ArrayList<>();
List<CollectDataResultRowVo> second = new ArrayList<>();
@@ -143,12 +143,12 @@ class CollectDataBrandCacheTest {
second.add(row("B" + (100 + i), "brand-" + i));
}
smallCache.filter(first);
CollectDataBrandBatchFilter.BrandBatchOutcome out = smallCache.filter(second);
smallCache.filter(first, 7L);
CollectDataBrandBatchFilter.BrandBatchOutcome out = smallCache.filter(second, 7L);
assertEquals(10, out.accepted().size(), "第二批 10 行全部 accepted");
ArgumentCaptor<List> captor = ArgumentCaptor.forClass(List.class);
verify(brandCheckClient, times(2)).checkAll(captor.capture(), any(), anyLong());
verify(brandCheckClient, times(2)).checkAll(captor.capture(), any(), anyLong(), any());
List<String> secondCall = captor.getAllValues().get(1);
assertEquals(2, secondCall.size(), "仅重查被淘汰的最旧 2 个品牌");
assertTrue(secondCall.containsAll(List.of("brand-0", "brand-1")), "淘汰的是最旧条目");
@@ -157,39 +157,39 @@ class CollectDataBrandCacheTest {
@Test
void test_task_047_cache_brand_invalid_input_rejected() {
// 非法参数:checkAll 返回 null 按无失败处理并缓存;null 行安全跳过。
when(brandCheckClient.checkAll(anyList(), any(), anyLong())).thenReturn(null);
when(brandCheckClient.checkAll(anyList(), any(), anyLong(), any())).thenReturn(null);
List<CollectDataResultRowVo> rows = new ArrayList<>();
rows.add(null);
rows.add(row("B000000001", "Nike"));
CollectDataBrandBatchFilter.BrandBatchOutcome first = filter.filter(rows);
CollectDataBrandBatchFilter.BrandBatchOutcome first = filter.filter(rows, 7L);
assertEquals(1, first.accepted().size(), "null 结果按无失败处理");
assertEquals(0, first.rejected().size(), "null 行不计数");
CollectDataBrandBatchFilter.BrandBatchOutcome second = filter.filter(rows);
CollectDataBrandBatchFilter.BrandBatchOutcome second = filter.filter(rows, 7L);
assertEquals(1, second.accepted().size(), "重复执行结果一致");
verify(brandCheckClient, times(1)).checkAll(anyList(), any(), anyLong());
verify(brandCheckClient, times(1)).checkAll(anyList(), any(), anyLong(), any());
}
@Test
void test_task_047_cache_brand_dependency_failure_releases_resources() {
// 依赖失败:远程抛错整批 queryFailed 且不缓存;恢复后重查成功,无残留状态。
when(brandCheckClient.checkAll(anyList(), any(), anyLong()))
when(brandCheckClient.checkAll(anyList(), any(), anyLong(), any()))
.thenThrow(new RuntimeException("brand service down"))
.thenReturn(new BrandCheckClient.BrandCheckBatchResult(
List.of(), List.of("Zara"), List.of()));
List.of(), List.of("Zara"), List.of(), ""));
List<CollectDataResultRowVo> rows = List.of(
row("B000000001", "Zara"), row("B000000002", "Nike"));
CollectDataBrandBatchFilter.BrandBatchOutcome failed = filter.filter(rows);
CollectDataBrandBatchFilter.BrandBatchOutcome failed = filter.filter(rows, 7L);
assertEquals(2, failed.queryFailed().size(), "失败批次整组降级 queryFailed");
CollectDataBrandBatchFilter.BrandBatchOutcome recovered = filter.filter(rows);
CollectDataBrandBatchFilter.BrandBatchOutcome recovered = filter.filter(rows, 7L);
assertEquals(1, recovered.rejected().size(), "恢复后重新检查并分类");
assertEquals(1, recovered.accepted().size(), "恢复后 accepted 正确");
assertTrue(recovered.queryFailed().isEmpty(), "恢复后无残留 queryFailed");
verify(brandCheckClient, times(2)).checkAll(anyList(), any(), anyLong());
verify(brandCheckClient, times(2)).checkAll(anyList(), any(), anyLong(), any());
}
private static CollectDataResultRowVo row(String asin, String brand) {
@@ -93,6 +93,26 @@ class DedupeRunServiceCleanRulesTest {
assertEquals(List.of("7", "B0FFFFFF01", "英国", "9.99", "品牌F", "在售"), readOutputRow(output, 1));
}
/**
* 去重出件的品牌列也必须剥掉亚马逊署名标签前缀:源文件是用户从详情页复制再上传的,
* 结果文件又是他的下一份上传物。源文件列集由用户勾选,所以只能按表头认出「品牌」这一列,
* 其余所选列一律原文透传(这里用同样带前缀的「状态」列钉住不越界)。
* 摘掉 buildCandidateRow 里按表头认出的 strip,下面第一条断言读回来的就是 "Brand: NIKE"。
*/
@Test
@DisplayName("品牌列出件剥掉行首标签前缀,其余所选列原文透传")
void stripsBrandLabelPrefixOnlyFromBrandColumn(@TempDir Path tempDir) throws Exception {
File output = runClean(tempDir, List.of(
new String[]{"1", "B0BRAND001", "英国", "10.00", "FBM", "Brand: NIKE", "Brand: 在售", "2026-09-01"},
new String[]{"2", "B0BRAND002", "英国", "11.00", "FBM", "Brands: NIKE", "在售", "2026-09-01"}),
List.of("id", "ASIN", "国家", "价格", "品牌", "状态"));
assertEquals(List.of("NIKE", "Brands: NIKE"), readOutputColumn(output, 4),
"品牌列只剥行首一个标签,「Brands:」是真实品牌写法");
assertEquals(List.of("Brand: 在售", "在售"), readOutputColumn(output, 5),
"非品牌列不参与清洗");
}
/** 纯规则单测:保留主链接开关打开时,整数行不再受子链接影响。 */
@Test
@DisplayName("开启保留主链接时,整数行不受子链接影响")
@@ -298,6 +298,46 @@ class InvalidAsinDataServiceTest {
return captor.getValue();
}
/**
* 品牌是这张表的匹配键(下游按它判"这个 ASIN 属于被屏蔽品牌")。人工把详情页署名行整段
* 粘进来会存成 "brand: nike",而采集侧现在给 "nike" —— 对不上时屏蔽**静默失效**,不报错,
* 比脏值出件更难发现。摘掉 create 里的 BrandLabel.strip,这两条一条读到 "brand: nike"、
* 一条根本不抛。
*/
@Test
@SuppressWarnings({"rawtypes", "unchecked"})
void createStripsTheBylineLabelFromTheMatchKey() {
InvalidAsinDataCreateRequest request = new InvalidAsinDataCreateRequest();
request.setDataValue("B012345678");
request.setBrand("Brand: Acme");
request.setGroupId(9L);
when(shopManageGroupService.getAccessibleById(9L, 7L, true)).thenReturn(group(9L, "group-a"));
when(invalidAsinDataMapper.selectOne(any())).thenReturn(null);
when(invalidAsinDataMapper.insert(any(InvalidAsinDataEntity.class))).thenAnswer(invocation -> {
invocation.getArgument(0, InvalidAsinDataEntity.class).setId(91L);
return 1;
});
when(invalidAsinDataMapper.selectById(91L)).thenReturn(data(91L, "MANUAL", 9L));
service.create(request, 7L);
ArgumentCaptor<InvalidAsinDataEntity> captor = ArgumentCaptor.forClass(InvalidAsinDataEntity.class);
verify(invalidAsinDataMapper).insert(captor.capture());
assertEquals("acme", captor.getValue().getBrand(), "标签前缀必须在落库前就剥掉,键值才是同一个串");
}
@Test
void createRejectsALabelOnlyBrand() {
// 先洗再判空:洗完全空=用户其实没填品牌,不能让它带着空串进唯一键
InvalidAsinDataCreateRequest request = new InvalidAsinDataCreateRequest();
request.setDataValue("B012345678");
request.setBrand("Brand:");
request.setGroupId(9L);
when(shopManageGroupService.getAccessibleById(9L, 7L, true)).thenReturn(group(9L, "group-a"));
assertThrows(BusinessException.class, () -> service.create(request, 7L));
}
private ShopManageGroupEntity group(Long id, String groupName) {
ShopManageGroupEntity group = new ShopManageGroupEntity();
group.setId(id);
@@ -2,6 +2,7 @@ package com.nanri.aiimage.modules.notification.service;
import com.nanri.aiimage.common.mapper.AdminUserMapper;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.modules.brand.support.BrandCheckFailureNotice;
import com.nanri.aiimage.modules.permission.support.UserDataScopeSupport;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@@ -11,6 +12,7 @@ import org.mockito.junit.jupiter.MockitoExtension;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.contains;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.startsWith;
@@ -19,7 +21,7 @@ import static org.mockito.Mockito.verify;
/**
* 品牌补测结果通知:补出结论才推、同任务同日一条(dedupe_key 带日期)、
* 全部收口未修复时改推「未能完成」指引。只推用户不推管理员(正向收敛不放大铃铛)。
* 全部收口未修复时改推「未能完成」并按**失败类别**给指引。只推用户不推管理员(正向收敛不放大铃铛)。
*/
@ExtendWith(MockitoExtension.class)
class NotificationDispatchServiceRecheckTest {
@@ -38,7 +40,8 @@ class NotificationDispatchServiceRecheckTest {
@Test
void pushRecheckOutcomeNotifiesUserWithInfoLevelWhenAllResolved() {
service.pushRecheckOutcome(961L, 29842L, "COLLECT_DATA", "COLLECT_DATA-29842", 3, 1, 0, 0);
service.pushRecheckOutcome(961L, 29842L, "COLLECT_DATA", "COLLECT_DATA-29842", 3, 1, 0, 0,
BrandCheckFailureNotice.Kind.UPSTREAM);
verify(notificationService).pushOrRefresh(eq(961L), eq("user"), eq("task_partial"),
eq("info"), contains("补测完成"), contains("新增结果 3 行"), startsWith("collect_recheck:29842:"));
@@ -46,7 +49,8 @@ class NotificationDispatchServiceRecheckTest {
@Test
void pushRecheckOutcomeUsesWarningWhileRowsStillPending() {
service.pushRecheckOutcome(961L, 29842L, "COLLECT_DATA", "COLLECT_DATA-29842", 3, 0, 5, 0);
service.pushRecheckOutcome(961L, 29842L, "COLLECT_DATA", "COLLECT_DATA-29842", 3, 0, 5, 0,
BrandCheckFailureNotice.Kind.UPSTREAM);
verify(notificationService).pushOrRefresh(eq(961L), eq("user"), eq("task_partial"),
eq("warning"), contains("补测完成"), contains("仍有 5 行"), anyString());
@@ -55,26 +59,53 @@ class NotificationDispatchServiceRecheckTest {
@Test
void pushRecheckOutcomeStaysSilentOnPureProgressRounds() {
// 本轮没有品牌出结论、也没有条目收口:纯排队推进,不打扰
service.pushRecheckOutcome(961L, 29842L, "COLLECT_DATA", "COLLECT_DATA-29842", 0, 0, 3, 0);
service.pushRecheckOutcome(961L, 29842L, "COLLECT_DATA", "COLLECT_DATA-29842", 0, 0, 0, 0);
service.pushRecheckOutcome(961L, 29842L, "COLLECT_DATA", "COLLECT_DATA-29842", 0, 0, 3, 0,
BrandCheckFailureNotice.Kind.UPSTREAM);
service.pushRecheckOutcome(961L, 29842L, "COLLECT_DATA", "COLLECT_DATA-29842", 0, 0, 0, 0,
BrandCheckFailureNotice.Kind.UPSTREAM);
verify(notificationService, never()).pushOrRefresh(
any(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString());
}
@Test
void pushRecheckOutcomeAdvisesManualRerunWhenAllExhausted() {
service.pushRecheckOutcome(961L, 29842L, "COLLECT_DATA", "COLLECT_DATA-29842", 0, 0, 0, 4);
void pushRecheckOutcomeTellsUserToFixProxyPackageWhenExhaustedByRejection() {
// 2026-10-20 现网主因:用户自己的代理套餐被拒付后冷却。旧文案一律怪「上游商标库」
// 并建议重跑,而重跑必然还是失败——这句得跟着类别走。
service.pushRecheckOutcome(961L, 29842L, "COLLECT_DATA", "COLLECT_DATA-29842", 0, 0, 0, 4,
BrandCheckFailureNotice.Kind.PROXY_PACKAGE_EXHAUSTED);
verify(notificationService).pushOrRefresh(eq(961L), eq("user"), eq("task_partial"),
eq("warning"), contains("未能完成"), contains("共 4 行"), startsWith("collect_recheck:29842:"));
eq("warning"), contains("未能完成"),
argThat(content -> content.contains("共 4 行") && content.contains("代理设置")),
startsWith("collect_recheck:29842:"));
}
@Test
void pushRecheckOutcomeBlamesUpstreamOnlyWhenReasonIsUpstream() {
service.pushRecheckOutcome(961L, 29842L, "COLLECT_DATA", "COLLECT_DATA-29842", 0, 0, 0, 4,
BrandCheckFailureNotice.Kind.UPSTREAM);
verify(notificationService).pushOrRefresh(eq(961L), eq("user"), eq("task_partial"),
eq("warning"), contains("未能完成"), contains("上游商标库"), startsWith("collect_recheck:29842:"));
}
@Test
void pushRecheckOutcomeFallsBackToUpstreamWordingWhenKindMissing() {
service.pushRecheckOutcome(961L, 29842L, "COLLECT_DATA", "COLLECT_DATA-29842", 0, 0, 0, 2, null);
verify(notificationService).pushOrRefresh(eq(961L), eq("user"), eq("task_partial"),
eq("warning"), contains("未能完成"), contains("自动重试"), anyString());
}
@Test
void pushRecheckOutcomeSkipsInvalidUser() {
service.pushRecheckOutcome(null, 29842L, "COLLECT_DATA", "COLLECT_DATA-29842", 3, 1, 0, 0);
service.pushRecheckOutcome(0L, 29842L, "COLLECT_DATA", "COLLECT_DATA-29842", 3, 1, 0, 0);
service.pushRecheckOutcome(961L, null, "COLLECT_DATA", "COLLECT_DATA-29842", 3, 1, 0, 0);
service.pushRecheckOutcome(null, 29842L, "COLLECT_DATA", "COLLECT_DATA-29842", 3, 1, 0, 0,
BrandCheckFailureNotice.Kind.UPSTREAM);
service.pushRecheckOutcome(0L, 29842L, "COLLECT_DATA", "COLLECT_DATA-29842", 3, 1, 0, 0,
BrandCheckFailureNotice.Kind.UPSTREAM);
service.pushRecheckOutcome(961L, null, "COLLECT_DATA", "COLLECT_DATA-29842", 3, 1, 0, 0,
BrandCheckFailureNotice.Kind.UPSTREAM);
verify(notificationService, never()).pushOrRefresh(
any(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString());
@@ -0,0 +1,638 @@
package com.nanri.aiimage.modules.publish.service.support;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import cn.hutool.crypto.digest.DigestUtil;
import com.nanri.aiimage.common.service.DistributedJobLockService;
import com.nanri.aiimage.config.InstanceMetadata;
import com.nanri.aiimage.modules.file.service.LocalFileStorageService;
import com.nanri.aiimage.modules.file.service.oss.OssStorageService;
import com.nanri.aiimage.modules.publish.mapper.PublishFileMapper;
import com.nanri.aiimage.modules.publish.mapper.PublishItemMapper;
import com.nanri.aiimage.modules.publish.model.dto.PublishParseRequest;
import com.nanri.aiimage.modules.publish.model.dto.PublishRowDto;
import com.nanri.aiimage.modules.publish.model.dto.PublishSourceFileDto;
import com.nanri.aiimage.modules.publish.model.entity.PublishFileEntity;
import com.nanri.aiimage.modules.publish.model.entity.PublishItemEntity;
import com.nanri.aiimage.modules.publish.model.vo.PublishFileVo;
import com.nanri.aiimage.modules.publish.model.vo.PublishParseVo;
import com.nanri.aiimage.modules.publish.service.PublishTaskService;
import com.nanri.aiimage.modules.publish.service.PublishWorkbookService;
import com.nanri.aiimage.modules.task.mapper.FileResultMapper;
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
import com.nanri.aiimage.modules.task.mapper.TaskChunkMapper;
import com.nanri.aiimage.modules.task.mapper.TaskScopeStateMapper;
import com.nanri.aiimage.modules.task.model.entity.FileResultEntity;
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import com.nanri.aiimage.modules.task.model.entity.TaskScopeStateEntity;
import com.nanri.aiimage.modules.task.service.TaskDistributedLockService;
import com.nanri.aiimage.modules.task.service.TaskFileJobService;
import com.nanri.aiimage.modules.task.service.TaskHeartbeatPositionService;
import com.nanri.aiimage.modules.task.service.TaskProgressLightAssembler;
import com.nanri.aiimage.modules.task.service.TransientPayloadStorageService;
import com.nanri.aiimage.modules.ziniao.service.ZiniaoShopIndexService;
import com.nanri.aiimage.modules.ziniao.service.ZiniaoShopSwitchService;
import com.nanri.aiimage.modules.ziniao.model.vo.ZiniaoShopMatchResultVo;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.apache.ibatis.session.Configuration;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
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.Mockito.lenient;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* 上架(publish)**建单段**的现网行为快照——Phase 3 收口清单里那条「publish 建单段 golden 缺口」。
*
* <p><b>为什么这一格一直欠着。</b>本支在册两条快照里 {@code PublishBatchLoadingSnapshotEquivTest}
* 吃的是读侧入口({@code history}/{@code dashboard}/{@code getTaskDetail}/{@code getTaskProgress}),
* {@code PublishSubmitResultSnapshotTest} 吃的是回传入口 {@code submitResult};
* <b>建单入口 {@code parseAndCreateTask} 一次都没进过</b>。3D 第三笔把
* {@code newTaskHeader}/{@code insertTask}/{@code newScopeRow} 换成了底座件,
* 当时的等值证据是「旧块/现块/底座件体的 setter 集合做差集」——那是推理级的证据,
* 不是可复跑的防线。这一支把那段补成防线:以后谁再动建单段,流水当场出声。
*
* <p><b>快照吃的是事件流水</b>({@code tx.begin → task.insert → file.insert →
* item.insertBatch → result.insert → tx.commit}),顺序换了即红。同时钉住六条本支特有的现网形状:
* <ol>
* <li><b>解析在事务外、落库在事务内</b>:{@code prepareFile} 全部跑完才开 {@code execute()},
* 而 {@code execute} 返回 null 时抛「创建上架任务失败」——本支是七支里
* {@code TransactionTemplate} 那一派(AppearancePatent/DeleteBrand 全程无事务)。</li>
* <li><b>一枚建单时刻复用给三处、第四处不复用</b>:{@code now} 同时喂头行(底座六参
* {@code newTaskHeader})、每个文件行、结果行(三处 {@code createdAtEqualsTaskNow=true},
* 比的是同一枚引用而非大小);而 {@code insertRows} 自己再取一次 {@code now()} 给
* {@code biz_publish_item}({@code itemCreatedAtEqualsTaskNow=false})。
* 「时钟不进快照」指的是值不进,复用关系可以进——3C 那笔登记的五参版微差
* (头行两列逐字相同)在本支不构成风险,本支走的正是显式时刻那一派。</li>
* <li><b>文件解析失败不抛、只把该文件标 FAILED</b>:三种失败出口各有各的文案
* (店铺名解析不出/店铺未匹配到紫鸟索引/匹配服务抛异常 ⇒ {@code matchStatus} 归 PENDING
* + Excel 解析抛)。只要有一个文件可用,任务仍是 PENDING;<b>全失败</b>才直接 FAILED
* 并写 {@code errorMessage}「全部文件解析或店铺匹配失败」+{@code finishedAt}。</li>
* <li><b>计数与落库不同径</b>:{@code file.totalRows} 与 {@code result.rowCount} 取
* {@code rows.size()}(<b>含 null 元素</b>),而 {@code insertRows} 逐行 {@code continue} 跳过 null
* ⇒ 落库行数可以少于计数。0 行文件也不会调 {@code insertBatch}(空列表早退),
* 但 0 行文件仍算「可处理」,任务照样建起来进队列。</li>
* <li><b>结果行的 {@code success} 写 0</b>(不是 NULL、不是 -1):与 AppearancePatent 留 NULL、
* ShopDataCrawl 的 -1 是三种形状 ⇒ 底座 {@code newScopeRow} 那两列刻意可空这件事,
* 本支由调用点显式交 0。</li>
* <li><b>行内品牌过 {@code BrandLabel.strip}</b>:清洗落在落库那一格而不是解析那一格,
* 所以 golden 里 {@code brands=[...]} 就是 {@code biz_publish_item.brand} 的真值形状。</li>
* </ol>
*
* <p><b>刻意不进快照的</b>:雪花 id({@code taskNo} 擦成 {@code <snowflake>})、
* 时钟本身(只断复用关系,不比时刻值)。
*
* golden:src/test/resources/publish/golden/create-task-snapshot.txt
* 重新生成:{@code SHUFU_SNAPSHOT_WRITE=true mvn -o test -Dtest=PublishCreateTaskSnapshotTest}
* (环境变量而非 {@code -D}:pom 的 {@code <argLine>} 是显式配置,命令行覆盖不动它。
* 这条 golden 只许在改动本支<b>之前</b>生成一次,此后它就是是非源。)
*/
class PublishCreateTaskSnapshotTest {
private static final File GOLDEN =
new File("src/test/resources/publish/golden/create-task-snapshot.txt");
private static final String MODULE_TYPE = "PUBLISH";
@BeforeAll
static void initializeMybatisMetadata() {
MapperBuilderAssistant assistant = new MapperBuilderAssistant(new Configuration(), "");
TableInfoHelper.initTableInfo(assistant, FileTaskEntity.class);
TableInfoHelper.initTableInfo(assistant, FileResultEntity.class);
TableInfoHelper.initTableInfo(assistant, PublishFileEntity.class);
TableInfoHelper.initTableInfo(assistant, PublishItemEntity.class);
TableInfoHelper.initTableInfo(assistant, TaskScopeStateEntity.class);
}
/** Spring 注入的那只 ObjectMapper ≠ {@code new ObjectMapper()}:Boot 挂 jsr310(Phase 0 实测教训)。 */
private static ObjectMapper bootLikeObjectMapper() {
return JsonMapper.builder()
.addModule(new JavaTimeModule())
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.build();
}
// ------------------------------------------------------------------
// 被测服务的装配:19 枚实参顺序=构造器声明顺序(四处 new PublishTaskService(…) 同形)
// ------------------------------------------------------------------
private static final class Harness {
final List<String> events = new ArrayList<>();
final LocalFileStorageService localFileStorageService = mock(LocalFileStorageService.class);
final ZiniaoShopSwitchService ziniaoShopSwitchService = mock(ZiniaoShopSwitchService.class);
final PublishWorkbookService workbookService = mock(PublishWorkbookService.class);
final PublishFileMapper publishFileMapper = mock(PublishFileMapper.class);
final PublishItemMapper publishItemMapper = mock(PublishItemMapper.class);
final FileTaskMapper fileTaskMapper = mock(FileTaskMapper.class);
final FileResultMapper fileResultMapper = mock(FileResultMapper.class);
final TransactionTemplate transactionTemplate = mock(TransactionTemplate.class);
final InstanceMetadata instanceMetadata = mock(InstanceMetadata.class);
/** 头行的建单时刻:用来断「同一枚 now 复用给文件行与结果行」,不比大小。 */
LocalDateTime taskCreatedAt;
/** 匹配服务的行为:null=索引里没有该店;抛异常=模拟网络/索引侧故障。 */
ZiniaoShopMatchResultVo matchToReturn;
java.util.function.Function<String, ZiniaoShopMatchResultVo> matchResolver;
RuntimeException matchFailure;
PublishTaskService service() {
lenient().when(instanceMetadata.getInstanceId()).thenReturn("node-A");
// 一格 answer 而不是两枚 when:service() 里的兜底 stub 注册在调用方之后,
// Mockito 按「后注册者优先」匹配,any() 那一枚会把调用方按名字打的具体桩顶掉。
lenient().when(ziniaoShopSwitchService.findIndexedStoreByName(any(), org.mockito.ArgumentMatchers.anyBoolean()))
.thenAnswer(invocation -> {
if (matchFailure != null) {
throw matchFailure;
}
String shopName = invocation.getArgument(0);
return matchResolver != null ? matchResolver.apply(shopName) : matchToReturn;
});
lenient().when(transactionTemplate.execute(any())).thenAnswer(invocation -> {
TransactionCallback<?> callback = invocation.getArgument(0);
events.add("tx.begin");
Object value = callback.doInTransaction(mock(TransactionStatus.class));
events.add("tx.commit");
return value;
});
doAnswer("task");
doAnswer("file");
doAnswer("item");
doAnswer("result");
return new PublishTaskService(
localFileStorageService,
ziniaoShopSwitchService,
workbookService,
publishFileMapper,
publishItemMapper,
fileTaskMapper,
fileResultMapper,
mock(TaskChunkMapper.class),
mock(TaskScopeStateMapper.class),
mock(TaskFileJobService.class),
mock(TaskDistributedLockService.class),
mock(TransientPayloadStorageService.class),
mock(OssStorageService.class),
bootLikeObjectMapper(),
transactionTemplate,
mock(DistributedJobLockService.class),
instanceMetadata,
mock(TaskProgressLightAssembler.class),
mock(TaskHeartbeatPositionService.class));
}
private void doAnswer(String which) {
switch (which) {
case "task" -> lenient().when(fileTaskMapper.insert(any(FileTaskEntity.class)))
.thenAnswer(invocation -> {
FileTaskEntity task = invocation.getArgument(0);
task.setId(1001L);
taskCreatedAt = task.getCreatedAt();
events.add("task.insert taskNo=" + maskTaskNo(task.getTaskNo())
+ " moduleType=" + task.getModuleType()
+ " status=" + task.getStatus()
+ " taskMode=" + task.getTaskMode()
+ " sourceFileCount=" + task.getSourceFileCount()
+ " successFileCount=" + task.getSuccessFileCount()
+ " failedFileCount=" + task.getFailedFileCount()
+ " userId=" + task.getUserId()
+ " createdBy=" + task.getCreatedBy()
+ " deviceId=" + task.getDeviceId()
+ " errorMessage=" + task.getErrorMessage()
+ " finishedAtSet=" + (task.getFinishedAt() != null)
+ " requestJson.keys=" + jsonKeys(task.getRequestJson())
+ " requestJson.digest=" + digest12(String.valueOf(task.getRequestJson()))
+ " resultJson=" + task.getResultJson());
return 1;
});
case "file" -> lenient().when(publishFileMapper.insert(any(PublishFileEntity.class)))
.thenAnswer(invocation -> {
PublishFileEntity file = invocation.getArgument(0);
file.setId(2001L + fileSeq++);
events.add("file.insert taskId=" + file.getTaskId()
+ " fileId=" + file.getId()
+ " fileKey=" + file.getFileKey()
+ " sourceFilename=" + file.getSourceFilename()
+ " relativePath=" + file.getRelativePath()
+ " shopName=" + file.getShopName()
+ " matched=" + file.getMatched()
+ " shopId=" + file.getShopId()
+ " matchedUserId=" + file.getMatchedUserId()
+ " platform=" + file.getPlatform()
+ " companyName=" + file.getCompanyName()
+ " matchStatus=" + file.getMatchStatus()
+ " matchMessage=" + file.getMatchMessage()
+ " status=" + file.getStatus()
+ " totalRows=" + file.getTotalRows()
+ " processedRows=" + file.getProcessedRows()
+ " errorMessage=" + file.getErrorMessage()
+ " finishedAtSet=" + (file.getFinishedAt() != null)
+ " createdAtEqualsTaskNow=" + (file.getCreatedAt() == taskCreatedAt));
return 1;
});
case "item" -> lenient().when(publishItemMapper.insertBatch(any())).thenAnswer(invocation -> {
List<PublishItemEntity> rows = invocation.getArgument(0);
StringBuilder rowIndexes = new StringBuilder();
StringBuilder asins = new StringBuilder();
StringBuilder brands = new StringBuilder();
for (PublishItemEntity row : rows) {
rowIndexes.append(rowIndexes.length() == 0 ? "" : ",").append(row.getRowIndex());
asins.append(asins.length() == 0 ? "" : ",").append(row.getAsin());
brands.append(brands.length() == 0 ? "" : ",").append(row.getBrand());
if (!rows.isEmpty()) {
// 同一批内 createdAt 必须也是那一枚建单时刻(insertRows 用的是自己的 now,见下条读数)
firstItemCreatedAt = row.getCreatedAt();
}
}
events.add("item.insertBatch count=" + rows.size()
+ " taskId=" + (rows.isEmpty() ? "null" : rows.get(0).getTaskId())
+ " fileId=" + (rows.isEmpty() ? "null" : rows.get(0).getFileId())
+ " rowIndex=[" + rowIndexes + "]"
+ " asins=[" + asins + "]"
+ " brands=[" + brands + "]"
+ " itemCreatedAtEqualsTaskNow=" + (firstItemCreatedAt == taskCreatedAt));
return rows.size();
});
default -> lenient().when(fileResultMapper.insert(any(FileResultEntity.class)))
.thenAnswer(invocation -> {
FileResultEntity result = invocation.getArgument(0);
result.setId(3001L);
events.add("result.insert taskId=" + result.getTaskId()
+ " moduleType=" + result.getModuleType()
+ " sourceFilename=" + result.getSourceFilename()
+ " sourceFileUrl=" + result.getSourceFileUrl()
+ " resultContentType=" + result.getResultContentType()
+ " rowCount=" + result.getRowCount()
+ " success=" + result.getSuccess()
+ " errorMessage=" + result.getErrorMessage()
+ " userId=" + result.getUserId()
+ " createdAtEqualsTaskNow=" + (result.getCreatedAt() == taskCreatedAt));
return 1;
});
}
}
private int fileSeq;
private LocalDateTime firstItemCreatedAt;
}
// ------------------------------------------------------------------
// 夹具
// ------------------------------------------------------------------
private static File existingFile() throws Exception {
File file = File.createTempFile("publish-create-task-", ".xlsx");
file.deleteOnExit();
return file;
}
private static ZiniaoShopMatchResultVo matchedVo() {
ZiniaoShopMatchResultVo match = new ZiniaoShopMatchResultVo();
match.setMatched(true);
match.setShopId("shop-9");
match.setShopName("shop-a");
match.setCompanyName("ACME 有限公司");
match.setPlatform("amazon");
match.setMatchedUserId(42L);
match.setMatchStatus(ZiniaoShopIndexService.MATCH_STATUS_MATCHED);
match.setMatchMessage("");
return match;
}
private static PublishRowDto row(String sourceId, String asin, String brand) {
PublishRowDto row = new PublishRowDto();
row.setSourceId(sourceId);
row.setAsin(asin);
row.setCountry("US");
row.setBrand(brand);
row.setPrice("19.90");
row.setStatus("在售");
row.setSyncStatus(null);
row.setSyncCountries(null);
return row;
}
private static PublishSourceFileDto source(String fileKey, String originalFilename, String relativePath) {
PublishSourceFileDto dto = new PublishSourceFileDto();
dto.setFileKey(fileKey);
dto.setOriginalFilename(originalFilename);
dto.setRelativePath(relativePath);
return dto;
}
private static PublishParseRequest request(Long userId, List<PublishSourceFileDto> files, String country) {
PublishParseRequest request = new PublishParseRequest();
request.setUserId(userId);
request.setFiles(files);
request.setPublishCountry(country);
return request;
}
private static Harness harnessWithFile(String fileKey, List<PublishRowDto> rows) throws Exception {
Harness harness = new Harness();
harness.matchToReturn = matchedVo();
File file = existingFile();
when(harness.localFileStorageService.findLocalSourceFile(fileKey)).thenReturn(file);
when(harness.workbookService.parse(file)).thenReturn(new PublishWorkbookService.ParsedWorkbook(rows));
return harness;
}
// ------------------------------------------------------------------
// 读数整形:只擦不稳定量,不改结构
// ------------------------------------------------------------------
private static String maskTaskNo(String taskNo) {
int idx = taskNo == null ? -1 : taskNo.lastIndexOf('-');
return idx < 0 ? String.valueOf(taskNo) : taskNo.substring(0, idx) + "-<snowflake>";
}
private static String digest12(String value) {
return DigestUtil.sha256Hex(value).substring(0, 12);
}
/** JSON 只取顶层键序+内容摘要:golden 要灵敏于变化,又不能变成一堵 JSON 墙。 */
private static String jsonKeys(String json) {
if (json == null || json.isBlank()) {
return "[]";
}
List<String> keys = new ArrayList<>();
Matcher matcher = Pattern.compile("\"([^\"]+)\"\\s*:").matcher(json);
while (matcher.find()) {
keys.add(matcher.group(1));
}
return keys.isEmpty() ? "[<scalar>]" : "[" + String.join(",", keys) + "]";
}
private static String describe(String label, Runnable action) {
try {
action.run();
return label + " -> 未抛异常";
} catch (Exception ex) {
return label + " -> " + ex.getClass().getSimpleName() + ": " + ex.getMessage();
}
}
private static String renderEvents(Harness harness) {
return String.join("\n", harness.events);
}
/**
* 事件名前缀:{@code tx.begin}/{@code tx.commit} 这两格<b>没有参数</b>、整条不含空格,
* 照 AP 那版直接 {@code substring(0, indexOf(' '))} 会抛越界(本件第一次跑就是这么红的)。
*/
private static String eventKind(String event) {
int idx = event.indexOf(' ');
return idx < 0 ? event : event.substring(0, idx);
}
private static String renderVo(PublishParseVo vo) {
StringBuilder sb = new StringBuilder();
sb.append("vo: taskId=").append(vo.getTaskId())
.append(" taskNo=").append(maskTaskNo(vo.getTaskNo()))
.append(" sourceFileCount=").append(vo.getSourceFileCount())
.append(" totalRows=").append(vo.getTotalRows())
.append(" pageSize=").append(vo.getPageSize())
.append('\n');
for (PublishFileVo file : vo.getFiles()) {
sb.append(" vo.file fileId=").append(file.getFileId())
.append(" fileKey=").append(file.getFileKey())
.append(" shopName=").append(file.getShopName())
.append(" matched=").append(file.isMatched())
.append(" status=").append(file.getStatus())
.append(" totalRows=").append(file.getTotalRows())
.append(" percent=").append(file.getPercent())
.append(" errorMessage=").append(file.getErrorMessage())
.append('\n');
}
return sb.toString();
}
// ------------------------------------------------------------------
// 各场景(golden 的每一节)
// ------------------------------------------------------------------
private static String caseSingleFile() throws Exception {
Harness harness = harnessWithFile("uploads/shop-a.xlsx", List.of(
row("1", "B001", "品牌: 耐克"),
row("2", "B002", "Adidas")));
PublishParseVo vo = harness.service().parseAndCreateTask(
request(7L, List.of(source("uploads/shop-a.xlsx", "shop-a.xlsx", "shop-a.xlsx")), "US"),
"device-1");
return "== 单文件建单:匹配成功、解析两行 ==\n"
+ renderEvents(harness) + "\n" + renderVo(vo);
}
private static String caseTwoFilesAggregate() throws Exception {
Harness harness = new Harness();
harness.matchToReturn = matchedVo();
File first = existingFile();
File second = existingFile();
when(harness.localFileStorageService.findLocalSourceFile("uploads/a.xlsx")).thenReturn(first);
when(harness.localFileStorageService.findLocalSourceFile("uploads/b.xlsx")).thenReturn(second);
when(harness.workbookService.parse(first))
.thenReturn(new PublishWorkbookService.ParsedWorkbook(List.of(row("1", "B001", "Nike"))));
when(harness.workbookService.parse(second))
.thenReturn(new PublishWorkbookService.ParsedWorkbook(List.of(row("2", "B002", "Puma"), row("3", "B003", "Asics"))));
PublishParseVo vo = harness.service().parseAndCreateTask(request(7L, List.of(
source("uploads/a.xlsx", "a.xlsx", "a.xlsx"),
source("uploads/b.xlsx", "b.xlsx", "b.xlsx")), "DE"), " device-2 ");
return "== 双文件聚合:结果类型换 zip、URL 取首文件、行号逐文件重计 ==\n"
+ renderEvents(harness) + "\n" + renderVo(vo);
}
private static String casePartialFailure() throws Exception {
Harness harness = new Harness();
harness.matchResolver = name -> "shop-a".equals(name) ? matchedVo() : null;
File okFile = existingFile();
when(harness.localFileStorageService.findLocalSourceFile("uploads/a.xlsx")).thenReturn(okFile);
when(harness.workbookService.parse(okFile))
.thenReturn(new PublishWorkbookService.ParsedWorkbook(List.of(row("1", "B001", "Nike"))));
PublishParseVo vo = harness.service().parseAndCreateTask(request(7L, List.of(
source("uploads/a.xlsx", "shop-a.xlsx", "a.xlsx"),
source("uploads/b.xlsx", "shop-b.xlsx", "b.xlsx")), "US"), null);
return "== 店铺未匹配:文件行 FAILED 但任务仍 PENDING(有一个可用就进队列) ==\n"
+ renderEvents(harness) + "\n" + renderVo(vo);
}
private static String caseAllFilesFailed() throws Exception {
Harness harness = new Harness();
harness.matchFailure = new IllegalStateException("紫鸟索引不可用");
PublishParseVo vo = harness.service().parseAndCreateTask(request(7L, List.of(
source("uploads/a.xlsx", "shop-a.xlsx", "a.xlsx")), "US"), "d");
return "== 匹配服务抛异常:全文件失败 ⇒ 任务直接 FAILED 并封口 ==\n"
+ renderEvents(harness) + "\n" + renderVo(vo);
}
private static String caseZeroRowFileStillQueued() throws Exception {
Harness harness = harnessWithFile("uploads/empty.xlsx", List.of());
PublishParseVo vo = harness.service().parseAndCreateTask(
request(7L, List.of(source("uploads/empty.xlsx", "shop-a.xlsx", "empty.xlsx")), "US"), "d");
return "== 解析出 0 行:不调 insertBatch,但文件仍 PENDING、任务仍建起来 ==\n"
+ renderEvents(harness) + "\n" + renderVo(vo);
}
private static String caseNullRowCountedButNotInserted() throws Exception {
Harness harness = harnessWithFile("uploads/null-row.xlsx",
Arrays.asList(row("1", "B001", "Brand: NIKE: X"), null, row("2", "B002", "品牌:李宁")));
PublishParseVo vo = harness.service().parseAndCreateTask(
request(7L, List.of(source("uploads/null-row.xlsx", "shop-a.xlsx", "n.xlsx")), "US"), "d");
return "== 行含 null:计数含 null 而落库跳 null,品牌落库前过 BrandLabel.strip ==\n"
+ renderEvents(harness) + "\n" + renderVo(vo);
}
private static String caseRejectionsTouchNothing() throws Exception {
StringBuilder sb = new StringBuilder("== 建单被拒的七格:事务未开、一次库都不碰 ==\n");
Harness blankKey = new Harness();
blankKey.matchToReturn = matchedVo();
File realFile = existingFile();
when(blankKey.localFileStorageService.findLocalSourceFile("uploads/dup.xlsx")).thenReturn(realFile);
when(blankKey.workbookService.parse(realFile))
.thenReturn(new PublishWorkbookService.ParsedWorkbook(List.of(row("1", "B001", "Nike"))));
sb.append(describe("request=null", () -> new Harness().service().parseAndCreateTask(null, "d"))).append('\n');
sb.append(describe("userId=null", () -> new Harness().service()
.parseAndCreateTask(request(null, List.of(source("k", "k.xlsx", "k")), "US"), "d"))).append('\n');
sb.append(describe("userId=0", () -> new Harness().service()
.parseAndCreateTask(request(0L, List.of(source("k", "k.xlsx", "k")), "US"), "d"))).append('\n');
sb.append(describe("files=null", () -> new Harness().service()
.parseAndCreateTask(request(7L, null, "US"), "d"))).append('\n');
sb.append(describe("files=空", () -> new Harness().service()
.parseAndCreateTask(request(7L, List.of(), "US"), "d"))).append('\n');
sb.append(describe("publishCountry=空白", () -> new Harness().service()
.parseAndCreateTask(request(7L, List.of(source("k", "k.xlsx", "k")), " "), "d"))).append('\n');
sb.append(describe("fileKey 重复", () -> blankKey.service()
.parseAndCreateTask(request(7L, List.of(
source("uploads/dup.xlsx", "shop-a.xlsx", "d.xlsx"),
source("uploads/dup.xlsx", "shop-a.xlsx", "d.xlsx")), "US"), "d"))).append('\n');
sb.append("events=").append(blankKey.events.size())
.append("(重复 fileKey 那格已 prepare 过首文件,但落库与事务都未开始)\n");
return sb.toString();
}
private static String renderAll() throws Exception {
StringBuilder sb = new StringBuilder();
sb.append(caseSingleFile()).append('\n');
sb.append(caseTwoFilesAggregate()).append('\n');
sb.append(casePartialFailure()).append('\n');
sb.append(caseAllFilesFailed()).append('\n');
sb.append(caseZeroRowFileStillQueued()).append('\n');
sb.append(caseNullRowCountedButNotInserted()).append('\n');
sb.append(caseRejectionsTouchNothing());
return sb.toString();
}
private static String read(File file) throws Exception {
return Files.readString(file.toPath(), StandardCharsets.UTF_8);
}
// ------------------------------------------------------------------
// 用例
// ------------------------------------------------------------------
@Test
void 建单段落库流水与golden一致() throws Exception {
assertEquals(read(GOLDEN), renderAll(), "建单段事件流水必须与 golden 逐字节相等");
}
@Test
void 副作用顺序是解析在事务外落库在事务内() throws Exception {
Harness harness = harnessWithFile("uploads/shop-a.xlsx", List.of(row("1", "B001", "Nike")));
harness.service().parseAndCreateTask(
request(7L, List.of(source("uploads/shop-a.xlsx", "shop-a.xlsx", "a.xlsx")), "US"), "d");
assertEquals(List.of("tx.begin", "task.insert", "file.insert", "item.insertBatch", "result.insert", "tx.commit"),
harness.events.stream().map(PublishCreateTaskSnapshotTest::eventKind).toList(),
"头行→文件行→行批插→结果行,整段在一次 execute() 里");
}
@Test
void 同一枚建单时刻复用给头行文件行与结果行() throws Exception {
Harness harness = harnessWithFile("uploads/shop-a.xlsx", List.of(row("1", "B001", "Nike")));
harness.service().parseAndCreateTask(
request(7L, List.of(source("uploads/shop-a.xlsx", "shop-a.xlsx", "a.xlsx")), "US"), "d");
assertTrue(harness.events.stream().anyMatch(e -> e.startsWith("file.insert") && e.contains("createdAtEqualsTaskNow=true")),
"文件行的 createdAt 必须就是底座头行那枚 now");
assertTrue(harness.events.stream().anyMatch(e -> e.startsWith("result.insert") && e.contains("createdAtEqualsTaskNow=true")),
"结果行的 createdAt 必须就是底座头行那枚 now");
assertTrue(harness.events.stream().anyMatch(e -> e.contains("itemCreatedAtEqualsTaskNow=false")),
"insertRows 自己再取一次 now,行项目的 createdAt 与建单时刻不同一枚——"
+ "这条现网不对称由本断言钉住,谁顺手统一就必须先过这里");
}
@Test
void 全失败才把任务直接判FAILED并封口() throws Exception {
Harness harness = new Harness();
harness.matchFailure = new IllegalStateException("紫鸟索引不可用");
harness.service().parseAndCreateTask(
request(7L, List.of(source("uploads/a.xlsx", "shop-a.xlsx", "a.xlsx")), "US"), "d");
assertTrue(harness.events.stream().anyMatch(e -> e.startsWith("task.insert") && e.contains(" status=FAILED")),
"无可用文件时任务不再进队列:" + harness.events);
assertTrue(harness.events.stream().anyMatch(e -> e.contains("全部文件解析或店铺匹配失败")));
assertTrue(harness.events.stream().anyMatch(e -> e.startsWith("result.insert") && e.contains(" rowCount=0")),
"结果行仍然 insert,只是零行");
}
@Test
void 非法建单一次库都不碰() {
Harness harness = new Harness();
assertThrows(com.nanri.aiimage.common.exception.BusinessException.class,
() -> harness.service().parseAndCreateTask(request(null, List.of(source("k", "k.xlsx", "k")), "US"), "d"));
assertTrue(harness.events.isEmpty(), "user_id 不合法时不得开事务、不得落库");
}
@Test
void golden文件已入库且非空() {
assertTrue(GOLDEN.isFile(), "golden 必须入库: " + GOLDEN.getAbsolutePath());
assertTrue(GOLDEN.length() > 0, "golden 非空");
}
@Test
void 篡改golden必须判红() throws Exception {
String original = read(GOLDEN);
assertTrue(original.contains("== 单文件建单"), "golden 内容合法");
try {
Files.writeString(GOLDEN.toPath(), original + "\n# tampered", StandardCharsets.UTF_8);
AssertionError failure = null;
try {
assertEquals(read(GOLDEN), renderAll(), "篡改后应与 golden 不一致");
} catch (AssertionError ex) {
failure = ex;
}
assertNotNull(failure, "篡改 golden 后断言必须失败,否则这支是恒绿的");
} finally {
Files.writeString(GOLDEN.toPath(), original, StandardCharsets.UTF_8);
}
assertEquals(original, read(GOLDEN), "恢复原始 golden");
}
@Test
void 同一夹具跑两次流水一致() throws Exception {
assertEquals(renderAll(), renderAll(), "快照必须可复现(雪花 id 与时钟值已擦除)");
}
/** 生成 golden 用:{@code SHUFU_SNAPSHOT_WRITE=true} 时把当前流水写回文件。 */
@Test
@org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable(named = "SHUFU_SNAPSHOT_WRITE", matches = "true")
void 重新生成golden() throws Exception {
Files.createDirectories(GOLDEN.toPath().getParent());
Files.writeString(GOLDEN.toPath(), renderAll(), StandardCharsets.UTF_8);
}
}
@@ -106,6 +106,31 @@ class ShopDataCrawlRowNormalizerTest {
assertEquals(" B001 ", source.getAsin());
}
/**
* 客户端从亚马逊详情页署名行原样回传,品牌值带着 "Brand: " 标签前缀。
* 读入(copyRow)与比对(sameRow / rowDedupKey)必须用同一个清洗后的字符串:
* 只洗其中一处,跨分片合并时已洗过的存量行与未洗的回传行会算出两个键,同一行重复出件。
* 摘掉 ShopDataCrawlRowNormalizer.brand 里的 strip,下面三条断言全部回退。
*/
@Test
void test_brand_label_prefix_stripped_on_ingest_and_in_dedup_key() {
ShopDataCrawlRowDto byline = row("2026-07-25", "B001", "Brand: NIKE", "img",
"10", "20", "30", "40", "50", "60");
ShopDataCrawlRowDto plain = row("2026-07-25", "B001", "NIKE", "img",
"10", "20", "30", "40", "50", "60");
assertEquals("NIKE", ShopDataCrawlRowNormalizer.copyRow(byline).getBrand(), "回传行进模型即剥标签");
assertTrue(ShopDataCrawlRowNormalizer.sameRow(byline, plain), "署名行与干净行是同一行");
assertEquals(ShopDataCrawlRowNormalizer.rowDedupKey(plain),
ShopDataCrawlRowNormalizer.rowDedupKey(byline), "去重键按剥完标签的品牌计算");
// "Brands:" 是真实品牌写法,不是字段标签
assertEquals("Brands: NIKE",
ShopDataCrawlRowNormalizer.copyRow(row("2026-07-25", "B001", "Brands: NIKE", "img",
"10", "20", "30", "40", "50", "60")).getBrand(),
"近似标签原样保留");
}
// ---- rowEmpty ----
@Test
@@ -128,6 +128,29 @@ class ShopDataCrawlSheetBuilderTest {
}
}
/**
* 出件的品牌末列必须剥掉亚马逊署名标签前缀:这份结果文件是用户的下一份上传物,
* 而改口径之前落库的累计文件快照与 row_payload 里仍带着 "Brand: " 前缀。
* 摘掉 writeDataRowValues 里的 strip,下面第一条断言读回来的就是 "Brand: NIKE"。
*/
@Test
void test_write_data_row_brand_label_prefix_stripped() throws Exception {
try (Workbook wb = new XSSFWorkbook()) {
Sheet sheet = ShopDataCrawlSheetBuilder.createStreamingSheet(wb, 0);
CellStyle[] none = new CellStyle[ShopDataCrawlSheetBuilder.HEADERS.size()];
Row dirty = sheet.createRow(1);
ShopDataCrawlSheetBuilder.writeDataRowValues(dirty,
row("2026-07-25", "B012345678", "Brand: NIKE", "https://img/x.jpg"), none);
Row lookalike = sheet.createRow(2);
ShopDataCrawlSheetBuilder.writeDataRowValues(lookalike,
row("2026-07-25", "B012345679", "Brands: NIKE", "https://img/x.jpg"), none);
assertEquals("NIKE", dirty.getCell(9).getStringCellValue(), "品牌末列剥掉行首标签");
assertEquals("Brands: NIKE", lookalike.getCell(9).getStringCellValue(), "近似标签是真实品牌写法,不剥");
assertEquals("2026-07-25", lookalike.getCell(0).getStringCellValue(), "其余列不参与品牌清洗");
}
}
@Test
void test_write_data_row_null_values_blank_cells() throws Exception {
try (Workbook wb = new XSSFWorkbook()) {
@@ -82,6 +82,9 @@ class ShopDataCrawlSnapshotTest {
private static ShopDataCrawlRowDto sparseRow() {
ShopDataCrawlRowDto row = new ShopDataCrawlRowDto();
row.setAsin("B099999999");
// 首尾空格刻意留着:品牌列出件要过 BrandLabel.strip,它除剥 "Brand:" 标签外还 trim
// (口径自 2026-10-08 就是这两手,Java/Python 正本与 MySQL 清洗脚本同形)。
// golden 里这格是无空格的 "Brand With Spaces" —— 快照改动是这条,不是有人手抖改了基线。
row.setBrand(" Brand With Spaces ");
return row;
}
@@ -12,6 +12,7 @@ import com.nanri.aiimage.modules.shopduplicatecheck.model.payload.DuplicateShop;
import com.nanri.aiimage.modules.shopduplicatecheck.service.ShopDataDuplicateCheckScanService.DuplicateScanView;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.util.List;
@@ -87,6 +88,37 @@ class ShopDataDuplicateCheckImportServiceTest {
verify(scanMapper).insert(any(ShopDataDuplicateScanEntity.class));
}
/** 基线 payload:郭悦晴那行的品牌带着改口径之前的标签前缀(这一店不在本次导入的店铺里,会被原样重插)。 */
private DuplicateScanView legacyBrandBaselineView() {
DuplicateOccurrence kept = new DuplicateOccurrence("B09PNTZM4L", "2026-08-19 05:48", "10.1",
"Brand: HANYTON", "郭悦晴", "G2", List.of("DE"), "DE");
DuplicateShop shop = new DuplicateShop("郭悦晴", "G2", List.of("DE"), 1, 1);
return new DuplicateScanView("2026-09-04 00:00:00", null, new DuplicateScanPayload(
List.of(shop), List.of(new DuplicateItem("B09PNTZM4L", 1, 1, List.of(kept)))));
}
/**
* 导入的基线行读自上一份落库 payload,改口径之前它带着 "Brand: " 前缀;原样重插就是替用户把
* 脏值写回扫描表一次(下载再上传同构的问题)。摘掉 applyToLatest 里的 strip,下面这条会红。
*/
@Test
void addImportDoesNotReseedLegacyBrandLabelIntoNewScanRow() throws Exception {
when(scanService.loadLatest()).thenReturn(legacyBrandBaselineView());
when(scanMapper.insert(any(ShopDataDuplicateScanEntity.class))).thenAnswer(invocation -> {
invocation.<ShopDataDuplicateScanEntity>getArgument(0).setId(99L);
return 1;
});
service.importExcel("小曾", "UK", workbook(), false);
ArgumentCaptor<ShopDataDuplicateScanEntity> inserted =
ArgumentCaptor.forClass(ShopDataDuplicateScanEntity.class);
verify(scanMapper).insert(inserted.capture());
assertThat(inserted.getValue().getPayloadJson())
.doesNotContain("Brand:")
.contains("HANYTON");
}
@Test
void importWithoutBaselineFails() {
when(scanService.loadLatest()).thenReturn(null);
@@ -4,13 +4,18 @@ import com.nanri.aiimage.modules.shopduplicatecheck.TestFixtures;
import com.nanri.aiimage.modules.shopduplicatecheck.mapper.ShopDuplicateCheckSourceMapper;
import com.nanri.aiimage.modules.shopduplicatecheck.model.payload.DuplicateItem;
import com.nanri.aiimage.modules.shopduplicatecheck.model.payload.DuplicateOccurrence;
import com.nanri.aiimage.modules.shopduplicatecheck.model.payload.DuplicateScanPayload;
import com.nanri.aiimage.modules.shopduplicatecheck.model.payload.DuplicateScanSummary;
import com.nanri.aiimage.modules.shopduplicatecheck.model.payload.DuplicateShop;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -265,6 +270,39 @@ class ShopDataDuplicateCheckQueryServiceTest {
assertThat(lines[1]).doesNotContain(",UK,");
}
/**
* 导出文件的品牌列必须是剥过标签前缀的:扫描行是改口径之前落库的,payload 里的品牌仍带
* "Brand: "(亚马逊详情页复制来的署名),而出件是用户的下一份上传物——这一格不洗,
* 下载再上传就把脏值送回链路里。摘掉 buildExportRows 里的 strip,这一格读回来就是 "Brand: NIKE"。
*/
@Test
void exportBrandColumnLosesTheAmazonBylinePrefix() throws Exception {
ShopDataDuplicateCheckScanService.DuplicateScanView legacyPayload =
new ShopDataDuplicateCheckScanService.DuplicateScanView(
"2026-09-04 03:10:00", null, new DuplicateScanPayload(List.of(), List.of(
new DuplicateItem("B0BRAND01", 2, 2, List.of(
legacyOccurrence("ShopA", "Brand: NIKE"),
legacyOccurrence("ShopB", "Brands: NIKE"))))));
ByteArrayOutputStream out = new ByteArrayOutputStream();
service.writeExportXlsx(legacyPayload, null, "all", noFilter(), out);
List<String> brands = new ArrayList<>();
try (XSSFWorkbook workbook = new XSSFWorkbook(new ByteArrayInputStream(out.toByteArray()))) {
Sheet sheet = workbook.getSheetAt(0);
for (int r = 1; r <= sheet.getLastRowNum(); r++) {
brands.add(sheet.getRow(r).getCell(7).getStringCellValue());
}
}
// "Brands:" 是真实品牌写法,只剥行首的那个标签
assertThat(brands).containsExactlyInAnyOrder("NIKE", "Brands: NIKE");
}
private static DuplicateOccurrence legacyOccurrence(String shopName, String brand) {
return new DuplicateOccurrence("B0BRAND01", "2026-08-30", "GBP 9.99", brand,
shopName, "GroupA", List.of("UK"), "UK");
}
@Test
void groupFilterNarrowsToGroupMembers() {
// 分组筛选:GroupA 只保留 ShopA/ShopB 键。
@@ -49,4 +49,22 @@ class ShopDataDuplicateCheckScanServiceTest {
void buildParsedShops_emptyInputReturnsEmpty() {
assertTrue(ShopDataDuplicateCheckScanService.buildParsedShops(List.of(), Map.of()).isEmpty());
}
/**
* 明细表的品牌是改口径之前落库的(采集端原样写入亚马逊署名行),扫描直接查这张表:
* 标签前缀要在进聚合这一端剥掉,落库 payload、台账页面与出件拿到的才是同一个干净值。
* 摘掉 buildParsedShops 里的 strip,下面第一条断言读回来的就是 "Brand: NIKE"。
*/
@Test
void buildParsedShops_stripsAmazonBylinePrefixFromDbBrandColumn() {
List<ShopParsed> parsed = ShopDataDuplicateCheckScanService.buildParsedShops(
List.of(new ShopLatestItemRowDto("店A", "UK", "B0001", "2026-09-01 10:00", "9.90", "Brand: NIKE"),
new ShopLatestItemRowDto("店A", "UK", "B0002", "2026-09-01 10:00", "9.90", "品牌:耐克"),
new ShopLatestItemRowDto("店A", "UK", "B0003", "2026-09-01 10:00", "9.90", "Brands: NIKE")),
Map.of());
assertEquals(List.of("NIKE", "耐克", "Brands: NIKE"),
parsed.get(0).rows().stream().map(RawRow::brand).toList(),
"行首标签剥掉,「Brands:」这类真实品牌写法原样保留");
}
}
@@ -75,4 +75,29 @@ class DuplicateCheckWorkbookParserTest {
new String[]{"2026-08-15", "9.99"});
assertEquals(0, DuplicateCheckWorkbookParser.parse(bytes).size(), "无 ASIN 列的 sheet 跳过");
}
/**
* 品牌列读入即剥标签前缀:用户上传的结果文件是亚马逊详情页复制来的,"Brand: XXX" 带着标签
* 进聚合就一路带到 payload、台账与出件。摘掉解析这一端的 strip,这里读到的就是原始署名值。
*/
@Test
void stripsAmazonBylinePrefixFromBrandColumn() throws Exception {
byte[] bytes = workbookWith(false, "英国",
new String[]{"ASIN", "日期", "价格", "品牌"},
new String[]{"B0BRAND01", "2026-08-15", "£34.46", "Brand: NIKE"});
assertEquals("NIKE", DuplicateCheckWorkbookParser.parse(bytes).get(0).brand(),
"行首标签在读入这一端剥掉");
}
/** "Brands:" 是真实品牌写法,不是字段标签;同一份文件里的价格/日期列不受品牌清洗影响。 */
@Test
void keepsLookalikeBrandAndOtherColumnsVerbatim() throws Exception {
byte[] bytes = workbookWith(false, "英国",
new String[]{"ASIN", "日期", "价格", "品牌"},
new String[]{"B0BRAND02", "Brand: 2026-08-15", "£Brand: 34.46", "Brands: NIKE"});
var row = DuplicateCheckWorkbookParser.parse(bytes).get(0);
assertEquals("Brands: NIKE", row.brand(), "近似标签原样保留");
assertEquals("Brand: 2026-08-15", row.date(), "非品牌列不参与清洗");
assertEquals("£Brand: 34.46", row.price(), "非品牌列不参与清洗");
}
}
@@ -209,6 +209,21 @@ class SimilarAsinSheetBuilderTest {
assertEquals("品牌Y", cellString(workbook, 1, 5), "品牌按包含匹配");
}
@Test
void test_build_brand_label_prefix_stripped() {
// 出件是用户的下一份上传物:亚马逊页面复制带上的 "Brand: " 前缀不在此剥掉,二次上传就把脏值送回链路
Workbook workbook = build(List.of(row("1", "B01A", "US", "19.9", "卖家1", "Brand: NIKE")));
assertEquals("NIKE", cellString(workbook, 1, 5), "品牌列剥掉行首标签前缀");
}
@Test
void test_build_brand_lookalike_kept() {
Workbook workbook = build(List.of(row("1", "B01A", "US", "19.9", "卖家1", "Brands: NIKE")));
assertEquals("Brands: NIKE", cellString(workbook, 1, 5), "近似标签是真实品牌写法,不随行首清洗被误剥");
}
@Test
void test_build_null_input() {
Workbook workbook = build(null);
@@ -140,8 +140,8 @@ class DuplicateSubmissionContractTest {
row.setAsin("B0DUP1234");
lenient().when(collectDataBatchQuery.filter(any(), any())).thenReturn(
new CollectDataBatchQuery.FilterResult(List.of(row), 0, 0));
lenient().when(brandBatchFilter.filter(any())).thenReturn(
new CollectDataBrandBatchFilter.BrandBatchOutcome(List.of(), List.of(), List.of(row)));
lenient().when(brandBatchFilter.filter(any(), any())).thenReturn(
new CollectDataBrandBatchFilter.BrandBatchOutcome(List.of(), List.of(), List.of(row), ""));
lenient().when(resultItemBatchWriter.upsertAccepted(anyLong(), anyLong(), anyString(), anyInt(), any(), anyString()))
.thenReturn(new CollectDataResultItemBatchWriter.UpsertCounts(1, 0, 1));
lenient().when(resultDetailCodec.encodeChunk(any())).thenReturn("{\"chunk\":1}");
@@ -266,13 +266,13 @@ class SourceScanTest {
// ---------------------------------------------------------------- N6 moduleSources
@Test
void moduleSources_appearancepatent返回31支含拆分后的support件() {
void moduleSources_appearancepatent返回38支含拆分后的support件() {
List<Path> files = SourceScan.moduleSources("modules/appearancepatent");
assertThat(files)
.as("真实集成:对真仓目录求值。31 支=1 controller+1 client+1 service 主件+3 spi/cache+"
+ "8 service/support+16 model(dto7/vo9),与 find 实测同号")
.hasSize(31);
.as("真实集成:对真仓目录求值。38 支=1 controller+1 client+1 service 主件+3 spi/cache+"
+ "15 service/support+16 model(dto7/vo9),与 find 实测同号")
.hasSize(38);
assertThat(files.stream().map(p -> p.toString().replace('\\', '/')).toList())
.as("support 目录里的既有件必须在面里——聚合入口存在的理由就是拆分后的新文件要自动被看到")
.anyMatch(rel -> rel.endsWith("service/support/AppearancePatentRowNormalizer.java"));
@@ -366,22 +366,29 @@ class SourceScanTest {
}
@Test
void recursive_包含service_support下的既有8件() {
void recursive_包含service_support下的既有15件() {
List<String> support = SourceScan.moduleSources("modules/appearancepatent").stream()
.map(p -> p.toString().replace('\\', '/'))
.filter(rel -> rel.contains("/service/support/"))
.toList();
assertThat(support)
.as("真实集成:对真仓 modules/appearancepatent/service/support 求值,实测 8 支(3A 拆薄把归属谓词、陈旧扫描、结果打包抽成三枚 support 件,5→8)。"
.as("真实集成:对真仓 modules/appearancepatent/service/support 求值,实测 15 支(3A 拆薄把归属谓词、陈旧扫描、结果打包、LLM 批管线、载荷读写、结果行读取、进度视图、分片回传、交付闸门、结果作业抽成十枚 support 件,5→15)。"
+ "这一格就是聚合入口存在的理由——拆分出去的新文件必须自动进面")
.hasSize(8);
.hasSize(15);
assertThat(support)
.as("3A 拆出去的三枚新件必须被逐枚点名扫到:只把分母数字改大,下一回拆件又只剩「数不对」"
.as("3A 拆出去的十枚新件必须被逐枚点名扫到:只把分母数字改大,下一回拆件又只剩「数不对」"
+ "一记红,证不了「扫得到」这件事")
.anyMatch(rel -> rel.endsWith("service/support/AppearancePatentTaskOwnership.java"))
.anyMatch(rel -> rel.endsWith("service/support/AppearancePatentStaleTaskScanner.java"))
.anyMatch(rel -> rel.endsWith("service/support/AppearancePatentResultPackager.java"));
.anyMatch(rel -> rel.endsWith("service/support/AppearancePatentResultPackager.java"))
.anyMatch(rel -> rel.endsWith("service/support/AppearancePatentLlmBatchPipeline.java"))
.anyMatch(rel -> rel.endsWith("service/support/AppearancePatentPayloadSupport.java"))
.anyMatch(rel -> rel.endsWith("service/support/AppearancePatentResultRowReader.java"))
.anyMatch(rel -> rel.endsWith("service/support/AppearancePatentProgressSupport.java"))
.anyMatch(rel -> rel.endsWith("service/support/AppearancePatentChunkSubmissionSupport.java"))
.anyMatch(rel -> rel.endsWith("service/support/AppearancePatentDeliverySupport.java"))
.anyMatch(rel -> rel.endsWith("service/support/AppearancePatentResultJobSupport.java"));
}
@Test
@@ -0,0 +1,72 @@
== 单文件建单:匹配成功、解析两行 ==
tx.begin
task.insert taskNo=PUBLISH-<snowflake> moduleType=PUBLISH status=PENDING taskMode=PYTHON_QUEUE sourceFileCount=1 successFileCount=0 failedFileCount=0 userId=7 createdBy=user:7 deviceId=device-1 errorMessage=null finishedAtSet=false requestJson.keys=[files,fileKey,originalFilename,relativePath,user_id,publish_country,sync_countries] requestJson.digest=d94395576c95 resultJson={"ownerInstanceId":"node-A"}
file.insert taskId=1001 fileId=2001 fileKey=uploads/shop-a.xlsx sourceFilename=shop-a.xlsx relativePath=shop-a.xlsx shopName=shop-a matched=1 shopId=shop-9 matchedUserId=42 platform=amazon companyName=ACME 有限公司 matchStatus=MATCHED matchMessage= status=PENDING totalRows=2 processedRows=0 errorMessage=null finishedAtSet=false createdAtEqualsTaskNow=true
item.insertBatch count=2 taskId=1001 fileId=2001 rowIndex=[1,2] asins=[B001,B002] brands=[耐克,Adidas] itemCreatedAtEqualsTaskNow=false
result.insert taskId=1001 moduleType=PUBLISH sourceFilename=shop-a.xlsx sourceFileUrl=uploads/shop-a.xlsx resultContentType=application/vnd.openxmlformats-officedocument.spreadsheetml.sheet rowCount=2 success=0 errorMessage=null userId=7 createdAtEqualsTaskNow=true
tx.commit
vo: taskId=1001 taskNo=PUBLISH-<snowflake> sourceFileCount=1 totalRows=2 pageSize=50
vo.file fileId=2001 fileKey=uploads/shop-a.xlsx shopName=shop-a matched=true status=PENDING totalRows=2 percent=0 errorMessage=null
== 双文件聚合:结果类型换 zip、URL 取首文件、行号逐文件重计 ==
tx.begin
task.insert taskNo=PUBLISH-<snowflake> moduleType=PUBLISH status=PENDING taskMode=PYTHON_QUEUE sourceFileCount=2 successFileCount=0 failedFileCount=0 userId=7 createdBy=user:7 deviceId=device-2 errorMessage=null finishedAtSet=false requestJson.keys=[files,fileKey,originalFilename,relativePath,fileKey,originalFilename,relativePath,user_id,publish_country,sync_countries] requestJson.digest=02e9718f0b2b resultJson={"ownerInstanceId":"node-A"}
file.insert taskId=1001 fileId=2001 fileKey=uploads/a.xlsx sourceFilename=a.xlsx relativePath=a.xlsx shopName=a matched=1 shopId=shop-9 matchedUserId=42 platform=amazon companyName=ACME 有限公司 matchStatus=MATCHED matchMessage= status=PENDING totalRows=1 processedRows=0 errorMessage=null finishedAtSet=false createdAtEqualsTaskNow=true
item.insertBatch count=1 taskId=1001 fileId=2001 rowIndex=[1] asins=[B001] brands=[Nike] itemCreatedAtEqualsTaskNow=false
file.insert taskId=1001 fileId=2002 fileKey=uploads/b.xlsx sourceFilename=b.xlsx relativePath=b.xlsx shopName=b matched=1 shopId=shop-9 matchedUserId=42 platform=amazon companyName=ACME 有限公司 matchStatus=MATCHED matchMessage= status=PENDING totalRows=2 processedRows=0 errorMessage=null finishedAtSet=false createdAtEqualsTaskNow=true
item.insertBatch count=2 taskId=1001 fileId=2002 rowIndex=[1,2] asins=[B002,B003] brands=[Puma,Asics] itemCreatedAtEqualsTaskNow=false
result.insert taskId=1001 moduleType=PUBLISH sourceFilename=a.xlsx 等 2 个文件 sourceFileUrl=uploads/a.xlsx resultContentType=application/zip rowCount=3 success=0 errorMessage=null userId=7 createdAtEqualsTaskNow=true
tx.commit
vo: taskId=1001 taskNo=PUBLISH-<snowflake> sourceFileCount=2 totalRows=3 pageSize=50
vo.file fileId=2001 fileKey=uploads/a.xlsx shopName=a matched=true status=PENDING totalRows=1 percent=0 errorMessage=null
vo.file fileId=2002 fileKey=uploads/b.xlsx shopName=b matched=true status=PENDING totalRows=2 percent=0 errorMessage=null
== 店铺未匹配:文件行 FAILED 但任务仍 PENDING(有一个可用就进队列) ==
tx.begin
task.insert taskNo=PUBLISH-<snowflake> moduleType=PUBLISH status=PENDING taskMode=PYTHON_QUEUE sourceFileCount=2 successFileCount=0 failedFileCount=1 userId=7 createdBy=user:7 deviceId=null errorMessage=null finishedAtSet=false requestJson.keys=[files,fileKey,originalFilename,relativePath,fileKey,originalFilename,relativePath,user_id,publish_country,sync_countries] requestJson.digest=e0166e85bd50 resultJson={"ownerInstanceId":"node-A"}
file.insert taskId=1001 fileId=2001 fileKey=uploads/a.xlsx sourceFilename=shop-a.xlsx relativePath=a.xlsx shopName=shop-a matched=1 shopId=shop-9 matchedUserId=42 platform=amazon companyName=ACME 有限公司 matchStatus=MATCHED matchMessage= status=PENDING totalRows=1 processedRows=0 errorMessage=null finishedAtSet=false createdAtEqualsTaskNow=true
item.insertBatch count=1 taskId=1001 fileId=2001 rowIndex=[1] asins=[B001] brands=[Nike] itemCreatedAtEqualsTaskNow=false
file.insert taskId=1001 fileId=2002 fileKey=uploads/b.xlsx sourceFilename=shop-b.xlsx relativePath=b.xlsx shopName=shop-b matched=0 shopId=null matchedUserId=null platform=null companyName=null matchStatus=null matchMessage=null status=FAILED totalRows=0 processedRows=0 errorMessage=店铺未匹配到紫鸟索引 finishedAtSet=true createdAtEqualsTaskNow=true
result.insert taskId=1001 moduleType=PUBLISH sourceFilename=shop-a.xlsx 等 2 个文件 sourceFileUrl=uploads/a.xlsx resultContentType=application/zip rowCount=1 success=0 errorMessage=null userId=7 createdAtEqualsTaskNow=true
tx.commit
vo: taskId=1001 taskNo=PUBLISH-<snowflake> sourceFileCount=2 totalRows=1 pageSize=50
vo.file fileId=2001 fileKey=uploads/a.xlsx shopName=shop-a matched=true status=PENDING totalRows=1 percent=0 errorMessage=null
vo.file fileId=2002 fileKey=uploads/b.xlsx shopName=shop-b matched=false status=FAILED totalRows=0 percent=100 errorMessage=店铺未匹配到紫鸟索引
== 匹配服务抛异常:全文件失败 ⇒ 任务直接 FAILED 并封口 ==
tx.begin
task.insert taskNo=PUBLISH-<snowflake> moduleType=PUBLISH status=FAILED taskMode=PYTHON_QUEUE sourceFileCount=1 successFileCount=0 failedFileCount=1 userId=7 createdBy=user:7 deviceId=d errorMessage=全部文件解析或店铺匹配失败 finishedAtSet=true requestJson.keys=[files,fileKey,originalFilename,relativePath,user_id,publish_country,sync_countries] requestJson.digest=9982fc0a2d4f resultJson={"ownerInstanceId":"node-A"}
file.insert taskId=1001 fileId=2001 fileKey=uploads/a.xlsx sourceFilename=shop-a.xlsx relativePath=a.xlsx shopName=shop-a matched=0 shopId=null matchedUserId=null platform=null companyName=null matchStatus=PENDING matchMessage=紫鸟索引不可用 status=FAILED totalRows=0 processedRows=0 errorMessage=紫鸟索引不可用 finishedAtSet=true createdAtEqualsTaskNow=true
result.insert taskId=1001 moduleType=PUBLISH sourceFilename=shop-a.xlsx sourceFileUrl=uploads/a.xlsx resultContentType=application/vnd.openxmlformats-officedocument.spreadsheetml.sheet rowCount=0 success=0 errorMessage=全部文件解析或店铺匹配失败 userId=7 createdAtEqualsTaskNow=true
tx.commit
vo: taskId=1001 taskNo=PUBLISH-<snowflake> sourceFileCount=1 totalRows=0 pageSize=50
vo.file fileId=2001 fileKey=uploads/a.xlsx shopName=shop-a matched=false status=FAILED totalRows=0 percent=100 errorMessage=紫鸟索引不可用
== 解析出 0 行:不调 insertBatch,但文件仍 PENDING、任务仍建起来 ==
tx.begin
task.insert taskNo=PUBLISH-<snowflake> moduleType=PUBLISH status=PENDING taskMode=PYTHON_QUEUE sourceFileCount=1 successFileCount=0 failedFileCount=0 userId=7 createdBy=user:7 deviceId=d errorMessage=null finishedAtSet=false requestJson.keys=[files,fileKey,originalFilename,relativePath,user_id,publish_country,sync_countries] requestJson.digest=0f201eecd7e5 resultJson={"ownerInstanceId":"node-A"}
file.insert taskId=1001 fileId=2001 fileKey=uploads/empty.xlsx sourceFilename=shop-a.xlsx relativePath=empty.xlsx shopName=shop-a matched=1 shopId=shop-9 matchedUserId=42 platform=amazon companyName=ACME 有限公司 matchStatus=MATCHED matchMessage= status=PENDING totalRows=0 processedRows=0 errorMessage=null finishedAtSet=false createdAtEqualsTaskNow=true
result.insert taskId=1001 moduleType=PUBLISH sourceFilename=shop-a.xlsx sourceFileUrl=uploads/empty.xlsx resultContentType=application/vnd.openxmlformats-officedocument.spreadsheetml.sheet rowCount=0 success=0 errorMessage=null userId=7 createdAtEqualsTaskNow=true
tx.commit
vo: taskId=1001 taskNo=PUBLISH-<snowflake> sourceFileCount=1 totalRows=0 pageSize=50
vo.file fileId=2001 fileKey=uploads/empty.xlsx shopName=shop-a matched=true status=PENDING totalRows=0 percent=0 errorMessage=null
== 行含 null:计数含 null 而落库跳 null,品牌落库前过 BrandLabel.strip ==
tx.begin
task.insert taskNo=PUBLISH-<snowflake> moduleType=PUBLISH status=PENDING taskMode=PYTHON_QUEUE sourceFileCount=1 successFileCount=0 failedFileCount=0 userId=7 createdBy=user:7 deviceId=d errorMessage=null finishedAtSet=false requestJson.keys=[files,fileKey,originalFilename,relativePath,user_id,publish_country,sync_countries] requestJson.digest=f87ffd176e5e resultJson={"ownerInstanceId":"node-A"}
file.insert taskId=1001 fileId=2001 fileKey=uploads/null-row.xlsx sourceFilename=shop-a.xlsx relativePath=n.xlsx shopName=shop-a matched=1 shopId=shop-9 matchedUserId=42 platform=amazon companyName=ACME 有限公司 matchStatus=MATCHED matchMessage= status=PENDING totalRows=3 processedRows=0 errorMessage=null finishedAtSet=false createdAtEqualsTaskNow=true
item.insertBatch count=2 taskId=1001 fileId=2001 rowIndex=[1,2] asins=[B001,B002] brands=[NIKE: X,李宁] itemCreatedAtEqualsTaskNow=false
result.insert taskId=1001 moduleType=PUBLISH sourceFilename=shop-a.xlsx sourceFileUrl=uploads/null-row.xlsx resultContentType=application/vnd.openxmlformats-officedocument.spreadsheetml.sheet rowCount=3 success=0 errorMessage=null userId=7 createdAtEqualsTaskNow=true
tx.commit
vo: taskId=1001 taskNo=PUBLISH-<snowflake> sourceFileCount=1 totalRows=3 pageSize=50
vo.file fileId=2001 fileKey=uploads/null-row.xlsx shopName=shop-a matched=true status=PENDING totalRows=3 percent=0 errorMessage=null
== 建单被拒的七格:事务未开、一次库都不碰 ==
request=null -> BusinessException: 请求不能为空
userId=null -> BusinessException: user_id 不合法
userId=0 -> BusinessException: user_id 不合法
files=null -> BusinessException: 请先上传 Excel 文件
files=空 -> BusinessException: 请先上传 Excel 文件
publishCountry=空白 -> BusinessException: 发布国家不能为空
fileKey 重复 -> BusinessException: 上传文件重复: shop-a.xlsx
events=0(重复 fileKey 那格已 prepare 过首文件,但落库与事务都未开始)
@@ -1,3 +1,3 @@
rows=2
日期=2026-07-25;ASIN=B012345678;商品图片=;库存销量=128;销售排名=#1,245;页面浏览量=3560;售出件数=42;价格=GBP 19.99;推荐报价=GBP 18.99;品牌=Example Brand;
日期=;ASIN=B099999999;商品图片=;库存销量=;销售排名=;页面浏览量=;售出件数=;价格=;推荐报价=;品牌= Brand With Spaces ;
日期=;ASIN=B099999999;商品图片=;库存销量=;销售排名=;页面浏览量=;售出件数=;价格=;推荐报价=;品牌=Brand With Spaces;