Compare commits
17 Commits
3c44f686da
...
278eaaec2c
| Author | SHA1 | Date | |
|---|---|---|---|
| 278eaaec2c | |||
| 2f0b6b0de9 | |||
| 84f248fa6c | |||
| 49eee59a13 | |||
| 1be4d766bb | |||
| 121ae9b064 | |||
| e90e5e7f64 | |||
| d22a9e2164 | |||
| d58546d314 | |||
| 87869ba0f9 | |||
| a59a3e1f61 | |||
| 56c8a4ff88 | |||
| 660a1b7084 | |||
| 3e797ab159 | |||
| e41ede74c3 | |||
| 899bc73a23 | |||
| b9e5aa4d30 |
+28
@@ -152,3 +152,31 @@ app/update/
|
||||
app/user_data/
|
||||
target/
|
||||
*.pid
|
||||
|
||||
# ===== 2026-10-18 重构蓝图 Phase 1:只堵未来的口子(审计报告 §4.1(b))=====
|
||||
# 本仓此前 0 支构建产物入库(实测 git ls-files -i -c --exclude-standard=0),下面每条都是
|
||||
# "今天没踩到、将来会踩到"的产物面;纯新增忽略,不改任何现存规则的行为。
|
||||
# 注意:gitignore 的行内 # 不是注释(会被当模式的一部分),所以说明一律单起一行。
|
||||
# node_modules:原只写了 frontend-vue/node_modules/,admin 靠子文件兜 ⇒ 提为通用
|
||||
node_modules/
|
||||
.vite/
|
||||
**/.vite/
|
||||
playwright-report/
|
||||
blob-report/
|
||||
test-results/
|
||||
surefire-reports/
|
||||
failsafe-reports/
|
||||
# Java 编译产物此前没人挡(原只有 *$py.class)
|
||||
*.class
|
||||
*.tsbuildinfo
|
||||
*.pyd
|
||||
# Windows 原生扩展与打包残留;本仓 0 支跟踪件用这些后缀(亲测 git ls-files 计数为 0)
|
||||
*.dll
|
||||
# 关键:*.log 匹配不到 aiimage-backend.log.2026-10-11.0 这类轮转名
|
||||
*.log.*
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
desktop.ini
|
||||
# ⚠ 报告另建议把遗留的 lib//parts//var/ 收窄成 /build/、/dist/ 式根锚定前缀,本轮不做:
|
||||
# 实测盘上有 53 个 lib、87 个 dist、19 个 bin 目录,收窄等于把今天被挡住的产物一次性放成 ?? 噪声,
|
||||
# 与 Phase 1「零行为变更」的定性冲突;而它们造成的实害今天是 0(ls-files -i -c 亲测)。单独拍板。
|
||||
|
||||
@@ -72,6 +72,18 @@ public class AppearancePatentProperties {
|
||||
*/
|
||||
private int flushPendingMinutes = 1;
|
||||
|
||||
/**
|
||||
* 组装作业在 WAIT_LLM 停放期间的租约续命间隔(毫秒)。
|
||||
*
|
||||
* <p>组装作业等下一轮分片回传时 process 返回 false、执行线程退出、Worker 的执行期心跳
|
||||
* 随之取消,作业停在 RUNNING 只能靠客户端心跳经 {@code onHeartbeat} 触发
|
||||
* {@code touchRunningAssembleJobsIfStale} 按本间隔节流续命(与 similar-asin 同一套口径)。
|
||||
* 取值必须小于 job 级 stuck 扫描阈值(result-file-job.stuck-timeout-minutes,默认 5 分钟),
|
||||
* 否则停放作业在两跳续命之间就会被判陈旧、5 次重试耗尽后被误判成
|
||||
* 「文件生成任务运行超时,已达到最大重试次数」(线上任务 31354 的死法)。
|
||||
*/
|
||||
private long dbJobTouchIntervalMillis = 60000L;
|
||||
|
||||
/** 单个外观专利源文件最多解析的有效数据行数,防止 POI 用户模型撑爆堆。 */
|
||||
private int maxParseRows = 50000;
|
||||
|
||||
|
||||
+9
-1
@@ -6,7 +6,8 @@ import com.nanri.aiimage.modules.task.model.entity.TaskFileJobEntity;
|
||||
|
||||
/**
|
||||
* APPEARANCE_PATENT 结果文件 Job Handler(04 注册表)。
|
||||
* process 返回 Service 的 boolean(false=等待 LLM 异步结果,Worker 保持运行心跳);
|
||||
* process 返回 Service 的 boolean(false=停放等待下一轮分片回传触发;此时执行线程已退出、
|
||||
* Worker 的执行期心跳已取消,停放租约由客户端心跳经 AppearancePatentTaskHeartbeatSpi#onHeartbeat 续命);
|
||||
* cleanup 委托 cleanupResultFileJob;支持异步 offload;owner scoped。
|
||||
*/
|
||||
public class AppearancePatentResultFileJobHandler implements ResultFileJobHandler {
|
||||
@@ -32,6 +33,13 @@ public class AppearancePatentResultFileJobHandler implements ResultFileJobHandle
|
||||
appearancePatentTaskService.cleanupResultFileJob(job);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean fallbackAssembleOnFailure(TaskFileJobEntity job, String message) {
|
||||
// 作业重试耗尽(含 WAIT_LLM 停放被 stuck 棘轮判死)时:用已有分片/结论尽力出
|
||||
// 部分结果文件供下载,别让已跑完的检测一张表都不剩(线上任务 31302/31354)。
|
||||
return appearancePatentTaskService.fallbackAssembleResultFile(job);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsAsyncOffload() {
|
||||
return true;
|
||||
|
||||
+27
@@ -1,6 +1,9 @@
|
||||
package com.nanri.aiimage.modules.appearancepatent.service;
|
||||
|
||||
import com.nanri.aiimage.config.AppearancePatentProperties;
|
||||
import com.nanri.aiimage.modules.task.model.dto.TaskHeartbeatRequest;
|
||||
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
|
||||
import com.nanri.aiimage.modules.task.service.TaskFileJobService;
|
||||
import com.nanri.aiimage.modules.task.spi.TaskModuleHeartbeatSpi;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
@@ -10,12 +13,21 @@ import org.springframework.stereotype.Service;
|
||||
*
|
||||
* <p>心跳逻辑(缓存刷新 / 任务缓存回写)从 task 模块收回本模块,task 侧只依赖 SPI 接口,
|
||||
* 消除 task → 业务模块的编译期依赖。
|
||||
*
|
||||
* <p>onHeartbeat 顺带给结果文件组装作业续租(与 {@code SimilarAsinTaskHeartbeatSpi} 同一套口径):
|
||||
* 组装作业在 WAIT_LLM 停放期间(process 返回 false 等下一轮分片回传触发)执行线程已退出、
|
||||
* Worker 的执行期心跳已随之取消,作业停在 RUNNING 无人续命,会被 job 级 stuck 扫描按
|
||||
* updated_at 判陈旧、5 次重试耗尽后误判成「文件生成任务运行超时」(线上任务 31354)。
|
||||
* 客户端在任务执行期持续上报心跳,经这里续租即可覆盖整个停放窗口;
|
||||
* 客户端也停了的场景由 stale 收尾链路与失败兜底(fallbackAssembleResultFile)接住。
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class AppearancePatentTaskHeartbeatSpi implements TaskModuleHeartbeatSpi {
|
||||
|
||||
private final AppearancePatentTaskCacheService cacheService;
|
||||
private final TaskFileJobService taskFileJobService;
|
||||
private final AppearancePatentProperties appearancePatentProperties;
|
||||
|
||||
@Override
|
||||
public String moduleType() {
|
||||
@@ -26,4 +38,19 @@ public class AppearancePatentTaskHeartbeatSpi implements TaskModuleHeartbeatSpi
|
||||
public void touchHeartbeat(Long taskId, TaskHeartbeatRequest request) {
|
||||
cacheService.touchTaskHeartbeat(taskId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onHeartbeat(FileTaskEntity task) {
|
||||
if (task == null || task.getId() == null) {
|
||||
return;
|
||||
}
|
||||
// touchRunningAssembleJobsIfStale 的 SQL 自带「距上次刷新超过间隔才写」的节流,
|
||||
// 心跳再密也不会把库写爆,无需在这里另做节流。
|
||||
taskFileJobService.touchRunningAssembleJobsIfStale(
|
||||
task.getId(), moduleType(), jobTouchIntervalMillis());
|
||||
}
|
||||
|
||||
private long jobTouchIntervalMillis() {
|
||||
return Math.max(1_000L, appearancePatentProperties.getDbJobTouchIntervalMillis());
|
||||
}
|
||||
}
|
||||
|
||||
+83
-3
@@ -53,6 +53,7 @@ import com.nanri.aiimage.modules.task.model.entity.TaskProgressSnapshotEntity;
|
||||
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 com.nanri.aiimage.modules.task.service.TaskHeartbeatPositionService;
|
||||
import com.nanri.aiimage.modules.task.service.TaskProgressSnapshotService;
|
||||
import com.nanri.aiimage.modules.task.service.TransientPayloadStorageService;
|
||||
@@ -1889,6 +1890,67 @@ public class AppearancePatentTaskService {
|
||||
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(MODULE_TYPE, 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(MODULE_TYPE, 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(buildTaskOwnerScopeKey(task));
|
||||
if (!isJobOwnedByCurrentInstance(job)) {
|
||||
log.info("[appearance-patent] fallback assemble skipped because owner is another instance taskId={} resultId={}",
|
||||
job.getTaskId(), job.getResultId());
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/** 返回真正落库的行键;没匹配到分片行的键不会出现在里面,调用方据此决定要不要撤销已检测标记。 */
|
||||
private Set<String> mergeLlmRowsIntoSubmittedChunks(FileTaskEntity task,
|
||||
List<AppearancePatentResultRowDto> llmRows,
|
||||
@@ -2189,6 +2251,16 @@ public class AppearancePatentTaskService {
|
||||
}
|
||||
|
||||
private AppearancePatentRowOutcome.Facts assembleResultWorkbook(FileTaskEntity task, FileResultEntity result) {
|
||||
return assembleResultWorkbook(task, result, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param allowPartial 供失败兜底路径({@link #fallbackAssembleResultFile})使用:
|
||||
* 覆盖率闸门按「允许部分结果」放行——作业已判死,缺口不再有补齐窗口,
|
||||
* 此刻拦下成品只会让用户连半张表都拿不到;缺口仍由行账锚点记数。
|
||||
*/
|
||||
private AppearancePatentRowOutcome.Facts assembleResultWorkbook(FileTaskEntity task, FileResultEntity result,
|
||||
boolean allowPartial) {
|
||||
AppearancePatentParsedPayloadDto parsed = readParsedPayload(task);
|
||||
List<AppearancePatentParsedRowVo> parsedRows = parsed.getAllItems() == null
|
||||
? List.of() : parsed.getAllItems();
|
||||
@@ -2214,7 +2286,7 @@ public class AppearancePatentTaskService {
|
||||
// 覆盖率先于「本文件无结果就跳过」判定:整源文件的 LLM 结果全丢(分片被跳过、
|
||||
// 结果清空)时覆盖率是 0%,必须在这里判掉,不能让 zip 少一个文件还报任务成功。
|
||||
deliveryFacts = deliveryFacts.plus(
|
||||
validateCompleteLlmCoverage(task.getId(), item.rows(), resultMap));
|
||||
validateCompleteLlmCoverage(task.getId(), item.rows(), resultMap, allowPartial));
|
||||
List<AppearancePatentParsedRowVo> receivedRows = filterReceivedParsedRows(item.rows(), resultMap);
|
||||
if (receivedRows.isEmpty()) {
|
||||
resultMap.clear();
|
||||
@@ -2417,6 +2489,13 @@ public class AppearancePatentTaskService {
|
||||
private AppearancePatentRowOutcome.Facts validateCompleteLlmCoverage(Long taskId,
|
||||
List<AppearancePatentParsedRowVo> parsedRows,
|
||||
Map<String, AppearancePatentResultRowDto> resultMap) {
|
||||
return validateCompleteLlmCoverage(taskId, parsedRows, resultMap, false);
|
||||
}
|
||||
|
||||
private AppearancePatentRowOutcome.Facts validateCompleteLlmCoverage(Long taskId,
|
||||
List<AppearancePatentParsedRowVo> parsedRows,
|
||||
Map<String, AppearancePatentResultRowDto> resultMap,
|
||||
boolean allowPartial) {
|
||||
if (parsedRows == null || parsedRows.isEmpty()) {
|
||||
return AppearancePatentRowOutcome.Facts.EMPTY;
|
||||
}
|
||||
@@ -2432,8 +2511,9 @@ public class AppearancePatentTaskService {
|
||||
}
|
||||
double minCoverage = properties.getLlmCoverageMinRatio();
|
||||
// 已判失败的任务走的是"按已有分片出部分结果"这条既有口径,这里再抛会把成品彻底拿掉;
|
||||
// 但它不再静默:上面的行账锚点必打,缺口由调用方写进任务错误信息,用户看得到「N 行没检测」。
|
||||
if (!taskAlreadyFailed && minCoverage > 0 && facts.expectedRows() > 0
|
||||
// 失败兜底路径(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) + "% 覆盖率下限)"
|
||||
|
||||
-15
@@ -1,15 +0,0 @@
|
||||
package com.nanri.aiimage.modules.brand.model.dto;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@Schema(description = "查询失败品牌记录。Java 会将该列表输出到结果 xlsx 的“查询失败品牌” sheet。")
|
||||
public class BrandQueryFailedDto {
|
||||
|
||||
@Schema(description = "查询失败的品牌名称。")
|
||||
private String brand;
|
||||
|
||||
@Schema(description = "失败时间。由前端或爬虫侧生成后原样回传。")
|
||||
private String time;
|
||||
}
|
||||
+59
-13
@@ -81,6 +81,7 @@ import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.PushbackInputStream;
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
@@ -222,9 +223,6 @@ public class CollectDataService {
|
||||
@Value("${aiimage.collect-data.progress-dirty-window-millis:30000}")
|
||||
private long progressDirtyWindowMillis;
|
||||
|
||||
/** 上次进度统计实际落库时间戳(任务级,单机内存态;无锁竞争风险由任务分布式锁兜底)。 */
|
||||
private long lastProgressFlushMillis;
|
||||
|
||||
/** 采集源文件大小上限。0/负值回退默认 50MB,防止解析无界增长。 */
|
||||
private long resolveMaxSourceFileBytes() {
|
||||
Long configured = maxSourceFileBytes;
|
||||
@@ -518,34 +516,51 @@ public class CollectDataService {
|
||||
changed = true;
|
||||
}
|
||||
if (!changed) {
|
||||
// 内容未变化:仅当脏数据兜底窗口到期时才强制刷新一次,
|
||||
// 内容未变化:仅当该任务自身的脏数据兜底窗口到期时才强制刷新一次,
|
||||
// 否则零 UPDATE(重复心跳幂等)。
|
||||
if (!shouldForceProgressFlush()) {
|
||||
if (!shouldForceProgressFlush(task)) {
|
||||
return;
|
||||
}
|
||||
} else if (shouldThrottleProgressFlush()) {
|
||||
} else if (shouldThrottleProgressFlush(task)) {
|
||||
// 节流窗口内:合并写(只更新内存态、不落库),窗口到期后统一持久化。
|
||||
return;
|
||||
}
|
||||
persistStats(task, stats);
|
||||
// 计时就写在这个随 UPDATE 一起落库的字段上:写失败时库里的 updated_at 仍是旧值,
|
||||
// 下一条心跳在 :479 重新 selectById 读到的还是旧值,会立刻补刷——不需要额外的
|
||||
// catch 回滚内存态(那会多一个 catch 块,且掩盖「本方法每次心跳都重读 DB」这一事实)。
|
||||
task.setUpdatedAt(LocalDateTime.now());
|
||||
fileTaskMapper.updateById(task);
|
||||
lastProgressFlushMillis = System.currentTimeMillis();
|
||||
}
|
||||
|
||||
/**
|
||||
* 节流判定:progressThrottleMillis>0 且距上次实际落库未超过窗口 → 合并写(跳过 UPDATE)。
|
||||
* 节流判定:距**该任务自身**上次落库未超过窗口 → 合并写(跳过 UPDATE)。
|
||||
* progressThrottleMillis<=0 视为关闭节流,恒返回 false(每次心跳都落库,兼容旧行为)。
|
||||
*/
|
||||
private boolean shouldThrottleProgressFlush() {
|
||||
private boolean shouldThrottleProgressFlush(FileTaskEntity task) {
|
||||
return progressThrottleMillis > 0
|
||||
&& System.currentTimeMillis() - lastProgressFlushMillis < progressThrottleMillis;
|
||||
&& millisSinceTaskFlush(task) < progressThrottleMillis;
|
||||
}
|
||||
|
||||
/** 脏数据兜底判定:progressDirtyWindowMillis>0 且距上次实际落库超过窗口 → 强制刷新一次。 */
|
||||
private boolean shouldForceProgressFlush() {
|
||||
/** 脏数据兜底判定:该任务自身距上次落库超过窗口 → 强制刷新一次,保证陈旧巡检看不到在跑的任务。 */
|
||||
private boolean shouldForceProgressFlush(FileTaskEntity task) {
|
||||
return progressDirtyWindowMillis > 0
|
||||
&& System.currentTimeMillis() - lastProgressFlushMillis >= progressDirtyWindowMillis;
|
||||
&& millisSinceTaskFlush(task) >= progressDirtyWindowMillis;
|
||||
}
|
||||
|
||||
/**
|
||||
* 计时一律取任务自身的 updated_at,不许换成服务上的单个时间戳:本方法是单例,
|
||||
* 全局时间戳会被并发任务(实测约 20 支采集任务同时在跑)中任何一个的落库重置,
|
||||
* 于是「心跳内容不变」的任务永远落在别人刚刷过的窗口里被丢弃,updated_at 停止前进,
|
||||
* 30 分钟陈旧巡检把还在正常回传分片的活任务判死并终态化(task 31253:20:47 仍在回传,
|
||||
* 21:52 被 stale 收尾,结果文件按当时的空明细出表)。
|
||||
*/
|
||||
private long millisSinceTaskFlush(FileTaskEntity task) {
|
||||
LocalDateTime last = task.getUpdatedAt();
|
||||
if (last == null) {
|
||||
return Long.MAX_VALUE;
|
||||
}
|
||||
return Math.max(0L, Duration.between(last, LocalDateTime.now()).toMillis());
|
||||
}
|
||||
|
||||
@Scheduled(cron = "${aiimage.collect-data.stale-check-cron:0 */2 * * * *}")
|
||||
@@ -1163,6 +1178,8 @@ public class CollectDataService {
|
||||
batch -> streamFinalRows(task.getId(), batch),
|
||||
stats.summaries,
|
||||
batch -> streamRawRows(task.getId(), batch));
|
||||
// 空表头文件不得当作成果交付:先校验再上传(见 guardDetailRowsWritten)。
|
||||
guardDetailRowsWritten(task.getId(), finalRowCount, stats);
|
||||
String objectKey = ossStorageService.uploadResultFile(xlsx, MODULE_TYPE);
|
||||
|
||||
// 复用同一份 stats 更新 finalRowCount 后再持久化,避免重复 loadStats 丢失 summaries。
|
||||
@@ -1198,6 +1215,10 @@ public class CollectDataService {
|
||||
.set(FileTaskEntity::getStatus, STATUS_SUCCESS)
|
||||
.set(FileTaskEntity::getSuccessFileCount, 1)
|
||||
.set(FileTaskEntity::getFailedFileCount, 0)
|
||||
// 组装阶段按明细表重算的 finalRowCount 必须随本条 UPDATE 一起落库:
|
||||
// persistStats 只改内存实体,此前这条语句不含 result_json,导致界面上的
|
||||
// 「保留 N 行」永远停在组装前的插入计数(task 31253:表里 0 行仍显示 93)。
|
||||
.set(FileTaskEntity::getResultJson, task.getResultJson())
|
||||
.set(FileTaskEntity::getErrorMessage, null)
|
||||
.set(FileTaskEntity::getUpdatedAt, LocalDateTime.now())
|
||||
.set(FileTaskEntity::getFinishedAt, LocalDateTime.now()));
|
||||
@@ -1225,6 +1246,31 @@ public class CollectDataService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 空明细守卫:明细 sheet 的行唯一来自 biz_task_result_item,写出的行数必须与表内行数一致。
|
||||
* 不一致就抛异常让结果文件作业重试,而不是上传一份只有表头的 xlsx 再把任务标成成功——
|
||||
* 后者在界面上就是「已完成 + 保留 N 行 + 下载下来是空白」(task 31253 实测:明细表 0 行、
|
||||
* 出表耗时 111ms、文件 4373 字节纯表头,而 result_json 里的计数仍写着 93,两边都对不上账)。
|
||||
* 表内确实 0 行且计数也是 0(全部行被过滤掉)属于合法空结果,照常出表。
|
||||
*/
|
||||
private void guardDetailRowsWritten(Long taskId, long finalRowCount, CollectDataStats stats) {
|
||||
Long stored = taskResultItemMapper.selectCount(new LambdaQueryWrapper<TaskResultItemEntity>()
|
||||
.eq(TaskResultItemEntity::getTaskId, taskId)
|
||||
.in(TaskResultItemEntity::getModuleType, MODULE_TYPE, LEGACY_MODULE_TYPE));
|
||||
long itemRows = stored == null ? 0L : stored;
|
||||
if (itemRows > 0L) {
|
||||
if (finalRowCount < itemRows) {
|
||||
throw new BusinessException("采集结果明细共 " + itemRows + " 行,本次仅写出 " + finalRowCount
|
||||
+ " 行,结果文件不生成缺行版本,等待重试");
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (stats != null && stats.finalRowCount > 0) {
|
||||
throw new BusinessException("采集结果计数为 " + stats.finalRowCount + " 行,但结果明细表为空,"
|
||||
+ "结果文件不生成空表,等待重试");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 分批流式读取采集结果明细(按 id 分页游标),每批消费完即可释放,
|
||||
* 避免几十万行明细对象整体驻留堆内存;返回写入的明细行总数。
|
||||
|
||||
+149
-150
@@ -5,7 +5,6 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
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.util.ExcelStreamReader;
|
||||
import com.nanri.aiimage.config.TaskPressureProperties;
|
||||
import com.nanri.aiimage.modules.file.service.oss.OssStorageService;
|
||||
@@ -31,13 +30,13 @@ 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.AbstractModuleTaskCacheService;
|
||||
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 com.nanri.aiimage.modules.task.service.TaskResultPayloadService;
|
||||
import com.nanri.aiimage.modules.task.service.pipeline.AbstractShopPayloadTaskPipeline;
|
||||
import com.nanri.aiimage.modules.ziniao.service.ZiniaoShopSwitchService;
|
||||
import cn.hutool.core.util.IdUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
@@ -64,9 +63,8 @@ import com.nanri.aiimage.modules.task.model.vo.TaskProgressLightBatchVo;
|
||||
import com.nanri.aiimage.modules.task.service.TaskProgressLightAssembler;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class PriceTrackTaskService {
|
||||
public class PriceTrackTaskService extends AbstractShopPayloadTaskPipeline<PriceTrackSubmitResultRequest.ShopResult> {
|
||||
|
||||
private static final String MODULE_TYPE = "PRICE_TRACK";
|
||||
/** 批量进度查询的任务 id 上限(轮询端点防滥用,与 patroldelete/deletebrand 保持一致)。 */
|
||||
@@ -79,11 +77,8 @@ public class PriceTrackTaskService {
|
||||
private static final String ASIN_ROWS_PAYLOAD_SCOPE = "price-track-asin-rows";
|
||||
private static final String NO_USABLE_ROWS_ERROR = "未收到有效跟价数据,未生成结果文件";
|
||||
|
||||
private final FileTaskMapper fileTaskMapper;
|
||||
private final FileResultMapper fileResultMapper;
|
||||
private final PriceTrackShopCandidateMapper candidateMapper;
|
||||
private final ZiniaoShopSwitchService ziniaoShopSwitchService;
|
||||
private final OssStorageService ossStorageService;
|
||||
/** 结果下载直链解析(2026-09 从本类抽到 common,消除 11 处逐字重复) */
|
||||
private final com.nanri.aiimage.common.service.ResultDownloadResolver resultDownloadResolver;
|
||||
private final ObjectMapper objectMapper;
|
||||
@@ -93,8 +88,6 @@ public class PriceTrackTaskService {
|
||||
private final PriceTrackLoopRunService priceTrackLoopRunService;
|
||||
private final TaskPressureProperties taskPressureProperties;
|
||||
private final TaskResultPayloadService taskResultPayloadService;
|
||||
private final TaskFileJobService taskFileJobService;
|
||||
private final TaskDistributedLockService taskDistributedLockService;
|
||||
private final TaskProgressLightAssembler taskProgressLightAssembler;
|
||||
private final com.nanri.aiimage.modules.file.service.LocalFileStorageService localFileStorageService;
|
||||
/**
|
||||
@@ -103,6 +96,79 @@ public class PriceTrackTaskService {
|
||||
*/
|
||||
private final org.springframework.transaction.PlatformTransactionManager transactionManager;
|
||||
|
||||
/** 参数表顺序=原先 {@code @RequiredArgsConstructor} 生成的那一个(夹具按位置 new,见 PriceTrackSnapshotTest:163)。 */
|
||||
public PriceTrackTaskService(FileTaskMapper fileTaskMapper,
|
||||
FileResultMapper fileResultMapper,
|
||||
PriceTrackShopCandidateMapper candidateMapper,
|
||||
ZiniaoShopSwitchService ziniaoShopSwitchService,
|
||||
OssStorageService ossStorageService,
|
||||
com.nanri.aiimage.common.service.ResultDownloadResolver resultDownloadResolver,
|
||||
ObjectMapper objectMapper,
|
||||
SkipPriceAsinService skipPriceAsinService,
|
||||
PriceTrackExcelAssemblyService excelAssemblyService,
|
||||
PriceTrackTaskCacheService priceTrackTaskCacheService,
|
||||
PriceTrackLoopRunService priceTrackLoopRunService,
|
||||
TaskPressureProperties taskPressureProperties,
|
||||
TaskResultPayloadService taskResultPayloadService,
|
||||
TaskFileJobService taskFileJobService,
|
||||
TaskDistributedLockService taskDistributedLockService,
|
||||
TaskProgressLightAssembler taskProgressLightAssembler,
|
||||
com.nanri.aiimage.modules.file.service.LocalFileStorageService localFileStorageService,
|
||||
org.springframework.transaction.PlatformTransactionManager transactionManager) {
|
||||
super(fileTaskMapper, fileResultMapper, taskDistributedLockService, taskFileJobService, ossStorageService);
|
||||
this.candidateMapper = candidateMapper;
|
||||
this.ziniaoShopSwitchService = ziniaoShopSwitchService;
|
||||
this.resultDownloadResolver = resultDownloadResolver;
|
||||
this.objectMapper = objectMapper;
|
||||
this.skipPriceAsinService = skipPriceAsinService;
|
||||
this.excelAssemblyService = excelAssemblyService;
|
||||
this.priceTrackTaskCacheService = priceTrackTaskCacheService;
|
||||
this.priceTrackLoopRunService = priceTrackLoopRunService;
|
||||
this.taskPressureProperties = taskPressureProperties;
|
||||
this.taskResultPayloadService = taskResultPayloadService;
|
||||
this.taskProgressLightAssembler = taskProgressLightAssembler;
|
||||
this.localFileStorageService = localFileStorageService;
|
||||
this.transactionManager = transactionManager;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// 管线钩子(Phase 3 首迁·孪生支之二)
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
@Override
|
||||
protected String moduleType() {
|
||||
return MODULE_TYPE;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected FileTaskEntity loadTaskForSubmission(Long taskId) {
|
||||
FileTaskEntity task = loadTaskForExecution(taskId);
|
||||
// 底座刻意不打日志(七支里只有本支在终态拒绝前 warn 一句,见 admitSubmission 的注释),
|
||||
// 而那句的位置就在「模块校验已过、throw 之前」——骨架里唯一等价的落点就是这里,同条件同顺序。
|
||||
// 删掉它就是改现网可观测行为(巡检按这句数过被拒的回传)。
|
||||
if (task != null && MODULE_TYPE.equals(task.getModuleType())
|
||||
&& ("SUCCESS".equals(task.getStatus()) || "FAILED".equals(task.getStatus()))) {
|
||||
log.warn("[price-track] submitResult rejected taskId={} status={}", taskId, task.getStatus());
|
||||
}
|
||||
return task;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected AbstractModuleTaskCacheService<PriceTrackSubmitResultRequest.ShopResult> taskCacheService() {
|
||||
return priceTrackTaskCacheService;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String submissionLockLogTag() {
|
||||
return "price-track";
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String normalizeShopKey(String rawShopName) {
|
||||
return ziniaoShopSwitchService.normalizeShopName(rawShopName);
|
||||
}
|
||||
|
||||
|
||||
private FileTaskEntity loadTaskForExecution(Long taskId) {
|
||||
// 缓存行仅当 requestJson 非空时视为可用(历史语义),否则回落 DB
|
||||
return TaskFinalizeSupport.loadTaskForExecution(fileTaskMapper, priceTrackTaskCacheService, MODULE_TYPE, taskId,
|
||||
@@ -300,11 +366,7 @@ public class PriceTrackTaskService {
|
||||
if ("SUCCESS".equals(task.getStatus()) || "FAILED".equals(task.getStatus())) {
|
||||
return null;
|
||||
}
|
||||
List<FileResultEntity> results = fileResultMapper.selectList(
|
||||
new LambdaQueryWrapper<FileResultEntity>()
|
||||
.eq(FileResultEntity::getTaskId, taskId)
|
||||
.eq(FileResultEntity::getModuleType, MODULE_TYPE)
|
||||
.orderByAsc(FileResultEntity::getId));
|
||||
List<FileResultEntity> results = listScopeRows(taskId);
|
||||
if (results.isEmpty()) {
|
||||
task.setStatus("FAILED");
|
||||
task.setErrorMessage(normalizedError);
|
||||
@@ -498,20 +560,11 @@ public class PriceTrackTaskService {
|
||||
final Map<String, List<Map<String, String>>> parsedAsinRows = asinRowsForPayload;
|
||||
return inRequiredTransaction(() -> {
|
||||
// 创建任务记录
|
||||
FileTaskEntity task = new FileTaskEntity();
|
||||
task.setTaskNo(MODULE_TYPE + "-" + IdUtil.getSnowflakeNextIdStr());
|
||||
task.setModuleType(MODULE_TYPE);
|
||||
task.setTaskMode("PYTHON_QUEUE");
|
||||
task.setStatus("RUNNING");
|
||||
task.setSourceFileCount(uniqueItems.size());
|
||||
FileTaskEntity task = newTaskHeader("RUNNING", "PYTHON_QUEUE", request.getUserId(),
|
||||
deviceId, uniqueItems.size());
|
||||
task.setSuccessFileCount(0);
|
||||
task.setFailedFileCount(0);
|
||||
task.setCreatedBy("user:" + request.getUserId());
|
||||
task.setUserId(request.getUserId());
|
||||
task.setDeviceId(AdminAuthSupport.normalizeDeviceId(deviceId));
|
||||
task.setCreatedAt(LocalDateTime.now());
|
||||
task.setUpdatedAt(LocalDateTime.now());
|
||||
fileTaskMapper.insert(task);
|
||||
insertTask(task);
|
||||
priceTrackTaskCacheService.touchTaskHeartbeat(task.getId());
|
||||
if (request.isAsinMode()) {
|
||||
saveTaskAsinRowsPayload(task.getId(), parsedAsinRows);
|
||||
@@ -528,14 +581,8 @@ public class PriceTrackTaskService {
|
||||
for (PriceTrackMatchShopsVo.PriceTrackShopQueueItem item : uniqueItems) {
|
||||
String norm = ziniaoShopSwitchService.normalizeShopName(item.getShopName());
|
||||
if (norm.isBlank()) throw new BusinessException("店铺名称无效");
|
||||
FileResultEntity fr = new FileResultEntity();
|
||||
fr.setTaskId(task.getId());
|
||||
fr.setModuleType(MODULE_TYPE);
|
||||
fr.setSourceFilename(norm);
|
||||
fr.setSourceFileUrl(Objects.toString(item.getShopId(), null));
|
||||
fr.setUserId(request.getUserId());
|
||||
fr.setSuccess(0);
|
||||
fr.setCreatedAt(LocalDateTime.now());
|
||||
FileResultEntity fr = newScopeRow(task.getId(), request.getUserId(), norm,
|
||||
Objects.toString(item.getShopId(), null), null, 0);
|
||||
fileResultMapper.insert(fr);
|
||||
PriceTrackResultItemVo snapshotItem = toSnapshotVo(fr, item, task.getStatus());
|
||||
snapshotItem.setLoopRunId(request.getLoopRunId());
|
||||
@@ -589,77 +636,63 @@ public class PriceTrackTaskService {
|
||||
}
|
||||
|
||||
public void submitResult(Long taskId, PriceTrackSubmitResultRequest request) {
|
||||
if (taskId == null || taskId <= 0) throw new BusinessException("taskId 不合法");
|
||||
if (request == null || request.getShops() == null || request.getShops().isEmpty()) {
|
||||
throw new BusinessException("shops 不能为空");
|
||||
submitShopScopedResults(taskId,
|
||||
request == null ? null : request.getShops(),
|
||||
PriceTrackSubmitResultRequest.ShopResult::getShopName,
|
||||
TerminalRejection.IDEMPOTENT,
|
||||
null);
|
||||
}
|
||||
|
||||
/** 迁移前那句 {@code [price-track] submitResult received ...} 的位置:准入已过、索引已建、行还没开始处理。 */
|
||||
@Override
|
||||
protected void onPayloadIndexed(FileTaskEntity task,
|
||||
Map<String, PriceTrackSubmitResultRequest.ShopResult> payloadByShopKey) {
|
||||
log.info("[price-track] submitResult received taskId={} payloadShopCount={} payloadKeys={}",
|
||||
task.getId(), payloadByShopKey.size(), payloadByShopKey.keySet());
|
||||
}
|
||||
|
||||
/**
|
||||
* 本支判序=「先判 error → 再判 success==FALSE → 处理删跳过 ASIN 的信号 → 最后才合并」,
|
||||
* 与 ShopMatch(先合并再判 error)相反;这段整体留在被迁支里,底座一个字都不碰
|
||||
* (家族层 javadoc 点名「刻意不沉」的两处之一,沉了就是把两支语义并成一支)。
|
||||
*/
|
||||
@Override
|
||||
protected void applyShopResultRow(Long taskId,
|
||||
FileTaskEntity task,
|
||||
FileResultEntity fr,
|
||||
String shopKey,
|
||||
PriceTrackSubmitResultRequest.ShopResult payload) {
|
||||
if (payload.getError() != null && !payload.getError().isBlank()) {
|
||||
finalizeFailedShop(fr, shopKey, payload, payload.getError());
|
||||
return;
|
||||
}
|
||||
try (TaskDistributedLockService.LockHandle ignored = acquireTaskLockOrThrow(taskId)) {
|
||||
FileTaskEntity task = loadTaskForExecution(taskId);
|
||||
if (task == null || !MODULE_TYPE.equals(task.getModuleType())) {
|
||||
throw new BusinessException("任务不存在");
|
||||
}
|
||||
if ("SUCCESS".equals(task.getStatus()) || "FAILED".equals(task.getStatus())) {
|
||||
log.warn("[price-track] submitResult rejected taskId={} status={}", taskId, task.getStatus());
|
||||
throw new BusinessException(40901, "任务已结束,拒绝重复提交");
|
||||
}
|
||||
priceTrackTaskCacheService.touchTaskHeartbeat(taskId);
|
||||
List<FileResultEntity> resultRows = fileResultMapper.selectList(
|
||||
new LambdaQueryWrapper<FileResultEntity>()
|
||||
.eq(FileResultEntity::getTaskId, taskId)
|
||||
.eq(FileResultEntity::getModuleType, MODULE_TYPE)
|
||||
.orderByAsc(FileResultEntity::getId));
|
||||
Map<String, PriceTrackSubmitResultRequest.ShopResult> payloadByShop = new LinkedHashMap<>();
|
||||
for (PriceTrackSubmitResultRequest.ShopResult sr : request.getShops()) {
|
||||
if (sr == null) continue;
|
||||
String key = ziniaoShopSwitchService.normalizeShopName(sr.getShopName());
|
||||
if (!key.isBlank()) payloadByShop.put(key, sr);
|
||||
}
|
||||
log.info("[price-track] submitResult received taskId={} payloadShopCount={} payloadKeys={}",
|
||||
taskId, payloadByShop.size(), payloadByShop.keySet());
|
||||
boolean changed = false;
|
||||
for (FileResultEntity fr : resultRows) {
|
||||
String shopKey = fr.getSourceFilename();
|
||||
PriceTrackSubmitResultRequest.ShopResult payload = shopKey == null ? null : payloadByShop.get(shopKey);
|
||||
if (payload == null) {
|
||||
continue;
|
||||
}
|
||||
changed = true;
|
||||
if (payload.getError() != null && !payload.getError().isBlank()) {
|
||||
finalizeFailedShop(fr, shopKey, payload, payload.getError());
|
||||
continue;
|
||||
}
|
||||
if (Boolean.FALSE.equals(payload.getSuccess())) {
|
||||
finalizeFailedShop(fr, shopKey, payload, "shop processing failed");
|
||||
continue;
|
||||
}
|
||||
handleSkipAsinDeletionSignals(shopKey, payload);
|
||||
PriceTrackSubmitResultRequest.ShopResult merged = mergeShopPayload(taskId, shopKey, payload);
|
||||
if (!Boolean.TRUE.equals(merged.getSuccess())) {
|
||||
continue;
|
||||
}
|
||||
if (countPayloadRows(merged) <= 0) {
|
||||
markResultFailed(fr, buildNoUsableRowsMessage(payload));
|
||||
priceTrackTaskCacheService.removeShopMergedPayload(taskId, shopKey);
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
enqueueResultFileAssembly(fr, shopKey, merged);
|
||||
priceTrackTaskCacheService.removeShopMergedPayload(taskId, shopKey);
|
||||
} catch (Exception ex) {
|
||||
markResultFailed(fr, ex.getMessage() == null ? "assemble price-track result failed" : ex.getMessage());
|
||||
priceTrackTaskCacheService.removeShopMergedPayload(taskId, shopKey);
|
||||
}
|
||||
}
|
||||
if (!changed) {
|
||||
return;
|
||||
}
|
||||
List<FileResultEntity> latest = fileResultMapper.selectList(
|
||||
new LambdaQueryWrapper<FileResultEntity>()
|
||||
.eq(FileResultEntity::getTaskId, taskId)
|
||||
.eq(FileResultEntity::getModuleType, MODULE_TYPE)
|
||||
.orderByAsc(FileResultEntity::getId));
|
||||
updateTaskStatusFromLatestRows(task, latest);
|
||||
if (Boolean.FALSE.equals(payload.getSuccess())) {
|
||||
finalizeFailedShop(fr, shopKey, payload, "shop processing failed");
|
||||
return;
|
||||
}
|
||||
handleSkipAsinDeletionSignals(shopKey, payload);
|
||||
PriceTrackSubmitResultRequest.ShopResult merged = mergeShopPayload(taskId, shopKey, payload);
|
||||
if (!Boolean.TRUE.equals(merged.getSuccess())) {
|
||||
return;
|
||||
}
|
||||
// 本支闸门只看 success,不看行数 ⇒「说完成了但一行可用 ASIN 都没有」在这里可达(ShopMatch 不可达)
|
||||
if (countPayloadRows(merged) <= 0) {
|
||||
markResultFailed(fr, buildNoUsableRowsMessage(payload));
|
||||
priceTrackTaskCacheService.removeShopMergedPayload(taskId, shopKey);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
enqueueResultFileAssembly(fr, shopKey, merged);
|
||||
priceTrackTaskCacheService.removeShopMergedPayload(taskId, shopKey);
|
||||
} catch (Exception ex) {
|
||||
markResultFailed(fr, ex.getMessage() == null ? "assemble price-track result failed" : ex.getMessage());
|
||||
priceTrackTaskCacheService.removeShopMergedPayload(taskId, shopKey);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onShopRowsRecomputed(FileTaskEntity task, List<FileResultEntity> latestRows) {
|
||||
updateTaskStatusFromLatestRows(task, latestRows);
|
||||
}
|
||||
|
||||
public boolean tryFinalizeTask(Long taskId, boolean fromCompensation) {
|
||||
@@ -678,11 +711,7 @@ public class PriceTrackTaskService {
|
||||
cleanupTaskCacheIfTerminal(taskId, task.getStatus());
|
||||
return false;
|
||||
}
|
||||
List<FileResultEntity> latest = fileResultMapper.selectList(
|
||||
new LambdaQueryWrapper<FileResultEntity>()
|
||||
.eq(FileResultEntity::getTaskId, taskId)
|
||||
.eq(FileResultEntity::getModuleType, MODULE_TYPE)
|
||||
.orderByAsc(FileResultEntity::getId));
|
||||
List<FileResultEntity> latest = listScopeRows(taskId);
|
||||
if (latest.isEmpty()) {
|
||||
task.setStatus("FAILED");
|
||||
task.setErrorMessage("task details missing, cannot finalize automatically");
|
||||
@@ -740,11 +769,7 @@ public class PriceTrackTaskService {
|
||||
if (!changed && cachedPayloadByShop.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
List<FileResultEntity> refreshed = fileResultMapper.selectList(
|
||||
new LambdaQueryWrapper<FileResultEntity>()
|
||||
.eq(FileResultEntity::getTaskId, taskId)
|
||||
.eq(FileResultEntity::getModuleType, MODULE_TYPE)
|
||||
.orderByAsc(FileResultEntity::getId));
|
||||
List<FileResultEntity> refreshed = listScopeRows(taskId);
|
||||
updateTaskStatusFromLatestRows(task, refreshed);
|
||||
return true;
|
||||
}
|
||||
@@ -771,11 +796,7 @@ public class PriceTrackTaskService {
|
||||
private void reconcileTaskAfterResultRemoval(Long taskId) {
|
||||
FileTaskEntity task = loadTaskForExecution(taskId);
|
||||
if (task == null || !MODULE_TYPE.equals(task.getModuleType())) return;
|
||||
List<FileResultEntity> latest = fileResultMapper.selectList(
|
||||
new LambdaQueryWrapper<FileResultEntity>()
|
||||
.eq(FileResultEntity::getTaskId, taskId)
|
||||
.eq(FileResultEntity::getModuleType, MODULE_TYPE)
|
||||
.orderByAsc(FileResultEntity::getId));
|
||||
List<FileResultEntity> latest = listScopeRows(taskId);
|
||||
if (latest.isEmpty()) {
|
||||
priceTrackLoopRunService.syncLoopRunAfterChildRemoved(taskId);
|
||||
fileTaskMapper.deleteById(taskId);
|
||||
@@ -842,19 +863,9 @@ public class PriceTrackTaskService {
|
||||
boolean partialFailure = result.getErrorMessage() != null && !result.getErrorMessage().isBlank();
|
||||
try {
|
||||
excelAssemblyService.writeWorkbook(xlsx, countries);
|
||||
String objectKey = ossStorageService.uploadResultFile(xlsx, MODULE_TYPE);
|
||||
if (partialFailure) {
|
||||
result.setSuccess(0);
|
||||
} else {
|
||||
result.setSuccess(1);
|
||||
result.setErrorMessage(null);
|
||||
}
|
||||
result.setResultFilename(stem + ".xlsx");
|
||||
result.setResultFileUrl(objectKey);
|
||||
result.setResultFileSize(xlsx.length());
|
||||
result.setResultContentType(CONTENT_TYPE_XLSX);
|
||||
result.setRowCount(excelAssemblyService.countRows(countries));
|
||||
fileResultMapper.updateById(result);
|
||||
// 上传+结果行 6 列落库是六支逐字相同的那一截,沉在底座;清理点各支不同,仍留在本层 finally
|
||||
publishResultFile(result, xlsx, stem + ".xlsx", CONTENT_TYPE_XLSX,
|
||||
excelAssemblyService.countRows(countries), partialFailure);
|
||||
} finally {
|
||||
cn.hutool.core.io.FileUtil.del(xlsx);
|
||||
}
|
||||
@@ -876,11 +887,7 @@ public class PriceTrackTaskService {
|
||||
assembleShopResult(result, job.getScopeKey(), payload);
|
||||
FileTaskEntity task = loadTaskForExecution(job.getTaskId());
|
||||
if (task != null && MODULE_TYPE.equals(task.getModuleType())) {
|
||||
List<FileResultEntity> latest = fileResultMapper.selectList(
|
||||
new LambdaQueryWrapper<FileResultEntity>()
|
||||
.eq(FileResultEntity::getTaskId, job.getTaskId())
|
||||
.eq(FileResultEntity::getModuleType, MODULE_TYPE)
|
||||
.orderByAsc(FileResultEntity::getId));
|
||||
List<FileResultEntity> latest = listScopeRows(job.getTaskId());
|
||||
updateTaskStatusFromLatestRows(task, latest);
|
||||
}
|
||||
}
|
||||
@@ -902,7 +909,7 @@ public class PriceTrackTaskService {
|
||||
applyServerModifyCounts(result.getTaskId(), payload);
|
||||
taskResultPayloadService.saveLatest(result.getTaskId(), MODULE_TYPE, shopKey, payload);
|
||||
markResultFilePending(result, shopKey, payload, preserveFailure);
|
||||
taskFileJobService.enqueueAssembleResult(result.getTaskId(), MODULE_TYPE, result.getId(), shopKey);
|
||||
enqueueResultAssembly(result.getTaskId(), result.getId(), shopKey);
|
||||
}
|
||||
|
||||
private void applyServerModifyCounts(
|
||||
@@ -1894,11 +1901,7 @@ public class PriceTrackTaskService {
|
||||
private PriceTrackTaskDetailVo buildTaskDetail(FileTaskEntity task) {
|
||||
PriceTrackTaskDetailVo detail = new PriceTrackTaskDetailVo();
|
||||
detail.setTask(toTaskItemVo(task));
|
||||
List<FileResultEntity> rows = fileResultMapper.selectList(
|
||||
new LambdaQueryWrapper<FileResultEntity>()
|
||||
.eq(FileResultEntity::getTaskId, task.getId())
|
||||
.eq(FileResultEntity::getModuleType, MODULE_TYPE)
|
||||
.orderByAsc(FileResultEntity::getId));
|
||||
List<FileResultEntity> rows = listScopeRows(task.getId());
|
||||
for (FileResultEntity fr : rows) {
|
||||
detail.getItems().add(toHistoryItemVo(fr, task));
|
||||
}
|
||||
@@ -1971,11 +1974,7 @@ public class PriceTrackTaskService {
|
||||
}
|
||||
|
||||
private List<PriceTrackResultItemVo> buildSnapshotFromDb(Long taskId, String taskStatus) {
|
||||
List<FileResultEntity> rows = fileResultMapper.selectList(
|
||||
new LambdaQueryWrapper<FileResultEntity>()
|
||||
.eq(FileResultEntity::getTaskId, taskId)
|
||||
.eq(FileResultEntity::getModuleType, MODULE_TYPE)
|
||||
.orderByAsc(FileResultEntity::getId));
|
||||
List<FileResultEntity> rows = listScopeRows(taskId);
|
||||
List<PriceTrackResultItemVo> list = new ArrayList<>();
|
||||
for (FileResultEntity fr : rows) list.add(toHistoryItemVo(fr, taskStatus));
|
||||
return list;
|
||||
@@ -2264,7 +2263,7 @@ public class PriceTrackTaskService {
|
||||
* 显式开启一个短事务:锁已在事务外获取,这里只包住 DB 段,
|
||||
* 保证原来同属一个 @Transactional 的多条写仍在同一事务内。
|
||||
*/
|
||||
private <T> T inNewTransaction(java.util.function.Supplier<T> action) {
|
||||
private <R> R inNewTransaction(java.util.function.Supplier<R> action) {
|
||||
if (transactionManager == null) {
|
||||
// 单测直接 new 出本类(history 见 QueryAsinSnapshotJsonThrottleTest 同类用法)时无事务管理器
|
||||
return action.get();
|
||||
@@ -2278,7 +2277,7 @@ public class PriceTrackTaskService {
|
||||
* 默认传播(REQUIRED)事务段:供「外部 IO 已移出、只剩 DB 写」的方法体使用。
|
||||
* 与 {@link #inNewTransaction} 的差别是不挂起外层事务;单测直接 new 本类时退化为直调。
|
||||
*/
|
||||
private <T> T inRequiredTransaction(java.util.function.Supplier<T> action) {
|
||||
private <R> R inRequiredTransaction(java.util.function.Supplier<R> action) {
|
||||
if (transactionManager == null) {
|
||||
return action.get();
|
||||
}
|
||||
|
||||
-15
@@ -1,15 +0,0 @@
|
||||
package com.nanri.aiimage.modules.shopdatacrawl.model.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 结果文件最近的 ASSEMBLE_RESULT 文件任务(按 job id 取最新,语义对齐 Flask)。
|
||||
*/
|
||||
@Data
|
||||
public class ShopDataCrawlAdminFileJobBriefDto {
|
||||
|
||||
private Long resultId;
|
||||
private Long fileJobId;
|
||||
private String fileStatus;
|
||||
private String fileError;
|
||||
}
|
||||
+135
-155
@@ -1,11 +1,9 @@
|
||||
package com.nanri.aiimage.modules.shopmatch.service;
|
||||
|
||||
import cn.hutool.core.io.FileUtil;
|
||||
import cn.hutool.core.util.IdUtil;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.config.TaskPressureProperties;
|
||||
import com.nanri.aiimage.modules.file.service.oss.OssStorageService;
|
||||
import com.nanri.aiimage.modules.productrisk.model.enums.ProductRiskCountryCode;
|
||||
@@ -38,12 +36,13 @@ 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.AbstractModuleTaskCacheService;
|
||||
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 com.nanri.aiimage.modules.task.service.TaskResultPayloadService;
|
||||
import com.nanri.aiimage.modules.task.service.pipeline.AbstractShopPayloadTaskPipeline;
|
||||
import com.nanri.aiimage.modules.ziniao.service.ZiniaoShopSwitchService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
@@ -63,9 +62,8 @@ import com.nanri.aiimage.modules.task.model.vo.TaskProgressLightBatchVo;
|
||||
import com.nanri.aiimage.modules.task.service.TaskProgressLightAssembler;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class ShopMatchTaskService {
|
||||
public class ShopMatchTaskService extends AbstractShopPayloadTaskPipeline<ShopMatchShopPayloadDto> {
|
||||
|
||||
private static final String MODULE_TYPE = "SHOP_MATCH";
|
||||
|
||||
@@ -75,20 +73,15 @@ public class ShopMatchTaskService {
|
||||
private static final String CONTENT_TYPE_XLSX = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
|
||||
private static final ZoneId BUSINESS_ZONE = ZoneId.of("Asia/Shanghai");
|
||||
|
||||
private final FileTaskMapper fileTaskMapper;
|
||||
private final FileResultMapper fileResultMapper;
|
||||
private final ShopMatchShopCandidateMapper candidateMapper;
|
||||
private final ZiniaoShopSwitchService ziniaoShopSwitchService;
|
||||
private final ShopMatchExcelAssemblyService excelAssemblyService;
|
||||
private final OssStorageService ossStorageService;
|
||||
/** 结果下载直链解析(2026-09 从本类抽到 common,消除 11 处逐字重复) */
|
||||
private final com.nanri.aiimage.common.service.ResultDownloadResolver resultDownloadResolver;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final ShopMatchTaskCacheService shopMatchTaskCacheService;
|
||||
private final TaskPressureProperties taskPressureProperties;
|
||||
private final TaskResultPayloadService taskResultPayloadService;
|
||||
private final TaskFileJobService taskFileJobService;
|
||||
private final TaskDistributedLockService taskDistributedLockService;
|
||||
private final SkipPriceAsinService skipPriceAsinService;
|
||||
private final QueryAsinMapper queryAsinMapper;
|
||||
private final TaskProgressLightAssembler taskProgressLightAssembler;
|
||||
@@ -97,6 +90,74 @@ public class ShopMatchTaskService {
|
||||
*/
|
||||
private final org.springframework.transaction.PlatformTransactionManager transactionManager;
|
||||
|
||||
/**
|
||||
* 参数表顺序=原先 {@code @RequiredArgsConstructor} 按字段声明序生成的那一个(测试夹具按位置 new)。
|
||||
* 头两枚加锁/Job/存储三枚交 {@code super} 由底座持有,本类那 30 余处引用改读继承来的 protected 字段、调用点未变。
|
||||
*/
|
||||
public ShopMatchTaskService(FileTaskMapper fileTaskMapper,
|
||||
FileResultMapper fileResultMapper,
|
||||
ShopMatchShopCandidateMapper candidateMapper,
|
||||
ZiniaoShopSwitchService ziniaoShopSwitchService,
|
||||
ShopMatchExcelAssemblyService excelAssemblyService,
|
||||
OssStorageService ossStorageService,
|
||||
com.nanri.aiimage.common.service.ResultDownloadResolver resultDownloadResolver,
|
||||
ObjectMapper objectMapper,
|
||||
ShopMatchTaskCacheService shopMatchTaskCacheService,
|
||||
TaskPressureProperties taskPressureProperties,
|
||||
TaskResultPayloadService taskResultPayloadService,
|
||||
TaskFileJobService taskFileJobService,
|
||||
TaskDistributedLockService taskDistributedLockService,
|
||||
SkipPriceAsinService skipPriceAsinService,
|
||||
QueryAsinMapper queryAsinMapper,
|
||||
TaskProgressLightAssembler taskProgressLightAssembler,
|
||||
org.springframework.transaction.PlatformTransactionManager transactionManager) {
|
||||
super(fileTaskMapper, fileResultMapper, taskDistributedLockService, taskFileJobService, ossStorageService);
|
||||
this.candidateMapper = candidateMapper;
|
||||
this.ziniaoShopSwitchService = ziniaoShopSwitchService;
|
||||
this.excelAssemblyService = excelAssemblyService;
|
||||
this.resultDownloadResolver = resultDownloadResolver;
|
||||
this.objectMapper = objectMapper;
|
||||
this.shopMatchTaskCacheService = shopMatchTaskCacheService;
|
||||
this.taskPressureProperties = taskPressureProperties;
|
||||
this.taskResultPayloadService = taskResultPayloadService;
|
||||
this.skipPriceAsinService = skipPriceAsinService;
|
||||
this.queryAsinMapper = queryAsinMapper;
|
||||
this.taskProgressLightAssembler = taskProgressLightAssembler;
|
||||
this.transactionManager = transactionManager;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// 管线钩子(Phase 3 首迁):形状在底座,模块语义留在下面这几个方法里
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
@Override
|
||||
protected String moduleType() {
|
||||
return MODULE_TYPE;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected FileTaskEntity loadTaskForSubmission(Long taskId) {
|
||||
return loadTaskForExecution(taskId); // 本支是缓存优先派(带历史复活防护的本地变体),不在底座里
|
||||
}
|
||||
|
||||
@Override
|
||||
protected AbstractModuleTaskCacheService<ShopMatchShopPayloadDto> taskCacheService() {
|
||||
return shopMatchTaskCacheService;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String submissionLockLogTag() {
|
||||
// 历史标签是小写短名,不是 moduleType();锁竞争日志有人按它数过
|
||||
return "shop-match";
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String normalizeShopKey(String rawShopName) {
|
||||
// 建单与回传必须同一条规则(:499 写进 sourceFilename 的就是它);该 bean 在 modules.ziniao 下,
|
||||
// 底座直接依赖会把 task→业务 的冻结线(0)顶开,所以留成钩子。
|
||||
return ziniaoShopSwitchService.normalizeShopName(rawShopName);
|
||||
}
|
||||
|
||||
private FileTaskEntity loadTaskForExecution(Long taskId) {
|
||||
Map<Long, FileTaskEntity> cachedTasks = shopMatchTaskCacheService.getTaskCacheBatch(List.of(taskId));
|
||||
FileTaskEntity cached = cachedTasks.get(taskId);
|
||||
@@ -347,10 +408,7 @@ public class ShopMatchTaskService {
|
||||
if (task == null || !MODULE_TYPE.equals(task.getModuleType())) {
|
||||
return;
|
||||
}
|
||||
List<FileResultEntity> latest = fileResultMapper.selectList(new LambdaQueryWrapper<FileResultEntity>()
|
||||
.eq(FileResultEntity::getTaskId, taskId)
|
||||
.eq(FileResultEntity::getModuleType, MODULE_TYPE)
|
||||
.orderByAsc(FileResultEntity::getId));
|
||||
List<FileResultEntity> latest = listScopeRows(taskId);
|
||||
if (latest.isEmpty()) {
|
||||
fileTaskMapper.deleteById(taskId);
|
||||
shopMatchTaskCacheService.deleteTaskCache(taskId);
|
||||
@@ -470,21 +528,12 @@ public class ShopMatchTaskService {
|
||||
persistedRequest.setCurrentStageIndex(0);
|
||||
}
|
||||
|
||||
FileTaskEntity task = new FileTaskEntity();
|
||||
task.setTaskNo(MODULE_TYPE + "-" + IdUtil.getSnowflakeNextIdStr());
|
||||
task.setModuleType(MODULE_TYPE);
|
||||
task.setTaskMode("PYTHON_QUEUE");
|
||||
task.setStatus(scheduleTimes.isEmpty() ? "RUNNING" : "SCHEDULED");
|
||||
task.setSourceFileCount(uniqueItems.size());
|
||||
FileTaskEntity task = newTaskHeader(scheduleTimes.isEmpty() ? "RUNNING" : "SCHEDULED",
|
||||
"PYTHON_QUEUE", request.getUserId(), deviceId, uniqueItems.size(), now);
|
||||
task.setSuccessFileCount(0);
|
||||
task.setFailedFileCount(0);
|
||||
task.setCreatedBy("user:" + request.getUserId());
|
||||
task.setUserId(request.getUserId());
|
||||
task.setDeviceId(AdminAuthSupport.normalizeDeviceId(deviceId));
|
||||
task.setCreatedAt(now);
|
||||
task.setUpdatedAt(now);
|
||||
task.setScheduledAt(scheduleTimes.isEmpty() ? null : scheduleTimes.get(0));
|
||||
fileTaskMapper.insert(task);
|
||||
insertTask(task);
|
||||
shopMatchTaskCacheService.saveTaskCache(task);
|
||||
|
||||
List<ProductRiskResultItemVo> snapshot = new ArrayList<>();
|
||||
@@ -493,23 +542,14 @@ public class ShopMatchTaskService {
|
||||
if (normalized.isBlank()) {
|
||||
throw new BusinessException("任务数据已失效,请刷新后重试");
|
||||
}
|
||||
FileResultEntity result = new FileResultEntity();
|
||||
result.setTaskId(task.getId());
|
||||
result.setModuleType(MODULE_TYPE);
|
||||
result.setSourceFilename(normalized);
|
||||
result.setSourceFileUrl(item.getShopId());
|
||||
result.setUserId(request.getUserId());
|
||||
result.setSuccess(0);
|
||||
result.setCreatedAt(now);
|
||||
// rowCount 留 null(本支建单时不写这列)、success 显式 0;时刻复用建单那一枚 now
|
||||
FileResultEntity result = newScopeRow(task.getId(), request.getUserId(), normalized,
|
||||
item.getShopId(), null, 0, now);
|
||||
fileResultMapper.insert(result);
|
||||
snapshot.add(toSnapshotVo(result, item, task.getStatus()));
|
||||
}
|
||||
try {
|
||||
task.setRequestJson(objectMapper.writeValueAsString(persistedRequest));
|
||||
task.setResultJson(objectMapper.writeValueAsString(snapshot));
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("task 不存在");
|
||||
}
|
||||
task.setRequestJson(writeJson(objectMapper, persistedRequest, "task 不存在"));
|
||||
task.setResultJson(writeJson(objectMapper, snapshot, "task 不存在"));
|
||||
updateTaskAndRefreshCache(task);
|
||||
if ("RUNNING".equals(task.getStatus())) {
|
||||
shopMatchTaskCacheService.touchTaskHeartbeat(task.getId());
|
||||
@@ -628,85 +668,51 @@ public class ShopMatchTaskService {
|
||||
* 且终态判断读的是最长 60s 的缓存)。
|
||||
*/
|
||||
public void submitResult(Long taskId, ShopMatchSubmitResultRequest request) {
|
||||
if (taskId == null || taskId <= 0) {
|
||||
throw new BusinessException("taskId 不合法");
|
||||
// 段 3 骨架(准入→取锁→建索引→逐行→changed 闸门→重算状态)在底座,本支只交「单行怎么处理」那一段。
|
||||
submitShopScopedResults(taskId,
|
||||
request == null ? null : request.getShops(),
|
||||
ShopMatchShopPayloadDto::getShopName,
|
||||
TerminalRejection.IDEMPOTENT,
|
||||
null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 迁移前 {@code submitResultLocked} 的全部模块语义就是下面这一个方法;骨架在
|
||||
* {@link AbstractShopPayloadTaskPipeline#submitShopScopedResults}。三处步序微差登记在蓝图
|
||||
* §4 Phase 3 实录(锁位、被摘掉的死局部变量 workRoot、锁内重查 taskId),
|
||||
* golden {@code shopmatch/golden/submit-result-snapshot.txt} 逐字节未动是这一笔的准出证据。
|
||||
*/
|
||||
@Override
|
||||
protected void applyShopResultRow(Long taskId,
|
||||
FileTaskEntity task,
|
||||
FileResultEntity result,
|
||||
String shopKey,
|
||||
ShopMatchShopPayloadDto incoming) {
|
||||
ShopMatchShopPayloadDto merged = mergeShopPayload(taskId, shopKey, incoming);
|
||||
if (incoming.getError() != null && !incoming.getError().isBlank()) {
|
||||
finalizeFailedShop(result, shopKey, merged, incoming.getError().trim());
|
||||
return;
|
||||
}
|
||||
try (TaskDistributedLockService.LockHandle ignored = acquireTaskLockOrThrow(taskId)) {
|
||||
submitResultLocked(taskId, request);
|
||||
if (!isShopPayloadCompleted(merged)) {
|
||||
return;
|
||||
}
|
||||
if (countPayloadRows(merged) <= 0) {
|
||||
markResultFailed(result, "未收到可用于组装的结果数据");
|
||||
shopMatchTaskCacheService.removeShopMergedPayload(taskId, shopKey);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
enqueueResultFileAssembly(result, shopKey, merged);
|
||||
shopMatchTaskCacheService.removeShopMergedPayload(taskId, shopKey);
|
||||
} catch (Exception ex) {
|
||||
markResultFailed(result, ex.getMessage() == null ? "结果组装失败" : ex.getMessage());
|
||||
shopMatchTaskCacheService.removeShopMergedPayload(taskId, shopKey);
|
||||
}
|
||||
}
|
||||
|
||||
private void submitResultLocked(Long taskId, ShopMatchSubmitResultRequest request) {
|
||||
if (taskId == null || taskId <= 0) {
|
||||
throw new BusinessException("taskId 不合法");
|
||||
}
|
||||
if (request == null || request.getShops() == null || request.getShops().isEmpty()) {
|
||||
throw new BusinessException("shops 不能为空");
|
||||
}
|
||||
|
||||
FileTaskEntity task = loadTaskForExecution(taskId);
|
||||
if (task == null || !MODULE_TYPE.equals(task.getModuleType())) {
|
||||
throw new BusinessException("任务不存在");
|
||||
}
|
||||
if ("SUCCESS".equals(task.getStatus()) || "FAILED".equals(task.getStatus())) {
|
||||
throw new BusinessException(40901, "任务已结束,拒绝重复提交");
|
||||
}
|
||||
|
||||
shopMatchTaskCacheService.touchTaskHeartbeat(taskId);
|
||||
List<FileResultEntity> resultRows = fileResultMapper.selectList(new LambdaQueryWrapper<FileResultEntity>()
|
||||
.eq(FileResultEntity::getTaskId, taskId)
|
||||
.eq(FileResultEntity::getModuleType, MODULE_TYPE)
|
||||
.orderByAsc(FileResultEntity::getId));
|
||||
Map<String, ShopMatchShopPayloadDto> payloadByShop = new LinkedHashMap<>();
|
||||
for (ShopMatchShopPayloadDto item : request.getShops()) {
|
||||
if (item == null) {
|
||||
continue;
|
||||
}
|
||||
String key = ziniaoShopSwitchService.normalizeShopName(item.getShopName());
|
||||
if (!key.isBlank()) {
|
||||
payloadByShop.put(key, item);
|
||||
}
|
||||
}
|
||||
File workRoot = FileUtil.mkdir(FileUtil.file(System.getProperty("java.io.tmpdir"), "shop-match-result", String.valueOf(taskId)));
|
||||
|
||||
boolean changed = false;
|
||||
for (FileResultEntity result : resultRows) {
|
||||
String shopKey = result.getSourceFilename();
|
||||
ShopMatchShopPayloadDto incoming = payloadByShop.get(shopKey);
|
||||
if (incoming == null) {
|
||||
continue;
|
||||
}
|
||||
changed = true;
|
||||
ShopMatchShopPayloadDto merged = mergeShopPayload(taskId, shopKey, incoming);
|
||||
if (incoming.getError() != null && !incoming.getError().isBlank()) {
|
||||
finalizeFailedShop(result, shopKey, merged, incoming.getError().trim());
|
||||
continue;
|
||||
}
|
||||
if (!isShopPayloadCompleted(merged)) {
|
||||
continue;
|
||||
}
|
||||
if (countPayloadRows(merged) <= 0) {
|
||||
markResultFailed(result, "未收到可用于组装的结果数据");
|
||||
shopMatchTaskCacheService.removeShopMergedPayload(taskId, shopKey);
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
enqueueResultFileAssembly(result, shopKey, merged);
|
||||
shopMatchTaskCacheService.removeShopMergedPayload(taskId, shopKey);
|
||||
} catch (Exception ex) {
|
||||
markResultFailed(result, ex.getMessage() == null ? "结果组装失败" : ex.getMessage());
|
||||
shopMatchTaskCacheService.removeShopMergedPayload(taskId, shopKey);
|
||||
}
|
||||
}
|
||||
|
||||
if (!changed) {
|
||||
return;
|
||||
}
|
||||
List<FileResultEntity> latest = fileResultMapper.selectList(new LambdaQueryWrapper<FileResultEntity>()
|
||||
.eq(FileResultEntity::getTaskId, taskId)
|
||||
.eq(FileResultEntity::getModuleType, MODULE_TYPE)
|
||||
.orderByAsc(FileResultEntity::getId));
|
||||
updateTaskStatusFromLatestRows(task, latest);
|
||||
@Override
|
||||
protected void onShopRowsRecomputed(FileTaskEntity task, List<FileResultEntity> latestRows) {
|
||||
updateTaskStatusFromLatestRows(task, latestRows);
|
||||
}
|
||||
|
||||
public boolean tryFinalizeTask(Long taskId, boolean fromCompensation) {
|
||||
@@ -727,10 +733,7 @@ public class ShopMatchTaskService {
|
||||
return true;
|
||||
}
|
||||
|
||||
List<FileResultEntity> resultRows = fileResultMapper.selectList(new LambdaQueryWrapper<FileResultEntity>()
|
||||
.eq(FileResultEntity::getTaskId, taskId)
|
||||
.eq(FileResultEntity::getModuleType, MODULE_TYPE)
|
||||
.orderByAsc(FileResultEntity::getId));
|
||||
List<FileResultEntity> resultRows = listScopeRows(taskId);
|
||||
if (resultRows.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
@@ -806,10 +809,7 @@ public class ShopMatchTaskService {
|
||||
return false;
|
||||
}
|
||||
|
||||
List<FileResultEntity> latest = fileResultMapper.selectList(new LambdaQueryWrapper<FileResultEntity>()
|
||||
.eq(FileResultEntity::getTaskId, taskId)
|
||||
.eq(FileResultEntity::getModuleType, MODULE_TYPE)
|
||||
.orderByAsc(FileResultEntity::getId));
|
||||
List<FileResultEntity> latest = listScopeRows(taskId);
|
||||
updateTaskStatusFromLatestRows(task, latest, batchErrors);
|
||||
return true;
|
||||
}
|
||||
@@ -825,19 +825,10 @@ public class ShopMatchTaskService {
|
||||
boolean partialFailure = result.getErrorMessage() != null && !result.getErrorMessage().isBlank();
|
||||
try {
|
||||
excelAssemblyService.writeWorkbook(xlsx, countries);
|
||||
String objectKey = ossStorageService.uploadResultFile(xlsx, MODULE_TYPE);
|
||||
result.setResultFilename(stem + ".xlsx");
|
||||
result.setResultFileUrl(objectKey);
|
||||
result.setResultFileSize(xlsx.length());
|
||||
result.setResultContentType(CONTENT_TYPE_XLSX);
|
||||
result.setRowCount(excelAssemblyService.countRows(countries));
|
||||
if (partialFailure) {
|
||||
result.setSuccess(0);
|
||||
} else {
|
||||
result.setSuccess(1);
|
||||
result.setErrorMessage(null);
|
||||
}
|
||||
fileResultMapper.updateById(result);
|
||||
// 上传+结果行 6 列落库是六支逐字相同的那一截,沉在底座(publishResultFile);
|
||||
// 临时文件的清理点各支不同,仍留在本层 finally 里。
|
||||
publishResultFile(result, xlsx, stem + ".xlsx", CONTENT_TYPE_XLSX,
|
||||
excelAssemblyService.countRows(countries), partialFailure);
|
||||
} finally {
|
||||
FileUtil.del(xlsx);
|
||||
}
|
||||
@@ -860,10 +851,7 @@ public class ShopMatchTaskService {
|
||||
assembleShopResult(result, job.getScopeKey(), payload, workRoot);
|
||||
FileTaskEntity task = loadTaskForExecution(job.getTaskId());
|
||||
if (task != null && MODULE_TYPE.equals(task.getModuleType())) {
|
||||
List<FileResultEntity> latest = fileResultMapper.selectList(new LambdaQueryWrapper<FileResultEntity>()
|
||||
.eq(FileResultEntity::getTaskId, job.getTaskId())
|
||||
.eq(FileResultEntity::getModuleType, MODULE_TYPE)
|
||||
.orderByAsc(FileResultEntity::getId));
|
||||
List<FileResultEntity> latest = listScopeRows(job.getTaskId());
|
||||
updateTaskStatusFromLatestRows(task, latest, List.of());
|
||||
}
|
||||
}
|
||||
@@ -880,7 +868,8 @@ public class ShopMatchTaskService {
|
||||
ShopMatchShopPayloadDto payload, boolean preserveFailure) {
|
||||
taskResultPayloadService.saveLatest(result.getTaskId(), MODULE_TYPE, shopKey, payload);
|
||||
markResultFilePending(result, shopKey, payload, preserveFailure);
|
||||
taskFileJobService.enqueueAssembleResult(result.getTaskId(), MODULE_TYPE, result.getId(), shopKey);
|
||||
// 挂 Job 那一转在底座(scopeKey 本支是店铺名,四形之一,底座只转发不解释)
|
||||
enqueueResultAssembly(result.getTaskId(), result.getId(), shopKey);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1045,7 +1034,7 @@ public class ShopMatchTaskService {
|
||||
* 显式短事务:锁已在事务外获取,这里只包住 DB 段,
|
||||
* 保证原来同属一个 @Transactional 的多条写仍在同一事务内。
|
||||
*/
|
||||
private <T> T inNewTransaction(java.util.function.Supplier<T> action) {
|
||||
private <R> R inNewTransaction(java.util.function.Supplier<R> action) {
|
||||
if (transactionManager == null) {
|
||||
return action.get();
|
||||
}
|
||||
@@ -1069,10 +1058,7 @@ public class ShopMatchTaskService {
|
||||
private ProductRiskTaskDetailVo buildTaskDetail(FileTaskEntity task) {
|
||||
ProductRiskTaskDetailVo detail = new ProductRiskTaskDetailVo();
|
||||
detail.setTask(toTaskItemVo(task));
|
||||
List<FileResultEntity> rows = fileResultMapper.selectList(new LambdaQueryWrapper<FileResultEntity>()
|
||||
.eq(FileResultEntity::getTaskId, task.getId())
|
||||
.eq(FileResultEntity::getModuleType, MODULE_TYPE)
|
||||
.orderByAsc(FileResultEntity::getId));
|
||||
List<FileResultEntity> rows = listScopeRows(task.getId());
|
||||
for (FileResultEntity row : rows) {
|
||||
detail.getItems().add(toHistoryItemVo(row, task));
|
||||
}
|
||||
@@ -1086,10 +1072,7 @@ public class ShopMatchTaskService {
|
||||
}
|
||||
|
||||
private List<ProductRiskResultItemVo> buildSnapshotFromDb(Long taskId, String taskStatus) {
|
||||
List<FileResultEntity> rows = fileResultMapper.selectList(new LambdaQueryWrapper<FileResultEntity>()
|
||||
.eq(FileResultEntity::getTaskId, taskId)
|
||||
.eq(FileResultEntity::getModuleType, MODULE_TYPE)
|
||||
.orderByAsc(FileResultEntity::getId));
|
||||
List<FileResultEntity> rows = listScopeRows(taskId);
|
||||
List<ProductRiskResultItemVo> items = new ArrayList<>();
|
||||
for (FileResultEntity row : rows) {
|
||||
items.add(toHistoryItemVo(row, taskStatus));
|
||||
@@ -1296,11 +1279,8 @@ public class ShopMatchTaskService {
|
||||
}
|
||||
|
||||
private void persistTaskRequest(FileTaskEntity task, ShopMatchCreateTaskRequest request) {
|
||||
try {
|
||||
task.setRequestJson(objectMapper.writeValueAsString(request));
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("序列化任务数据失败");
|
||||
}
|
||||
// 序列化失败即拒、不带 cause——七支同形的那一截,沉在底座 writeJson(文案是本支自己的那句,逐字保留)
|
||||
task.setRequestJson(writeJson(objectMapper, request, "序列化任务数据失败"));
|
||||
}
|
||||
|
||||
private void updateTaskAndRefreshCache(FileTaskEntity task) {
|
||||
|
||||
+47
-9
@@ -4,7 +4,9 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.nanri.aiimage.common.service.DistributedJobLockService;
|
||||
import com.nanri.aiimage.modules.task.spi.BrandTaskStaleRepairSpi;
|
||||
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 lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -40,6 +42,8 @@ public class StaleTaskRepairService {
|
||||
private static final int MAX_BRAND_STALE_BATCH = 500;
|
||||
|
||||
private final FileTaskMapper fileTaskMapper;
|
||||
private final FileResultMapper fileResultMapper;
|
||||
private final TaskFileJobService taskFileJobService;
|
||||
private final BrandTaskStaleRepairSpi brandTaskStaleRepairSpi;
|
||||
private final DistributedJobLockService distributedJobLockService;
|
||||
/** 心跳时钟改为「从首次心跳起算」:排队中的 RUNNING 任务不在这条线上判死。 */
|
||||
@@ -78,16 +82,17 @@ public class StaleTaskRepairService {
|
||||
return;
|
||||
}
|
||||
String reason = "任务长期未被领取,已自动失败";
|
||||
List<Long> ids = stale.stream().map(FileTaskEntity::getId).toList();
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
int updated = fileTaskMapper.update(null, new LambdaUpdateWrapper<FileTaskEntity>()
|
||||
.in(FileTaskEntity::getId, stale.stream().map(FileTaskEntity::getId).toList())
|
||||
.in(FileTaskEntity::getId, ids)
|
||||
.eq(FileTaskEntity::getStatus, STATUS_PENDING)
|
||||
.set(FileTaskEntity::getStatus, STATUS_FAILED)
|
||||
.set(FileTaskEntity::getErrorMessage, reason)
|
||||
.set(FileTaskEntity::getFinishedAt, now));
|
||||
if (updated > 0) {
|
||||
log.warn("[stale-task-repair] 陈旧中间态已标失败 count={} ids={}",
|
||||
updated, stale.stream().map(FileTaskEntity::getId).toList());
|
||||
log.warn("[stale-task-repair] 陈旧中间态已标失败 count={} ids={}", updated, ids);
|
||||
markDeadDownstream(ids, reason);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -114,16 +119,17 @@ public class StaleTaskRepairService {
|
||||
return;
|
||||
}
|
||||
String reason = "定时任务到点后长时间未启动,已自动失败";
|
||||
List<Long> ids = stale.stream().map(FileTaskEntity::getId).toList();
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
int updated = fileTaskMapper.update(null, new LambdaUpdateWrapper<FileTaskEntity>()
|
||||
.in(FileTaskEntity::getId, stale.stream().map(FileTaskEntity::getId).toList())
|
||||
.in(FileTaskEntity::getId, ids)
|
||||
.eq(FileTaskEntity::getStatus, STATUS_SCHEDULED)
|
||||
.set(FileTaskEntity::getStatus, STATUS_FAILED)
|
||||
.set(FileTaskEntity::getErrorMessage, reason)
|
||||
.set(FileTaskEntity::getFinishedAt, now));
|
||||
if (updated > 0) {
|
||||
log.warn("[stale-task-repair] 陈旧定时任务已标失败 count={} ids={}",
|
||||
updated, stale.stream().map(FileTaskEntity::getId).toList());
|
||||
log.warn("[stale-task-repair] 陈旧定时任务已标失败 count={} ids={}", updated, ids);
|
||||
markDeadDownstream(ids, reason);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -144,16 +150,17 @@ public class StaleTaskRepairService {
|
||||
return;
|
||||
}
|
||||
String reason = "任务心跳超时,已自动失败";
|
||||
List<Long> ids = stale.stream().map(FileTaskEntity::getId).toList();
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
int updated = fileTaskMapper.update(null, new LambdaUpdateWrapper<FileTaskEntity>()
|
||||
.in(FileTaskEntity::getId, stale.stream().map(FileTaskEntity::getId).toList())
|
||||
.in(FileTaskEntity::getId, ids)
|
||||
.eq(FileTaskEntity::getStatus, STATUS_RUNNING)
|
||||
.set(FileTaskEntity::getStatus, STATUS_FAILED)
|
||||
.set(FileTaskEntity::getErrorMessage, reason)
|
||||
.set(FileTaskEntity::getFinishedAt, now));
|
||||
if (updated > 0) {
|
||||
log.warn("[stale-task-repair] 心跳超时 RUNNING 已标失败 count={} ids={}",
|
||||
updated, stale.stream().map(FileTaskEntity::getId).toList());
|
||||
log.warn("[stale-task-repair] 心跳超时 RUNNING 已标失败 count={} ids={}", updated, ids);
|
||||
markDeadDownstream(ids, reason);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -191,4 +198,35 @@ public class StaleTaskRepairService {
|
||||
log.warn("[stale-task-repair] brand 陈旧任务已标失败 count={} ids={}", failedIds.size(), failedIds);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 判死必须连带改口下游两处,否则只改 {@code biz_file_task} 会留下两种假象:
|
||||
*
|
||||
* <p>1){@code biz_file_result.success} 是 {@code NOT NULL DEFAULT 1} 的列,只有走正常收尾才回写。
|
||||
* 被兜底判死的任务这一位仍是 1,而历史列表拿它当「已完成」的判据之一,于是显示「已完成」却没有任何
|
||||
* 结果文件(2026-10-16 任务 31060:客户端只回传 51/510 个分片,判死后结果行仍是 success=1)。
|
||||
* 只改没有结果文件的行——文件已经补出来的任务,其部分交付提示(error_message)不能被这里覆盖。
|
||||
*
|
||||
* <p>2)结果文件作业仍 RUNNING 会被 worker 反复 defer 续命、永不出栈,见
|
||||
* {@link TaskFileJobService#failUnfinishedJobs}。
|
||||
*
|
||||
* <p>批内并发:下游按「本轮 SELECT 到的陈旧 id」写,而任务行的 UPDATE 带 status 条件,理论上可波及
|
||||
* 同批里刚被别的写入方推走的任务。窗口是同一次方法调用内 SELECT→UPDATE 的毫秒级,且候选已被要求
|
||||
* 2 小时无任何更新,故按批处理、不逐行复核。
|
||||
*/
|
||||
private void markDeadDownstream(List<Long> taskIds, String reason) {
|
||||
if (taskIds.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
fileResultMapper.update(null, new LambdaUpdateWrapper<FileResultEntity>()
|
||||
.in(FileResultEntity::getTaskId, taskIds)
|
||||
.eq(FileResultEntity::getSuccess, 1)
|
||||
.and(w -> w.isNull(FileResultEntity::getResultFileUrl)
|
||||
.or().eq(FileResultEntity::getResultFileUrl, ""))
|
||||
.set(FileResultEntity::getSuccess, 0)
|
||||
.set(FileResultEntity::getErrorMessage, reason));
|
||||
int jobs = taskFileJobService.failUnfinishedJobs(taskIds, reason);
|
||||
log.warn("[stale-task-repair] 判死下游已改口(不影响本轮判死)tasks={} jobs={} reason={}",
|
||||
taskIds.size(), jobs, reason);
|
||||
}
|
||||
}
|
||||
|
||||
+27
@@ -734,6 +734,33 @@ public class TaskFileJobService {
|
||||
.set(TaskFileJobEntity::getTerminalCallbackAt, LocalDateTime.now()));
|
||||
}
|
||||
|
||||
/**
|
||||
* 父任务已被判死时,终结它仍未结束的组装作业。
|
||||
*
|
||||
* <p>不终结的后果(2026-10-16 线上作业 22136 / 任务 31060):worker 每 15 秒把作业捞起来走
|
||||
* {@code touchRunning} 续命,{@code updated_at} 因此一直被刷新,而 job 级 stuck 扫描正是按
|
||||
* {@code updated_at} 判陈旧的 → 永不命中,作业随已死的父任务空转 28 小时。
|
||||
*
|
||||
* <p>与 {@link #markFailedPermanent} 同口径:重试拉满(FAILED 而 retry_count 未达上限的作业会被
|
||||
* {@code listRunnableJobs} 再次捞起)+ 打 {@code terminal_callback_at}(否则失败收尾扫描会去回调
|
||||
* 已被判死的父任务与结果行)。
|
||||
*/
|
||||
public int failUnfinishedJobs(List<Long> taskIds, String message) {
|
||||
if (taskIds == null || taskIds.isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
return taskFileJobMapper.update(null, new LambdaUpdateWrapper<TaskFileJobEntity>()
|
||||
.in(TaskFileJobEntity::getTaskId, taskIds)
|
||||
.in(TaskFileJobEntity::getStatus, "RUNNING", "PENDING")
|
||||
.set(TaskFileJobEntity::getStatus, "FAILED")
|
||||
.set(TaskFileJobEntity::getRetryCount, MAX_RETRY_COUNT)
|
||||
.set(TaskFileJobEntity::getErrorMessage, message == null ? "父任务已判死,结果文件作业同步结束" : message)
|
||||
.set(TaskFileJobEntity::getUpdatedAt, now)
|
||||
.set(TaskFileJobEntity::getFinishedAt, now)
|
||||
.set(TaskFileJobEntity::getTerminalCallbackAt, now));
|
||||
}
|
||||
|
||||
/**
|
||||
* 该任务是否已有「重试耗尽且已走完终态回调」的组装 job。
|
||||
*
|
||||
|
||||
+15
@@ -187,4 +187,19 @@ public final class TaskFinalizeSupport {
|
||||
}
|
||||
return lockHandle;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// 模块归属谓词(2026-10-18 收口:TaskLifecycleDebtRatchetTest 棘轮只许降)
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* 「这一行是不是这个模块的」归属谓词出口。此前该判断在 16 个业务文件里手抄了 130 遍
|
||||
* ({@code !MODULE_TYPE.equals(x.getModuleType())}),棘轮只许降不许升——新增归属校验
|
||||
* 一律改走这里,漏一处的表现是某页检查静默变成「谁都能读」,不报错、不 403。
|
||||
*
|
||||
* @return true 表示记录属于 expectedModuleType 模块(expected 为 null 视为不归属)
|
||||
*/
|
||||
public static boolean belongsToModule(String expectedModuleType, String recordModuleType) {
|
||||
return expectedModuleType != null && expectedModuleType.equals(recordModuleType);
|
||||
}
|
||||
}
|
||||
|
||||
+460
@@ -0,0 +1,460 @@
|
||||
package com.nanri.aiimage.modules.task.service.pipeline;
|
||||
|
||||
import cn.hutool.core.util.IdUtil;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
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.security.AdminAuthSupport;
|
||||
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.model.entity.FileResultEntity;
|
||||
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
|
||||
import com.nanri.aiimage.modules.task.service.AbstractModuleTaskCacheService;
|
||||
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 java.io.File;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 后端任务管线四段(文件任务→解析→跑批→出结果)的公共底座。
|
||||
*
|
||||
* <p><b>本类只沉「七支巨石实测逐字相同的那一截」,不承诺统一四段。</b>签名逐条来自
|
||||
* 2026-10-18 对七支现网代码的定点实贴(AppearancePatent 3,377/ShopDataCrawl 3,195/
|
||||
* DeleteBrand 2,304/PriceTrack 2,302/Publish 2,249/CollectData 2,162/ShopMatch 2,027),
|
||||
* 每段方法的注释里都写了它的出处行号,Phase 3 迁移时被迁移支必须能逐字替换,
|
||||
* 换不上就是本类缺件,不是迁移方自由发挥。
|
||||
*
|
||||
* <p>四段实测结论(决定了下面有什么、没有什么):
|
||||
* <ul>
|
||||
* <li><b>解析建单</b>:能沉的是 task 头行与结果行的<b>落库形状</b>({@link #newTaskHeader}
|
||||
* /{@link #newScopeRow});<b>不能沉</b>的是解析本身——
|
||||
* 七支只有 4 支读 Excel(ShopDataCrawl/ShopMatch 无文件概念),且事务策略三分
|
||||
* (AppearancePatent 与 DeleteBrand 全程无事务、Publish/CollectData 用
|
||||
* {@code TransactionTemplate}、ShopDataCrawl/ShopMatch 用 {@code @Transactional}),
|
||||
* 返回 VO 字段互不相交。所以 parse 是钩子留在各支,底座只提供落库件。</li>
|
||||
* <li><b>序列化那半件已随 Phase 3 首迁落下</b>({@link #writeJson}):七支建单时都写
|
||||
* 「{@code writeValueAsString} 失败即 {@code BusinessException}(不带 cause)」,形状一致、
|
||||
* 只有文案不同,是最干净的公共件。Phase 2 当时落不了——{@code config/CatchSilenceRatchetTest}
|
||||
* 的自述规则是「新增捕获块要么别加,要么同批减掉一处同形状」,而 Phase 2 禁止改七支
|
||||
* ⇒ 减不掉只能不加(登记见蓝图 §5 Phase 2 那条);首迁这一笔删掉被迁支的本地同名件,
|
||||
* 净增 ≤ 0 才成立。现成模板 {@code PublishTaskService:2118-2124} 的私有
|
||||
* {@code writeJson(Object, String)} 就是带文案参数的形状。
|
||||
* ⚠ task 模块内部那三份逐字同名件({@code TaskProgressSnapshotService:186}/
|
||||
* {@code TaskResultItemService:405}/{@code TaskResultPayloadService:113})<b>本轮仍未归并</b>:
|
||||
* 归并会把 RETHROW 那一格跌破下限(它是下限不是上限,实测首迁后正好落在 386),
|
||||
* 那属于「调整门禁判据」动作,与 Phase 0 那格「三格守卫」同批做,不在迁移笔里顺手干。</li>
|
||||
* <li><b>跑批</b>:服务端<b>没有属于这七支的可沉件</b>——机制早已收在
|
||||
* {@link TaskFileJobService}(enqueue/claim/markSuccess/markFailed)+
|
||||
* {@code TaskResultFileJobWorker}(取锁、重排、重试)+
|
||||
* {@code TaskClientPullService},而 {@code ClientTaskPullSpi} 只有 3/7 支实现。
|
||||
* 本类<b>不</b>为此段提供转发钩子:那是空壳,不是抽象。</li>
|
||||
* <li><b>回传落库</b>:能沉的是准入(校验→取锁→加载→模块校验→终态拒绝→心跳)
|
||||
* 与结果行列举;<b>不能沉</b>的是合并模型——实测三个家族(chunk+scope/
|
||||
* shop-payload/DeleteBrand 自有存储),shop-payload 那族见
|
||||
* {@link AbstractShopPayloadTaskPipeline}。</li>
|
||||
* <li><b>出结果</b>:六支逐字相同的是「上传对象存储 → 写 6 列 → {@code updateById}」
|
||||
* ({@link #publishResultFile}),第七支 ShopDataCrawl 走批量条件更新、不在其列
|
||||
* (见该方法注释)。<b>本类不新建 report SPI</b>——
|
||||
* {@code ResultFileJobHandler} 已是该段的注册契约(moduleType 唯一、启动 fail-fast),
|
||||
* 各支的 Handler 实现改为复用这段骨架,而不是再立一套。</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>缓存与心跳复用 {@link AbstractModuleTaskCacheService},不新造第二套:4/7 支有模块缓存服务
|
||||
* (AppearancePatent/ShopDataCrawl/ShopMatch/PriceTrack),其余三支没有——
|
||||
* 故 {@link #taskCacheService()} 默认 {@code null},心跳只在有缓存服务的支上落,
|
||||
* 与现网一致(DeleteBrand 走自家 {@code saveProgress},其缓存服务<b>不</b>继承本抽象,
|
||||
* 见 {@code DeleteBrandRunService:1265} 注释)。
|
||||
*
|
||||
* <p>依赖严格限于 task 模块内部+{@code common}+{@code modules.file},不触碰任何业务模块,
|
||||
* 满足 ArchUnit 冻结线 {@code TASK_TO_BUSINESS_BASELINE = 0}
|
||||
* ({@code ArchitectureBoundaryTest:39})。泛型 {@code T} 即该支店铺维度合并载荷类型,
|
||||
* 与 {@link AbstractModuleTaskCacheService} 的 {@code T} 同义,因此两者可直接对接。
|
||||
*/
|
||||
@Slf4j
|
||||
public abstract class AbstractFileTaskPipeline<T> {
|
||||
|
||||
/** 终态任务被再次回传时的拒绝形状。两支差异不是文案,是线协议。 */
|
||||
public enum TerminalRejection {
|
||||
/**
|
||||
* 带 {@link BusinessCodes#TASK_ALREADY_FINISHED}(40901):
|
||||
* {@code GlobalExceptionHandler} 转 HTTP 200 + success=true,Python 侧按幂等忽略、停止重试。
|
||||
* 现网出处:ShopMatch {@code :652}/PriceTrack {@code :603}/CollectData {@code :864/:904}。
|
||||
*/
|
||||
IDEMPOTENT,
|
||||
/**
|
||||
* 不带 code({@code BusinessException(String)}):响应 success=false,调用方会当错误处理。
|
||||
* 现网出处:ShopDataCrawl {@code :633}/DeleteBrand {@code :1362-1374}/Publish {@code :1344}。
|
||||
*/
|
||||
ERROR
|
||||
}
|
||||
|
||||
protected final FileTaskMapper fileTaskMapper;
|
||||
protected final FileResultMapper fileResultMapper;
|
||||
protected final TaskDistributedLockService taskDistributedLockService;
|
||||
protected final TaskFileJobService taskFileJobService;
|
||||
protected final OssStorageService ossStorageService;
|
||||
|
||||
protected AbstractFileTaskPipeline(FileTaskMapper fileTaskMapper,
|
||||
FileResultMapper fileResultMapper,
|
||||
TaskDistributedLockService taskDistributedLockService,
|
||||
TaskFileJobService taskFileJobService,
|
||||
OssStorageService ossStorageService) {
|
||||
this.fileTaskMapper = fileTaskMapper;
|
||||
this.fileResultMapper = fileResultMapper;
|
||||
this.taskDistributedLockService = taskDistributedLockService;
|
||||
this.taskFileJobService = taskFileJobService;
|
||||
this.ossStorageService = ossStorageService;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// 钩子:实测真差异处,只有这四条
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/** 该支模块标识,全库唯一(同时是结果文件 Job 的注册键与锁键)。 */
|
||||
protected abstract String moduleType();
|
||||
|
||||
/**
|
||||
* 回传准入用任务加载:实测两派——AppearancePatent/Publish/CollectData 直接
|
||||
* {@code fileTaskMapper.selectById}(DB),ShopDataCrawl/ShopMatch/PriceTrack 走
|
||||
* 缓存优先({@link TaskFinalizeSupport#loadTaskForExecution}),DeleteBrand 用本地缓存件。
|
||||
* 派别由子类定,底座不替它选。
|
||||
*/
|
||||
protected abstract FileTaskEntity loadTaskForSubmission(Long taskId);
|
||||
|
||||
/**
|
||||
* 该支的模块缓存服务;无缓存服务的三支返回 {@code null}。
|
||||
* 返回非空时 {@link #admitSubmission} 会按现网形状打一次心跳。
|
||||
*/
|
||||
protected AbstractModuleTaskCacheService<T> taskCacheService() {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 归属实例校验钩子,默认放过。现网只有 AppearancePatent{@code :2026}/
|
||||
* Publish{@code :1375}/ShopDataCrawl{@code :3114} 三支实现(多实例转发用),
|
||||
* 其余四支不校验——所以默认必须是空实现而不是抛错。
|
||||
*/
|
||||
protected void ensureTaskOwnedByCurrentInstance(FileTaskEntity task, String operation) {
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// 段 1:解析建单——task 头行与结果行的落库形状
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* 建任务头行(不落库)。七支逐字相同的字段集合在此钉死:
|
||||
* {@code taskNo = <moduleType>-<雪花id>}、{@code createdBy = "user:" + userId}、
|
||||
* {@code deviceId = AdminAuthSupport.normalizeDeviceId(deviceId)}、{@code createdAt/updatedAt}
|
||||
* 取同一时刻。后者对 AppearancePatent{@code :207-208} 与 DeleteBrand{@code :156-157}
|
||||
* 是一处微差——它们各调了两次 {@code LocalDateTime.now()}(可能差几微秒),底座只取一次;
|
||||
* 两列都只用于「建单时刻」,无人拿它们互相比较,故按 Majority 的单次写法沉。
|
||||
* 出处:ShopDataCrawl{@code :575-587}/ShopMatch{@code :473-486}/Publish{@code :1054-1070}
|
||||
* /CollectData{@code :329-341}/AppearancePatent{@code :196-214}/PriceTrack{@code :501-513}
|
||||
* /DeleteBrand{@code :146-157}。
|
||||
*
|
||||
* <p>{@code taskMode} 六支 {@code "PYTHON_QUEUE"}、DeleteBrand 一支 {@code "IMMEDIATE"};
|
||||
* {@code status} 建单时各不相同——{@code RUNNING}(ShopDataCrawl/PriceTrack/DeleteBrand)、
|
||||
* {@code PENDING}(AppearancePatent/CollectData)、{@code SCHEDULED}(ShopMatch 带排期时)、
|
||||
* 乃至 Publish 在全部文件解析失败时直接 {@code FAILED}({@code :1058})。
|
||||
* 两者一律由调用方显式传入,不在底座设默认值——设了就会有人不再想它。
|
||||
*
|
||||
* <p><b>{@code successFileCount}/{@code failedFileCount} 刻意不由底座初始化</b>:建单时五支写 0
|
||||
* (AppearancePatent{@code :202-203}/ShopDataCrawl{@code :581-582}/ShopMatch{@code :479-480}/
|
||||
* PriceTrack{@code :507-508}/CollectData{@code :333-334}),Publish{@code :1060-1061} 写的是
|
||||
* 真实失败数,而 DeleteBrand{@code :146-157} 首次 insert 两列都留 NULL、到 {@code :268-278}
|
||||
* 循环后才回填。底座一旦默认写 0,就把 DeleteBrand 的「还没统计」偷换成了「零成功零失败」。
|
||||
* 其余模块专有列({@code requestJson}/{@code resultJson}/{@code scheduledAt}
|
||||
* /{@code errorMessage}/{@code finishedAt})同样请在返回的实体上继续 set,再交 {@link #insertTask}。
|
||||
*/
|
||||
protected final FileTaskEntity newTaskHeader(String status,
|
||||
String taskMode,
|
||||
Long userId,
|
||||
String deviceId,
|
||||
int sourceFileCount) {
|
||||
return newTaskHeader(status, taskMode, userId, deviceId, sourceFileCount, LocalDateTime.now());
|
||||
}
|
||||
|
||||
/**
|
||||
* 带<b>显式建单时刻</b>的重载——Phase 3 首迁实测出来的缺件,不是锦上添花。
|
||||
*
|
||||
* <p>五参版写死 {@code LocalDateTime.now()}(JVM 默认时区),那是 PriceTrack{@code :512-513}
|
||||
* 的形状;ShopMatch{@code :462 → :484-485} 用的是 {@code now()}=
|
||||
* {@code LocalDateTime.now(Asia/Shanghai)},并且<b>同一个时刻</b>还要喂给每一行结果行
|
||||
* ({@code :503})。默认时区一旦不是业务时区(容器换 TZ、换主机、跑在 CI 里),
|
||||
* 用五参版迁 ShopMatch 就把建单时间整体挪了几个小时——而这条<b>快照量不出来</b>
|
||||
* (时钟刻意不进快照,否则逐字节对撞无从谈起)。所以时刻必须由被迁支自己交进来,
|
||||
* 底座不替它选时区。
|
||||
*/
|
||||
protected final FileTaskEntity newTaskHeader(String status,
|
||||
String taskMode,
|
||||
Long userId,
|
||||
String deviceId,
|
||||
int sourceFileCount,
|
||||
LocalDateTime createdAt) {
|
||||
requireUserId(userId);
|
||||
FileTaskEntity task = new FileTaskEntity();
|
||||
task.setTaskNo(moduleType() + "-" + IdUtil.getSnowflakeNextIdStr());
|
||||
task.setModuleType(moduleType());
|
||||
task.setTaskMode(taskMode);
|
||||
task.setStatus(status);
|
||||
task.setSourceFileCount(sourceFileCount);
|
||||
task.setCreatedBy("user:" + userId);
|
||||
task.setUserId(userId);
|
||||
task.setDeviceId(AdminAuthSupport.normalizeDeviceId(deviceId));
|
||||
task.setCreatedAt(createdAt);
|
||||
task.setUpdatedAt(createdAt);
|
||||
return task;
|
||||
}
|
||||
|
||||
/** 落库任务头行。主键由 {@code IdType.AUTO} 回填,返回同一实体以便调用方继续用 id。 */
|
||||
protected final FileTaskEntity insertTask(FileTaskEntity task) {
|
||||
fileTaskMapper.insert(task);
|
||||
return task;
|
||||
}
|
||||
|
||||
/**
|
||||
* 建一个「作用域结果行」(一支一店/一支一文件)。七支逐字相同的字段集合:
|
||||
* {@code taskId/moduleType/sourceFilename/sourceFileUrl/userId/createdAt}。
|
||||
* {@code rowCount} 与 {@code success} 刻意可空——现网 ShopDataCrawl{@code :598-606}
|
||||
* 与 ShopMatch{@code :496-504} 不写 rowCount,{@code success} 则有三值:
|
||||
* {@code null}(AppearancePatent{@code :229-237} 不写)、{@code 0}(多数)、
|
||||
* {@code -1}(ShopDataCrawl 的 {@code RESULT_PENDING})。底座不替它们归一。
|
||||
*
|
||||
* <p>{@code sourceFilename} 在 shop 族是店铺名、在 file 族是源文件名,
|
||||
* 且回传侧正是用它当作用域键({@code ShopMatchTaskService:674} {@code row.getSourceFilename()}),
|
||||
* 所以这里的入参就是后续 {@link #listScopeRows} 的匹配键,别传展示用的名字。
|
||||
*/
|
||||
protected final FileResultEntity newScopeRow(Long taskId,
|
||||
Long userId,
|
||||
String sourceFilename,
|
||||
String sourceFileUrl,
|
||||
Integer rowCount,
|
||||
Integer success) {
|
||||
return newScopeRow(taskId, userId, sourceFilename, sourceFileUrl, rowCount, success, LocalDateTime.now());
|
||||
}
|
||||
|
||||
/**
|
||||
* 带<b>显式时刻</b>的结果行重载。理由与 {@link #newTaskHeader(String, String, Long, String, int, LocalDateTime)}
|
||||
* 同一处缺件:ShopMatch{@code :503} 把建单那一枚 {@code now()} 复用给<b>每一行</b>,
|
||||
* 所以同一任务的所有结果行 {@code createdAt} 逐字相同;PriceTrack{@code :538} 则逐行各取一次
|
||||
* 默认时区的 {@code now()}。底座只有一种写法,就必然有一支被悄悄改掉。
|
||||
*/
|
||||
protected final FileResultEntity newScopeRow(Long taskId,
|
||||
Long userId,
|
||||
String sourceFilename,
|
||||
String sourceFileUrl,
|
||||
Integer rowCount,
|
||||
Integer success,
|
||||
LocalDateTime createdAt) {
|
||||
FileResultEntity row = new FileResultEntity();
|
||||
row.setTaskId(taskId);
|
||||
row.setModuleType(moduleType());
|
||||
row.setSourceFilename(sourceFilename);
|
||||
row.setSourceFileUrl(sourceFileUrl);
|
||||
row.setRowCount(rowCount);
|
||||
row.setSuccess(success);
|
||||
row.setUserId(userId);
|
||||
row.setCreatedAt(createdAt);
|
||||
return row;
|
||||
}
|
||||
|
||||
/**
|
||||
* 逐条插入结果行。<b>刻意不批插</b>:PriceTrack{@code :524-527} 的注释写明了原因——
|
||||
* 后续要用 {@code useGeneratedKeys} 回填的 {@code resultId} 去挂载荷,批插拿不到逐行主键。
|
||||
*/
|
||||
protected final List<FileResultEntity> insertScopeRows(List<FileResultEntity> rows) {
|
||||
List<FileResultEntity> saved = new ArrayList<>(rows.size());
|
||||
for (FileResultEntity row : rows) {
|
||||
fileResultMapper.insert(row);
|
||||
saved.add(row);
|
||||
}
|
||||
return saved;
|
||||
}
|
||||
|
||||
/**
|
||||
* 「序列化失败即拒」的公共件——Phase 2 登记为「随 Phase 3 首迁同笔落」的那一件,现在落了。
|
||||
*
|
||||
* <p>七支建单与状态回写时都要把对象转成 JSON,失败形状逐字相同:
|
||||
* 抛 {@code BusinessException(<文案>)} 且<b>不带 cause</b>
|
||||
* (ShopMatch{@code :510-512} 的文案是「task 不存在」、{@code :1301-1303} 是「序列化任务数据失败」,
|
||||
* PriceTrack{@code :571-573} 与 Publish{@code :2118-2124} 同款)。
|
||||
* 文案是各支自己的对外语义(其中「task 不存在」甚至是现网一句会说谎的文案——序列化失败跟任务存不存在
|
||||
* 没关系,但 Python 侧按这句决定要不要重试,改它=改线协议),所以底座只收形状、文案由调用方给。
|
||||
*
|
||||
* <p><b>为什么 Phase 2 不能落、首迁这一笔必须落。</b>{@code CatchSilenceRatchetTest} 的自述规则是
|
||||
* 「新增捕获块要么别加,要么同批减掉一处同形状」,而 Phase 2 禁止改七支 ⇒ 当时只能不加。
|
||||
* 首迁这一笔把被迁支的本地同名件删掉,净增才是 ≤ 0(实测:本件 +1 处重抛,
|
||||
* ShopMatch 两处 −2 处 ⇒ 整树 total 由 1003 降到 1002、RETHROW 由 387 落到下限 386,
|
||||
* 两个判据一条都没放宽)。
|
||||
*
|
||||
* <p>捕获面是宽的一类({@code Exception})而不是只收 {@code JsonProcessingException}:被迁支原样就是宽捕获,
|
||||
* 收窄会让「序列化器自己抛的 RuntimeException」从「拒单」变成「冒出去」——那是行为变更,不归本件。
|
||||
*
|
||||
* @param failureMessage 失败时对外的文案,逐字取被迁支现网那句
|
||||
*/
|
||||
protected final String writeJson(ObjectMapper objectMapper, Object value, String failureMessage) {
|
||||
try {
|
||||
return objectMapper.writeValueAsString(value);
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException(failureMessage);
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// 段 3:回传落库——准入序列
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/** {@code taskId} 非法即拒。出处:ShopDataCrawl{@code :619}/ShopMatch{@code :631}/PriceTrack{@code :592}。 */
|
||||
protected final void requireTaskId(Long taskId) {
|
||||
if (taskId == null || taskId <= 0) {
|
||||
throw new BusinessException("taskId 不合法");
|
||||
}
|
||||
}
|
||||
|
||||
/** {@code user_id} 非法即拒;七支文案逐字相同({@code user_id 不合法})。 */
|
||||
protected final void requireUserId(Long userId) {
|
||||
if (userId == null || userId <= 0) {
|
||||
throw new BusinessException("user_id 不合法");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 取任务分布式锁,竞争即 {@link BusinessCodes#TASK_BUSY} 拒绝(不静默降级)。
|
||||
* 委托既有 {@link TaskFinalizeSupport#acquireTaskLockOrThrow},不另立一套锁语义。
|
||||
*/
|
||||
protected final TaskDistributedLockService.LockHandle acquireSubmissionLockOrThrow(Long taskId, String logTag) {
|
||||
return TaskFinalizeSupport.acquireTaskLockOrThrow(taskDistributedLockService, moduleType(), taskId, logTag);
|
||||
}
|
||||
|
||||
/** 带等待时长的变体(CollectData/ShopDataCrawl 等自有 {@code TASK_LOCK_WAIT_MILLIS})。 */
|
||||
protected final TaskDistributedLockService.LockHandle acquireSubmissionLockOrThrow(Long taskId,
|
||||
String logTag,
|
||||
long waitMillis) {
|
||||
TaskDistributedLockService.LockHandle lockHandle =
|
||||
TaskFinalizeSupport.acquireTaskLock(taskDistributedLockService, moduleType(), taskId, waitMillis);
|
||||
if (lockHandle == null) {
|
||||
log.warn("[{}] 任务锁竞争,拒绝本次提交 taskId={}", logTag, taskId);
|
||||
throw new BusinessException(BusinessCodes.TASK_BUSY, "任务正在处理中,请稍后再试");
|
||||
}
|
||||
return lockHandle;
|
||||
}
|
||||
|
||||
/**
|
||||
* 回传准入:校验 taskId → 加载任务 → 模块校验 → 终态拒绝 → 归属校验 → 心跳。
|
||||
* 出处:ShopMatch{@code :647-655} 对 PriceTrack{@code :597-605} 除终态那格的日志外逐字相同;
|
||||
* ShopDataCrawl{@code :627-636} 同形但步序相反(见下)。
|
||||
*
|
||||
* <p>终态怎么拒由 {@code terminalRejection} 决定(见 {@link TerminalRejection} 的线协议后果),
|
||||
* 归属校验是否发生由 {@code ownershipOperation} 决定(传 {@code null} = 不校验,
|
||||
* 对应现网 ShopMatch/PriceTrack/DeleteBrand/CollectData 四支不查归属)。
|
||||
*
|
||||
* <p><b>步序按 ShopMatch/PriceTrack 定:终态判定在归属校验之前。</b>ShopDataCrawl 现网是反的
|
||||
* ({@code :631} 先查归属、{@code :632} 再判终态),一支既被别人持有又已终态的任务,
|
||||
* 走它会得 {@code TaskOwnerMismatchException}、走本方法是终态拒绝。所以 ShopDataCrawl 迁移时
|
||||
* 要么保留自己的步序(传 {@code null} 后自查归属),要么把这条差异单独立账,
|
||||
* 不许悄悄套用本默认序就算迁完。
|
||||
*
|
||||
* <p><b>本方法不打日志</b>:七支里只有 PriceTrack{@code :602} 在终态拒绝前打一行 warn,
|
||||
* 其余六支沉默。日志不是公共形状,所以那一行留在它自己的调用点,别当成已沉掉后把它删了。
|
||||
*/
|
||||
protected final FileTaskEntity admitSubmission(Long taskId,
|
||||
TerminalRejection terminalRejection,
|
||||
String ownershipOperation) {
|
||||
requireTaskId(taskId);
|
||||
FileTaskEntity task = loadTaskForSubmission(taskId);
|
||||
if (task == null || !moduleType().equals(task.getModuleType())) {
|
||||
throw new BusinessException("任务不存在");
|
||||
}
|
||||
String status = task.getStatus();
|
||||
if ("SUCCESS".equals(status) || "FAILED".equals(status)) {
|
||||
if (terminalRejection == TerminalRejection.IDEMPOTENT) {
|
||||
throw new BusinessException(BusinessCodes.TASK_ALREADY_FINISHED, "任务已结束,拒绝重复提交");
|
||||
}
|
||||
throw new BusinessException("任务已结束,拒绝重复提交");
|
||||
}
|
||||
if (ownershipOperation != null) {
|
||||
ensureTaskOwnedByCurrentInstance(task, ownershipOperation);
|
||||
}
|
||||
AbstractModuleTaskCacheService<T> cacheService = taskCacheService();
|
||||
if (cacheService != null) {
|
||||
cacheService.touchTaskHeartbeat(taskId);
|
||||
}
|
||||
return task;
|
||||
}
|
||||
|
||||
/**
|
||||
* 该任务的全部结果行,按主键升序——回传侧的作用域匹配与收尾判定都依赖这个顺序。
|
||||
* 出处:ShopMatch{@code :656-659}/PriceTrack{@code :606-610}/DeleteBrand 同款 selectList。
|
||||
*/
|
||||
protected final List<FileResultEntity> listScopeRows(Long taskId) {
|
||||
return fileResultMapper.selectList(new LambdaQueryWrapper<FileResultEntity>()
|
||||
.eq(FileResultEntity::getTaskId, taskId)
|
||||
.eq(FileResultEntity::getModuleType, moduleType())
|
||||
.orderByAsc(FileResultEntity::getId));
|
||||
}
|
||||
|
||||
/**
|
||||
* 挂一个结果文件组装 Job。{@code scopeKey} 实测是<b>四形</b>的,不是笔误:
|
||||
* 归属实例域 {@code task:{id}:owner:{instance}}(Publish{@code :1046/:1216}、
|
||||
* ShopDataCrawl{@code :1920}、AppearancePatent{@code :1753})/固定 {@code task:{id}}
|
||||
* (CollectData{@code :1122})/店铺名(ShopMatch{@code :883}、PriceTrack{@code :905})
|
||||
* /文件身份(DeleteBrand{@code :1505/:1770})。底座只转发,不解释形状。
|
||||
*/
|
||||
protected final void enqueueResultAssembly(Long taskId, Long resultId, String scopeKey) {
|
||||
taskFileJobService.enqueueAssembleResult(taskId, moduleType(), resultId, scopeKey);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// 段 4:出结果——上传与结果行 6 列落库
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* 把已组装好的结果文件上传对象存储,并写回结果行的 6 列后落库。
|
||||
* 出处(六支同形):ShopMatch{@code :828-840}/PriceTrack{@code :845-857}/
|
||||
* Publish{@code :590-598}/CollectData{@code :1166-1190}/AppearancePatent{@code :1876}
|
||||
* /DeleteBrand{@code :1921-1929}。
|
||||
*
|
||||
* <p><b>ShopDataCrawl 不在此件适用范围内</b>:它写 5 列走的是另一条路——
|
||||
* {@code updateResultFileColumns:1880-1892} 用 {@code LambdaUpdateWrapper} 按 id 集合批量
|
||||
* {@code .in(ids).eq(success, RESULT_SUCCESS).set(...)},既不 {@code updateById} 载入的实体、
|
||||
* 不写 {@code success}/{@code errorMessage},还会在 {@code :1919} 传 {@code objectKey=null}
|
||||
* (终态无工作簿那格)。硬套本方法会把它的「只刷成功行、不动状态位」语义改掉,
|
||||
* 故 3B 迁移那一支必须保留本地写法,别把这句读成「七支都能换」。
|
||||
*
|
||||
* <p>{@code preserveFailure} 是 ShopMatch/PriceTrack 的「失败店铺部分结果」语义:
|
||||
* 结果行已带 {@code errorMessage} 时只挂文件、{@code success} 保持 0,
|
||||
* 否则组装一落地就把行“洗成成功”,用户再也看不到「这个店铺其实没跑完」
|
||||
* (原注释见 {@code ShopMatchTaskService:823-825})。其余五支恒传 {@code false}
|
||||
* (它们无条件 {@code success=1} 并清 {@code errorMessage})。
|
||||
*
|
||||
* <p><b>临时文件不由本方法删</b>:现网七支的清理点不同(有的在本层 {@code finally}、
|
||||
* 有的在外层),谁上传谁负责,与本类 javadoc 说的「只沉逐字相同那截」一致。
|
||||
*/
|
||||
protected final void publishResultFile(FileResultEntity row,
|
||||
File resultFile,
|
||||
String filename,
|
||||
String contentType,
|
||||
int rowCount,
|
||||
boolean preserveFailure) {
|
||||
String objectKey = ossStorageService.uploadResultFile(resultFile, moduleType());
|
||||
if (preserveFailure) {
|
||||
row.setSuccess(0);
|
||||
} else {
|
||||
row.setSuccess(1);
|
||||
row.setErrorMessage(null);
|
||||
}
|
||||
row.setResultFilename(filename);
|
||||
row.setResultFileUrl(objectKey);
|
||||
row.setResultFileSize(resultFile.length());
|
||||
row.setResultContentType(contentType);
|
||||
row.setRowCount(rowCount);
|
||||
fileResultMapper.updateById(row);
|
||||
}
|
||||
}
|
||||
+164
@@ -0,0 +1,164 @@
|
||||
package com.nanri.aiimage.modules.task.service.pipeline;
|
||||
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
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.model.entity.FileResultEntity;
|
||||
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
|
||||
import com.nanri.aiimage.modules.task.service.TaskDistributedLockService;
|
||||
import com.nanri.aiimage.modules.task.service.TaskFileJobService;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
|
||||
/**
|
||||
* 「店铺维度合并载荷」家族的回传落库(段 3)骨架——{@link AbstractFileTaskPipeline} 的家族层。
|
||||
*
|
||||
* <p><b>为什么只有这一族值得再下一层。</b>2026-10-18 实贴七支的 {@code submitResult},
|
||||
* 合并模型实测分三族:chunk+scope(AppearancePatent/Publish/CollectData)、
|
||||
* shop-payload(ShopDataCrawl/ShopMatch/PriceTrack)、DeleteBrand 自有分片存储。
|
||||
* 其中 <b>ShopMatch 与 PriceTrack 两支的 {@code submitResult} 是行级孪生件</b>:
|
||||
* 校验→取锁→准入→按店铺名建索引→逐行合并→{@code changed} 闸门→重读结果行→重算任务状态
|
||||
* 整段结构一致({@code ShopMatchTaskService:630-710} 对 {@code PriceTrackTaskService:591-663}),
|
||||
* 差异全在「单行怎么处理」那一步里。ShopDataCrawl 只共用「准入」与「用
|
||||
* {@code row.sourceFilename} 当作用域匹配键」这两件事({@code :644-648}):它的索引是自建的
|
||||
* {@code normalizePayloadByShop(shops, 首行店铺名)}({@code :641}),尾部<b>没有</b> {@code changed}
|
||||
* 闸门而是无条件 {@code persistProgressOrSnapshot}+{@code tryFinalizeTask}({@code :679-681}),
|
||||
* 单行体整段走快照机——所以本模板对 ShopDataCrawl <b>不适用</b>,那一支保留自己的写法。
|
||||
*
|
||||
* <p><b>刻意不沉的两处</b>(沉了就是替现网做决定,Phase 3 会拿不到行为对撞):
|
||||
* <ul>
|
||||
* <li>单行处理体:ShopMatch 先合并再判 {@code error}({@code :680-684}),PriceTrack 先判
|
||||
* {@code error} 与 {@code success==FALSE} 再合并({@code :627-636}),且 PriceTrack 多一段
|
||||
* {@code handleSkipAsinDeletionSignals}——合并时机与副作用顺序不同,抽成一个钩子实现,
|
||||
* 两套语义各自保留。</li>
|
||||
* <li>结果簿组装:两支的 {@code assembleShopResult} 近乎相同,但各自吃
|
||||
* {@code ShopMatchExcelAssemblyService}/{@code PriceTrackExcelAssemblyService} 两种类型,
|
||||
* 合并它们要先造一个装配服务接口=新立抽象。两支共同的「上传+6 列落库」那截
|
||||
* 已由 {@link AbstractFileTaskPipeline#publishResultFile} 承接。</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>店铺名归一化留成钩子:两支现网都调 {@code ZiniaoShopSwitchService.normalizeShopName}
|
||||
* ({@code ShopMatchTaskService:665}/{@code PriceTrackTaskService:614}),但该 bean 在
|
||||
* {@code modules.ziniao} 下,底座直接依赖它会把 task→业务 的冻结线(0)顶开。
|
||||
*/
|
||||
public abstract class AbstractShopPayloadTaskPipeline<T> extends AbstractFileTaskPipeline<T> {
|
||||
|
||||
protected AbstractShopPayloadTaskPipeline(FileTaskMapper fileTaskMapper,
|
||||
FileResultMapper fileResultMapper,
|
||||
TaskDistributedLockService taskDistributedLockService,
|
||||
TaskFileJobService taskFileJobService,
|
||||
OssStorageService ossStorageService) {
|
||||
super(fileTaskMapper, fileResultMapper, taskDistributedLockService,
|
||||
taskFileJobService, ossStorageService);
|
||||
}
|
||||
|
||||
/**
|
||||
* 店铺名归一化(同时是结果行 {@code sourceFilename} 与载荷索引键的构造规则)。
|
||||
* 两支必须用同一规则建与查,否则回传永远匹配不上行。
|
||||
*/
|
||||
protected abstract String normalizeShopKey(String rawShopName);
|
||||
|
||||
/**
|
||||
* 单行处理:合并该店铺载荷,并按各自现网语义决定「失败置位/等待更多分片/挂组装 Job」。
|
||||
* 调用即代表本次回传命中了该行({@code changed} 由模板在调用前置位,与两支现网一致)。
|
||||
*/
|
||||
protected abstract void applyShopResultRow(Long taskId,
|
||||
FileTaskEntity task,
|
||||
FileResultEntity row,
|
||||
String shopKey,
|
||||
T incoming);
|
||||
|
||||
/** 本轮有行被命中后的收尾:两支现网都是拿最新结果行重算任务状态。 */
|
||||
protected abstract void onShopRowsRecomputed(FileTaskEntity task, List<FileResultEntity> latestRows);
|
||||
|
||||
/**
|
||||
* 锁竞争日志标签。历史值是各支小写短名({@code shop-match}/{@code price-track}/
|
||||
* {@code shop-data-crawl}),与 {@link #moduleType()} 的大写枚举形不同,
|
||||
* 默认返回 moduleType 仅供未覆写时不缺标签,两支迁移时必须按历史值覆写。
|
||||
*/
|
||||
protected String submissionLockLogTag() {
|
||||
return moduleType();
|
||||
}
|
||||
|
||||
/**
|
||||
* 索引建好、行循环开始之前的观察点。默认空实现。
|
||||
*
|
||||
* <p><b>为什么要有这一格——它是首迁实测出来的缺件,不是预留扩展点。</b>底座刻意不打日志
|
||||
* (见 {@link AbstractFileTaskPipeline#admitSubmission} 那句「日志不是公共形状」),
|
||||
* 而 PriceTrack{@code :617} 在现网有一句 {@code [price-track] submitResult received
|
||||
* payloadShopCount=.. payloadKeys=..},位置正好卡在「准入已通过+载荷已建索引+行循环还没开始」。
|
||||
* 那句话巡检按它数过回传批次,删掉就是改现网可观测行为;但除了这一格,模板里没有别的点
|
||||
* 能同时满足「在拒绝路径之后、在逐行处理之前、每次回传恰好一次」。
|
||||
* 所以给一个默认空的观察点:不需要它的支(ShopMatch)一个字都不用改。
|
||||
*/
|
||||
protected void onPayloadIndexed(FileTaskEntity task, Map<String, T> payloadByShopKey) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 段 3「回传落库」整段骨架。入参 {@code incoming} 即各支请求里的 {@code shops} 列表。
|
||||
*
|
||||
* <p>闸门与终态拒绝形状由 {@code terminalRejection} 决定;{@code ownershipOperation}
|
||||
* 传 {@code null} 表示不校验归属(两支现网都不校验)。
|
||||
*
|
||||
* <p>结果行匹配键取 {@code row.getSourceFilename()},因此建单时写进该列的必须是
|
||||
* {@link #normalizeShopKey(String)} 归一化后的店铺名({@code ShopMatchTaskService:499}
|
||||
* 与 {@code PriceTrackTaskService:534} 正是这么写的)。
|
||||
*
|
||||
* <p><b>校验在取锁之前</b>(按 PriceTrack{@code :592-596} 的形状):ShopMatch 现网把
|
||||
* {@code shops} 非空检查放在锁内({@code :634} 取锁 → {@code :643} 才检查)。两者对调用方
|
||||
* 的可见结果相同,本模板选前者是为了「明显不合法的请求不去抢锁」。迁移这一支时把这句
|
||||
* 微差登记在案,别让它变成「顺手改的」没人知道。
|
||||
*/
|
||||
protected final void submitShopScopedResults(Long taskId,
|
||||
List<T> incoming,
|
||||
Function<T, String> rawShopNameOf,
|
||||
TerminalRejection terminalRejection,
|
||||
String ownershipOperation) {
|
||||
requireTaskId(taskId);
|
||||
if (incoming == null || incoming.isEmpty()) {
|
||||
throw new BusinessException("shops 不能为空");
|
||||
}
|
||||
try (TaskDistributedLockService.LockHandle ignored =
|
||||
acquireSubmissionLockOrThrow(taskId, submissionLockLogTag())) {
|
||||
FileTaskEntity task = admitSubmission(taskId, terminalRejection, ownershipOperation);
|
||||
Map<String, T> payloadByShopKey = indexByShopKey(incoming, rawShopNameOf);
|
||||
onPayloadIndexed(task, payloadByShopKey);
|
||||
boolean changed = false;
|
||||
for (FileResultEntity row : listScopeRows(taskId)) {
|
||||
String shopKey = row.getSourceFilename();
|
||||
T item = shopKey == null ? null : payloadByShopKey.get(shopKey);
|
||||
if (item == null) {
|
||||
continue;
|
||||
}
|
||||
changed = true;
|
||||
applyShopResultRow(taskId, task, row, shopKey, item);
|
||||
}
|
||||
if (!changed) {
|
||||
return;
|
||||
}
|
||||
onShopRowsRecomputed(task, listScopeRows(taskId));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 回传载荷按店铺名建索引:跳过 null 项与归一化后为空的项,保持请求顺序。
|
||||
* 出处:{@code ShopMatchTaskService:660-669}/{@code PriceTrackTaskService:611-616}(逐字同形)。
|
||||
*/
|
||||
protected final Map<String, T> indexByShopKey(List<T> incoming, Function<T, String> rawShopNameOf) {
|
||||
Map<String, T> indexed = new LinkedHashMap<>();
|
||||
for (T item : incoming) {
|
||||
if (item == null) {
|
||||
continue;
|
||||
}
|
||||
String shopKey = normalizeShopKey(rawShopNameOf.apply(item));
|
||||
if (shopKey != null && !shopKey.isBlank()) {
|
||||
indexed.put(shopKey, item);
|
||||
}
|
||||
}
|
||||
return indexed;
|
||||
}
|
||||
}
|
||||
@@ -46,8 +46,9 @@ class CatchSilenceRatchetTest {
|
||||
|
||||
// ==== 验收基线(用户 2026-10-08 12:0x 实测,HEAD 274ad017,单位:处)====
|
||||
// 10-17 心跳证据两处 fail-open 抬 559 -> 561,逐处出处见 STRICT_NOT_RETHROW 上方注释。
|
||||
// 10-18 外观专利失败兜底自吞抬 561 -> 562,逐处出处同下。
|
||||
static final int GIVEN_TOTAL = 1000;
|
||||
static final int GIVEN_NOT_RETHROW = 561;
|
||||
static final int GIVEN_NOT_RETHROW = 562;
|
||||
static final int GIVEN_LOG_ONLY = 249;
|
||||
static final int GIVEN_EMPTY = 56;
|
||||
|
||||
@@ -65,8 +66,13 @@ class CatchSilenceRatchetTest {
|
||||
* 「没有证据」,判死线据此放宽)。两处都是 fail-open 且方向是「少杀一个任务」,与上面
|
||||
* BuildInfoLogger 同形状;本仓实测基线由 1001 起(原记 1002 留有 1 格无人认领的额度),
|
||||
* 加这 2 处后实测 1003。
|
||||
* 10-18 再 +1:{@code AppearancePatentTaskService.fallbackAssembleResultFile()} 的兜底自吞
|
||||
* (log.warn + return false)——{@code ResultFileJobHandler#fallbackAssembleOnFailure} 的接口
|
||||
* 契约明确要求「实现应自吞异常(兜底失败只记日志,不影响 job 已终态失败的事实)」,与
|
||||
* DeleteBrandRunService 同名兜底同形状;Worker 侧另有 catch 双保险,让判死作业的兜底每轮
|
||||
* stuck 扫描幂等重入。实测 1004。
|
||||
*/
|
||||
static final int STRICT_TOTAL = 1003;
|
||||
static final int STRICT_TOTAL = 1004;
|
||||
/**
|
||||
* 重抛型 catch 的**下限**(不是上限):本轮把两处吞异常改成重抛之后实测 388。
|
||||
* 这一格只能涨不能跌——它是"异常会往外走"的总量,把它钉成"只许减"就等于拦着别人修吞异常。
|
||||
@@ -89,8 +95,13 @@ class CatchSilenceRatchetTest {
|
||||
* 判死线据此**放宽**(顶多让任务多活一会儿,最终仍由未启动宽限与 stale-repair 兜底)。
|
||||
* 两处的误差方向都是「少杀一个任务」,与这一格想拦的「异常到此为止、外面看不见」不同性质;
|
||||
* 抬格是为了把出处留在这份 diff 里,而不是让后来人以为基线自然涨上来的。
|
||||
* 10-18 抬 561 -> 562,逐处记名:{@code AppearancePatentTaskService.fallbackAssembleResultFile()}——
|
||||
* 失败兜底组装的自吞出口(接口契约要求,见 {@code ResultFileJobHandler#fallbackAssembleOnFailure}),
|
||||
* 与 {@code DeleteBrandRunService.fallbackAssembleResultFile} 同形状、同性质:兜底失败不得掩盖
|
||||
* 作业已终态失败的事实,也不得打断 stuck 扫描对终态失败作业的幂等重入。形状是 log+return false,
|
||||
* 因此只进本格与 total,不进 STRICT_LOG_ONLY(严格口径不数 log 后接 return)。
|
||||
*/
|
||||
static final int STRICT_NOT_RETHROW = 561;
|
||||
static final int STRICT_NOT_RETHROW = 562;
|
||||
/**
|
||||
* 10-17 抬 172 -> 173,出处就是上面点名过的 {@code TaskHeartbeatLivenessService.stamp()}:
|
||||
* 块体只有「取到 key 名 + log.warn」一句,写心跳证据失败时既不重试也不抛出——
|
||||
|
||||
@@ -0,0 +1,306 @@
|
||||
package com.nanri.aiimage.config;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.nanri.aiimage.common.service.ResultDownloadResolver;
|
||||
import com.nanri.aiimage.modules.file.service.LocalFileStorageService;
|
||||
import com.nanri.aiimage.modules.file.service.oss.OssStorageService;
|
||||
import com.nanri.aiimage.modules.pricetrack.mapper.PriceTrackShopCandidateMapper;
|
||||
import com.nanri.aiimage.modules.pricetrack.service.PriceTrackExcelAssemblyService;
|
||||
import com.nanri.aiimage.modules.pricetrack.service.PriceTrackLoopRunService;
|
||||
import com.nanri.aiimage.modules.pricetrack.service.PriceTrackTaskCacheService;
|
||||
import com.nanri.aiimage.modules.pricetrack.service.PriceTrackTaskService;
|
||||
import com.nanri.aiimage.modules.shopkey.mapper.QueryAsinMapper;
|
||||
import com.nanri.aiimage.modules.shopkey.service.SkipPriceAsinService;
|
||||
import com.nanri.aiimage.modules.shopmatch.mapper.ShopMatchShopCandidateMapper;
|
||||
import com.nanri.aiimage.modules.shopmatch.service.ShopMatchExcelAssemblyService;
|
||||
import com.nanri.aiimage.modules.shopmatch.service.ShopMatchTaskCacheService;
|
||||
import com.nanri.aiimage.modules.shopmatch.service.ShopMatchTaskService;
|
||||
import com.nanri.aiimage.modules.task.mapper.FileResultMapper;
|
||||
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
|
||||
import com.nanri.aiimage.modules.task.service.TaskDistributedLockService;
|
||||
import com.nanri.aiimage.modules.task.service.TaskFileJobService;
|
||||
import com.nanri.aiimage.modules.task.service.TaskProgressLightAssembler;
|
||||
import com.nanri.aiimage.modules.task.service.TaskResultPayloadService;
|
||||
import com.nanri.aiimage.modules.task.service.pipeline.AbstractShopPayloadTaskPipeline;
|
||||
import com.nanri.aiimage.modules.ziniao.service.ZiniaoShopSwitchService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
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.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
|
||||
/**
|
||||
* 迁移过的那几支 {@code *TaskService} 的**真实容器装配切片**(重构蓝图 Phase 3·用户 2026-10-19 拍板补的一格)。
|
||||
*
|
||||
* <p><b>它替谁补位。</b>Phase 2/3 连续两格把「真机启动验收」如实登记成未做,理由写在蓝图 §5:
|
||||
* 本仓没有全容器装配测试({@code ConfigWiringSmokeTest} 只起 config 切片、
|
||||
* {@code ApiGuardCoverage*} 只起 HandlerMapping),而 {@code mvn -o spring-boot:run} 要 MySQL+Redis。
|
||||
* Phase 3 动了 {@code @Service} 的**构造器形状**(Lombok {@code @RequiredArgsConstructor} 生成枚
|
||||
* → 手写的显式枚,还要把 5 枚交给 {@code super})——这正是「装配相邻」的改动,光靠单测说不过去。
|
||||
* 本切片不连数据库,但走的是**真的 Spring 构造器解析**:隐式单构造器注入是否成立、
|
||||
* 底座那 5 枚是否真从 {@code super(...)} 落进来、两支是否各自拿到自己的缓存服务与装配服务。
|
||||
*
|
||||
* <p><b>为什么不只断言「refresh() 没抛异常」。</b>那是一句会说谎的判据:Spring 6 在没有
|
||||
* {@code @Autowired} 而存在多枚 public 构造器时,会**静默挑无参那一枚**,容器照样起得来、
|
||||
* 字段全 null。所以下面用两枚探针类各做一次非零对照(一枚该红、一枚「起得来但字段空」),
|
||||
* 再用逐枚 {@code assertSame} 的字段断言作为真正的判据——探针不红、字段不空,这两条同时成立
|
||||
* 才说明这套断言有牙。
|
||||
*
|
||||
* <p>依赖一律是 Mockito 桩:本切片量的是**装配**,不是这些协作者的行为。
|
||||
*/
|
||||
class TaskServiceWiringSliceTest {
|
||||
|
||||
@Configuration
|
||||
static class Collaborators {
|
||||
@Bean FileTaskMapper fileTaskMapper() {
|
||||
return mock(FileTaskMapper.class);
|
||||
}
|
||||
|
||||
@Bean FileResultMapper fileResultMapper() {
|
||||
return mock(FileResultMapper.class);
|
||||
}
|
||||
|
||||
@Bean ShopMatchShopCandidateMapper shopMatchCandidateMapper() {
|
||||
return mock(ShopMatchShopCandidateMapper.class);
|
||||
}
|
||||
|
||||
@Bean PriceTrackShopCandidateMapper priceTrackCandidateMapper() {
|
||||
return mock(PriceTrackShopCandidateMapper.class);
|
||||
}
|
||||
|
||||
@Bean ZiniaoShopSwitchService ziniaoShopSwitchService() {
|
||||
return mock(ZiniaoShopSwitchService.class);
|
||||
}
|
||||
|
||||
@Bean ShopMatchExcelAssemblyService shopMatchExcelAssemblyService() {
|
||||
return mock(ShopMatchExcelAssemblyService.class);
|
||||
}
|
||||
|
||||
@Bean PriceTrackExcelAssemblyService priceTrackExcelAssemblyService() {
|
||||
return mock(PriceTrackExcelAssemblyService.class);
|
||||
}
|
||||
|
||||
@Bean OssStorageService ossStorageService() {
|
||||
return mock(OssStorageService.class);
|
||||
}
|
||||
|
||||
@Bean ResultDownloadResolver resultDownloadResolver() {
|
||||
return mock(ResultDownloadResolver.class);
|
||||
}
|
||||
|
||||
@Bean ObjectMapper objectMapper() {
|
||||
return mock(ObjectMapper.class);
|
||||
}
|
||||
|
||||
@Bean ShopMatchTaskCacheService shopMatchTaskCacheService() {
|
||||
return mock(ShopMatchTaskCacheService.class);
|
||||
}
|
||||
|
||||
@Bean PriceTrackTaskCacheService priceTrackTaskCacheService() {
|
||||
return mock(PriceTrackTaskCacheService.class);
|
||||
}
|
||||
|
||||
@Bean com.nanri.aiimage.config.TaskPressureProperties taskPressureProperties() {
|
||||
return mock(com.nanri.aiimage.config.TaskPressureProperties.class);
|
||||
}
|
||||
|
||||
@Bean TaskResultPayloadService taskResultPayloadService() {
|
||||
return mock(TaskResultPayloadService.class);
|
||||
}
|
||||
|
||||
@Bean TaskFileJobService taskFileJobService() {
|
||||
return mock(TaskFileJobService.class);
|
||||
}
|
||||
|
||||
@Bean TaskDistributedLockService taskDistributedLockService() {
|
||||
return mock(TaskDistributedLockService.class);
|
||||
}
|
||||
|
||||
@Bean SkipPriceAsinService skipPriceAsinService() {
|
||||
return mock(SkipPriceAsinService.class);
|
||||
}
|
||||
|
||||
@Bean QueryAsinMapper queryAsinMapper() {
|
||||
return mock(QueryAsinMapper.class);
|
||||
}
|
||||
|
||||
@Bean TaskProgressLightAssembler taskProgressLightAssembler() {
|
||||
return mock(TaskProgressLightAssembler.class);
|
||||
}
|
||||
|
||||
@Bean PlatformTransactionManager platformTransactionManager() {
|
||||
return mock(PlatformTransactionManager.class);
|
||||
}
|
||||
|
||||
@Bean PriceTrackLoopRunService priceTrackLoopRunService() {
|
||||
return mock(PriceTrackLoopRunService.class);
|
||||
}
|
||||
|
||||
@Bean LocalFileStorageService localFileStorageService() {
|
||||
return mock(LocalFileStorageService.class);
|
||||
}
|
||||
}
|
||||
|
||||
private static AnnotationConfigApplicationContext context(Class<?>... services) {
|
||||
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
|
||||
ctx.register(Collaborators.class);
|
||||
ctx.register(services);
|
||||
ctx.refresh();
|
||||
return ctx;
|
||||
}
|
||||
|
||||
/** 沿类继承链找字段——底座那 5 枚在 {@code AbstractFileTaskPipeline} 上,本支的在自己的类里。 */
|
||||
private static Object fieldValue(Object target, String fieldName) {
|
||||
for (Class<?> type = target.getClass(); type != null; type = type.getSuperclass()) {
|
||||
try {
|
||||
Field field = type.getDeclaredField(fieldName);
|
||||
field.setAccessible(true);
|
||||
return field.get(target);
|
||||
} catch (NoSuchFieldException ignored) {
|
||||
// 继续往父类找;全链都没有才算缺件
|
||||
} catch (IllegalAccessException ex) {
|
||||
throw new IllegalStateException("读不到 " + target.getClass() + "." + fieldName, ex);
|
||||
}
|
||||
}
|
||||
throw new AssertionError("字段不存在:" + target.getClass().getName() + "#" + fieldName
|
||||
+ "(迁移把字段沉进底座时改名了?那就该红,别让它悄悄通过)");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// 正判:真实容器把两支建起来,且每一枚依赖都落在它该落的位置
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void migratedServicesInstantiateThroughTheSpringContainer() {
|
||||
try (AnnotationConfigApplicationContext ctx =
|
||||
context(ShopMatchTaskService.class, PriceTrackTaskService.class)) {
|
||||
ShopMatchTaskService shopMatch = ctx.getBean(ShopMatchTaskService.class);
|
||||
PriceTrackTaskService priceTrack = ctx.getBean(PriceTrackTaskService.class);
|
||||
|
||||
assertNotNull(shopMatch, "Lombok 生成枚换成显式枚之后,Spring 仍要能隐式构造注入");
|
||||
assertNotNull(priceTrack);
|
||||
assertTrue(shopMatch instanceof AbstractShopPayloadTaskPipeline,
|
||||
"Phase 3 的判据是「真有生产调用方继承底座」,不是只由单测证明契约可用");
|
||||
assertTrue(priceTrack instanceof AbstractShopPayloadTaskPipeline);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void superCallLandsTheFiveBaseDependenciesInOrder() {
|
||||
try (AnnotationConfigApplicationContext ctx =
|
||||
context(ShopMatchTaskService.class, PriceTrackTaskService.class)) {
|
||||
ShopMatchTaskService shopMatch = ctx.getBean(ShopMatchTaskService.class);
|
||||
PriceTrackTaskService priceTrack = ctx.getBean(PriceTrackTaskService.class);
|
||||
|
||||
// 这五枚是交给 super(...) 的那五枚。参数表里它们与其余 12/13 枚同类型不重复,
|
||||
// 换位会在编译期就被挡住——但「少交一枚」「交 null」不会。逐枚 assertSame 才是硬证。
|
||||
for (Object service : List.of(shopMatch, priceTrack)) {
|
||||
assertSame(ctx.getBean(FileTaskMapper.class), fieldValue(service, "fileTaskMapper"));
|
||||
assertSame(ctx.getBean(FileResultMapper.class), fieldValue(service, "fileResultMapper"));
|
||||
assertSame(ctx.getBean(TaskDistributedLockService.class),
|
||||
fieldValue(service, "taskDistributedLockService"));
|
||||
assertSame(ctx.getBean(TaskFileJobService.class), fieldValue(service, "taskFileJobService"));
|
||||
assertSame(ctx.getBean(OssStorageService.class), fieldValue(service, "ossStorageService"));
|
||||
}
|
||||
|
||||
// 两支各自的私有件:绝不能把 A 支的缓存服务注进 B 支(同族两个 bean,最容易串的就是这儿)
|
||||
assertSame(ctx.getBean(ShopMatchTaskCacheService.class), fieldValue(shopMatch, "shopMatchTaskCacheService"));
|
||||
assertSame(ctx.getBean(PriceTrackTaskCacheService.class), fieldValue(priceTrack, "priceTrackTaskCacheService"));
|
||||
assertSame(ctx.getBean(ShopMatchExcelAssemblyService.class), fieldValue(shopMatch, "excelAssemblyService"));
|
||||
assertSame(ctx.getBean(PriceTrackExcelAssemblyService.class), fieldValue(priceTrack, "excelAssemblyService"));
|
||||
assertSame(ctx.getBean(ShopMatchShopCandidateMapper.class), fieldValue(shopMatch, "candidateMapper"));
|
||||
assertSame(ctx.getBean(PriceTrackShopCandidateMapper.class), fieldValue(priceTrack, "candidateMapper"));
|
||||
assertSame(ctx.getBean(PriceTrackLoopRunService.class), fieldValue(priceTrack, "priceTrackLoopRunService"));
|
||||
assertSame(ctx.getBean(LocalFileStorageService.class), fieldValue(priceTrack, "localFileStorageService"));
|
||||
assertSame(ctx.getBean(QueryAsinMapper.class), fieldValue(shopMatch, "queryAsinMapper"));
|
||||
assertSame(ctx.getBean(PlatformTransactionManager.class), fieldValue(shopMatch, "transactionManager"));
|
||||
assertSame(ctx.getBean(PlatformTransactionManager.class), fieldValue(priceTrack, "transactionManager"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void injectedCollaboratorsAreActuallyUsedAndEachBranchReportsItsOwnModuleType() {
|
||||
try (AnnotationConfigApplicationContext ctx =
|
||||
context(ShopMatchTaskService.class, PriceTrackTaskService.class)) {
|
||||
TaskProgressLightAssembler assembler = ctx.getBean(TaskProgressLightAssembler.class);
|
||||
ShopMatchTaskService shopMatch = ctx.getBean(ShopMatchTaskService.class);
|
||||
PriceTrackTaskService priceTrack = ctx.getBean(PriceTrackTaskService.class);
|
||||
List<Long> taskIds = List.of(1L);
|
||||
|
||||
shopMatch.progressLight(taskIds, 7L);
|
||||
priceTrack.progressLight(taskIds, 7L);
|
||||
|
||||
// moduleType() 是迁移新加的钩子:回错一支,心跳、结果行与组装 Job 全挂到别人模块上,
|
||||
// 而建单照样成功——那种错只有在这里才看得见。
|
||||
verify(assembler, times(1)).assemble(eq("SHOP_MATCH"), eq(7L), eq(taskIds));
|
||||
verify(assembler, times(1)).assemble(eq("PRICE_TRACK"), eq(7L), eq(taskIds));
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// 非零对照:证明上面那两条判据不是恒绿
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/** 两枚 public 构造器且都带参:Spring 找不到候选构造器 ⇒ 容器必须起不来。 */
|
||||
static class TwoConstructorsService {
|
||||
TwoConstructorsService(FileTaskMapper fileTaskMapper) {
|
||||
}
|
||||
|
||||
TwoConstructorsService(FileTaskMapper fileTaskMapper, FileResultMapper fileResultMapper) {
|
||||
}
|
||||
}
|
||||
|
||||
/** 一枚无参+一枚带参:Spring **静默挑无参那一枚**,容器起得来、字段全 null——所以「起得来」不是证据。 */
|
||||
static class SilentNoArgConstructorService {
|
||||
private final FileTaskMapper fileTaskMapper;
|
||||
|
||||
SilentNoArgConstructorService() {
|
||||
this.fileTaskMapper = null;
|
||||
}
|
||||
|
||||
SilentNoArgConstructorService(FileTaskMapper fileTaskMapper) {
|
||||
this.fileTaskMapper = fileTaskMapper;
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void ambiguousConstructorsFailTheContainerSoTheSliceCanActuallyGoRed() {
|
||||
try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) {
|
||||
ctx.register(Collaborators.class);
|
||||
ctx.register(TwoConstructorsService.class);
|
||||
assertThrows(Exception.class, ctx::refresh,
|
||||
"探针没红 ⇒ 这套装配判据是恒绿的,正判用例说了不算");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void containerStartingGreenIsNotProofBecauseSpringSilentlyPicksTheNoArgConstructor() {
|
||||
try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) {
|
||||
ctx.register(Collaborators.class);
|
||||
ctx.register(SilentNoArgConstructorService.class);
|
||||
ctx.refresh();
|
||||
SilentNoArgConstructorService probe = ctx.getBean(SilentNoArgConstructorService.class);
|
||||
|
||||
assertNotNull(probe, "无参那一枚被静默选中:容器确实起得来");
|
||||
assertNull(fieldValue(probe, "fileTaskMapper"),
|
||||
"而字段是空的——这正是「只断言 refresh 不抛异常」会放过去的失效模式,"
|
||||
+ "所以上面两条用例走的是逐枚 assertSame");
|
||||
verifyNoInteractions(ctx.getBean(FileTaskMapper.class));
|
||||
}
|
||||
}
|
||||
}
|
||||
+36
@@ -181,6 +181,24 @@ class AppearancePatentDeliveryGateTest {
|
||||
}
|
||||
}
|
||||
|
||||
/** 失败兜底路径的 4 参口径:allowPartial=true 时覆盖率闸门放行(作业已判死,缺口不再有补齐窗口)。 */
|
||||
private AppearancePatentRowOutcome.Facts validatePartial(List<AppearancePatentParsedRowVo> rows,
|
||||
Map<String, AppearancePatentResultRowDto> resultMap,
|
||||
boolean allowPartial)
|
||||
throws Exception {
|
||||
Method method = AppearancePatentTaskService.class.getDeclaredMethod(
|
||||
"validateCompleteLlmCoverage", Long.class, List.class, Map.class, boolean.class);
|
||||
method.setAccessible(true);
|
||||
try {
|
||||
return (AppearancePatentRowOutcome.Facts) method.invoke(service, TASK_ID, rows, resultMap, allowPartial);
|
||||
} catch (InvocationTargetException ex) {
|
||||
if (ex.getCause() instanceof RuntimeException runtime) {
|
||||
throw runtime;
|
||||
}
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean requestRecheck(FileTaskEntity task, TaskFileJobEntity job,
|
||||
AppearancePatentRowOutcome.Facts facts) throws Exception {
|
||||
Method method = AppearancePatentTaskService.class.getDeclaredMethod(
|
||||
@@ -254,6 +272,24 @@ class AppearancePatentDeliveryGateTest {
|
||||
assertEquals(5, facts.noDataRows());
|
||||
}
|
||||
|
||||
@Test
|
||||
void allowPartialLetsBelowFloorCoverageThroughForFailureFallback() throws Exception {
|
||||
// 同一份 50% 覆盖率:常规路径判红(belowFloorThrowsWithBothCountersInTheMessage),
|
||||
// 兜底路径放行——作业已判死,此刻拦下成品只会让用户连半张表都拿不到(线上任务 31302)
|
||||
List<AppearancePatentParsedRowVo> rows = List.of(sheetRow("1", "B0A1"), sheetRow("2", "B0A2"),
|
||||
sheetRow("3", "B0A3"));
|
||||
Map<String, AppearancePatentResultRowDto> map = new LinkedHashMap<>();
|
||||
map.putAll(submittedRows(List.of(sheetRow("1", "B0A1")), 1, true));
|
||||
map.putAll(submittedRows(List.of(sheetRow("2", "B0A2")), 0, true));
|
||||
map.putAll(submittedRows(List.of(sheetRow("3", "B0A3")), 0, false));
|
||||
when(fileTaskMapper.selectById(TASK_ID)).thenReturn(task("RUNNING"));
|
||||
|
||||
AppearancePatentRowOutcome.Facts facts = validatePartial(rows, map, true);
|
||||
assertEquals(2, facts.expectedRows());
|
||||
assertEquals(1, facts.judgedRows());
|
||||
assertEquals(1, facts.missingRows());
|
||||
}
|
||||
|
||||
// ---------- 补检出口 ----------
|
||||
|
||||
@Test
|
||||
|
||||
+150
@@ -0,0 +1,150 @@
|
||||
package com.nanri.aiimage.modules.appearancepatent.service;
|
||||
|
||||
import com.nanri.aiimage.common.service.DistributedJobLockService;
|
||||
import com.nanri.aiimage.config.AppearancePatentProperties;
|
||||
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.file.service.LocalFileStorageService;
|
||||
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.TaskFileJobEntity;
|
||||
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.TaskProgressSnapshotService;
|
||||
import com.nanri.aiimage.modules.task.service.TransientPayloadStorageService;
|
||||
import com.nanri.aiimage.modules.usersecret.service.UserApiSecretService;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* 失败兜底组装的守卫与幂等(2026-10-18,线上任务 31302/31354 死因修复)。
|
||||
*
|
||||
* <p>组装作业重试耗尽判死后,用户要「起码失败了也可以下载」:兜底用已有分片/结论出
|
||||
* 部分结果文件。本类钉住兜底入口的分支语义;组装主体(xlsx 生成/上传)由
|
||||
* AppearancePatentSheetBuilderTest/AppearancePatentResultFormatTest/交付闸门测试覆盖。
|
||||
*/
|
||||
class AppearancePatentFallbackAssembleTest {
|
||||
|
||||
private static final long TASK_ID = 31302L;
|
||||
private static final long RESULT_ID = 9001L;
|
||||
private static final long JOB_ID = 7001L;
|
||||
|
||||
private final FileTaskMapper fileTaskMapper = mock(FileTaskMapper.class);
|
||||
private final FileResultMapper fileResultMapper = mock(FileResultMapper.class);
|
||||
private final TaskScopeStateMapper taskScopeStateMapper = mock(TaskScopeStateMapper.class);
|
||||
private final TaskChunkMapper taskChunkMapper = mock(TaskChunkMapper.class);
|
||||
private final LocalFileStorageService localFileStorageService = mock(LocalFileStorageService.class);
|
||||
private final AppearancePatentLlmClient llmClient = mock(AppearancePatentLlmClient.class);
|
||||
private final AppearancePatentTaskCacheService taskCacheService = mock(AppearancePatentTaskCacheService.class);
|
||||
private final AppearancePatentProperties properties = mock(AppearancePatentProperties.class);
|
||||
private final StorageProperties storageProperties = mock(StorageProperties.class);
|
||||
private final TaskFileJobService taskFileJobService = mock(TaskFileJobService.class);
|
||||
private final TaskProgressSnapshotService taskProgressSnapshotService = mock(TaskProgressSnapshotService.class);
|
||||
private final TransientPayloadStorageService transientPayloadStorageService = mock(TransientPayloadStorageService.class);
|
||||
private final PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class);
|
||||
private final DistributedJobLockService distributedJobLockService = mock(DistributedJobLockService.class);
|
||||
private final TaskDistributedLockService taskDistributedLockService = mock(TaskDistributedLockService.class);
|
||||
private final InstanceMetadata instanceMetadata = mock(InstanceMetadata.class);
|
||||
|
||||
private AppearancePatentTaskService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
when(properties.getLlmCoverageMinRatio()).thenReturn(0.95D);
|
||||
service = new AppearancePatentTaskService(
|
||||
localFileStorageService, null,
|
||||
mock(com.nanri.aiimage.common.service.ResultDownloadResolver.class),
|
||||
storageProperties, fileTaskMapper, fileResultMapper,
|
||||
taskScopeStateMapper, taskChunkMapper, new ObjectMapper(), llmClient, taskCacheService,
|
||||
properties, taskFileJobService, taskProgressSnapshotService,
|
||||
mock(TaskHeartbeatPositionService.class), transientPayloadStorageService, transactionManager,
|
||||
distributedJobLockService, taskDistributedLockService, instanceMetadata,
|
||||
mock(TaskProgressLightAssembler.class), mock(UserApiSecretService.class));
|
||||
}
|
||||
|
||||
private static TaskFileJobEntity job() {
|
||||
TaskFileJobEntity job = new TaskFileJobEntity();
|
||||
job.setId(JOB_ID);
|
||||
job.setTaskId(TASK_ID);
|
||||
job.setResultId(RESULT_ID);
|
||||
job.setModuleType("APPEARANCE_PATENT");
|
||||
job.setStatus("FAILED");
|
||||
return job;
|
||||
}
|
||||
|
||||
private static FileResultEntity result(String resultFileUrl) {
|
||||
FileResultEntity result = new FileResultEntity();
|
||||
result.setId(RESULT_ID);
|
||||
result.setTaskId(TASK_ID);
|
||||
result.setModuleType("APPEARANCE_PATENT");
|
||||
result.setResultFileUrl(resultFileUrl);
|
||||
return result;
|
||||
}
|
||||
|
||||
private static FileTaskEntity task() {
|
||||
FileTaskEntity task = new FileTaskEntity();
|
||||
task.setId(TASK_ID);
|
||||
task.setModuleType("APPEARANCE_PATENT");
|
||||
task.setStatus("FAILED");
|
||||
task.setUserId(7L);
|
||||
return task;
|
||||
}
|
||||
|
||||
@Test
|
||||
void incompleteJobArgumentsAreRejected() {
|
||||
assertFalse(service.fallbackAssembleResultFile(null), "null 作业直接拒绝");
|
||||
assertFalse(service.fallbackAssembleResultFile(new TaskFileJobEntity()), "缺 taskId/resultId 直接拒绝");
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingResultRecordReturnsFalse() {
|
||||
when(fileResultMapper.selectById(RESULT_ID)).thenReturn(null);
|
||||
assertFalse(service.fallbackAssembleResultFile(job()), "结果记录不存在(孤儿作业)无可组装");
|
||||
verify(fileTaskMapper, never()).selectById(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void existingResultFileShortCircuitsAssemble() {
|
||||
// 幂等:stuck 扫描对终态失败作业每轮重入兜底钩子,已有结果文件就不再重做组装
|
||||
when(fileResultMapper.selectById(RESULT_ID)).thenReturn(result("appearance-patent/existing.xlsx"));
|
||||
assertTrue(service.fallbackAssembleResultFile(job()), "已有结果文件视为兜底成功");
|
||||
verify(fileTaskMapper, never()).selectById(any());
|
||||
verify(fileResultMapper, never()).updateById(any(FileResultEntity.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingTaskRecordReturnsFalse() {
|
||||
when(fileResultMapper.selectById(RESULT_ID)).thenReturn(result(null));
|
||||
when(fileTaskMapper.selectById(TASK_ID)).thenReturn(null);
|
||||
assertFalse(service.fallbackAssembleResultFile(job()), "任务记录不存在无可组装");
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptyPayloadFailsSoftlyWithoutTouchingResult() {
|
||||
// 组装抛业务异常(无可解析行)时兜底自吞:返回 false、不改写 result,作业保持终态失败
|
||||
when(fileResultMapper.selectById(RESULT_ID)).thenReturn(result(null));
|
||||
FileTaskEntity task = task();
|
||||
task.setResultJson("{}");
|
||||
when(fileTaskMapper.selectById(TASK_ID)).thenReturn(task);
|
||||
|
||||
assertFalse(service.fallbackAssembleResultFile(job()), "空载荷组装失败要被吞掉");
|
||||
verify(fileResultMapper, never()).updateById(any(FileResultEntity.class));
|
||||
}
|
||||
}
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
package com.nanri.aiimage.modules.appearancepatent.service;
|
||||
|
||||
import com.nanri.aiimage.config.AppearancePatentProperties;
|
||||
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
|
||||
import com.nanri.aiimage.modules.task.service.TaskFileJobService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* 外观专利任务心跳的组装作业续租(2026-10-18,线上任务 31354 死因修复)。
|
||||
*
|
||||
* <p>组装作业在 WAIT_LLM 停放期间执行线程已退出、Worker 执行期心跳已取消,若无人续命,
|
||||
* job 级 stuck 扫描(stuck-timeout-minutes 默认 5 分钟)会按 updated_at 判陈旧、
|
||||
* 5 次重试耗尽后误判「文件生成任务运行超时」。客户端心跳经 onHeartbeat 触发
|
||||
* touchRunningAssembleJobsIfStale 按配置间隔节流续租(与 SimilarAsinTaskHeartbeatSpi 同口径)。
|
||||
*/
|
||||
class AppearancePatentTaskHeartbeatSpiTest {
|
||||
|
||||
private final AppearancePatentTaskCacheService cacheService = mock(AppearancePatentTaskCacheService.class);
|
||||
private final TaskFileJobService taskFileJobService = mock(TaskFileJobService.class);
|
||||
private final AppearancePatentProperties properties = new AppearancePatentProperties();
|
||||
|
||||
private AppearancePatentTaskHeartbeatSpi spi;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
spi = new AppearancePatentTaskHeartbeatSpi(cacheService, taskFileJobService, properties);
|
||||
}
|
||||
|
||||
@Test
|
||||
void onHeartbeatRenewsAssembleJobLease() {
|
||||
FileTaskEntity task = new FileTaskEntity();
|
||||
task.setId(31354L);
|
||||
task.setModuleType("APPEARANCE_PATENT");
|
||||
|
||||
spi.onHeartbeat(task);
|
||||
|
||||
verify(taskFileJobService).touchRunningAssembleJobsIfStale(31354L, "APPEARANCE_PATENT",
|
||||
properties.getDbJobTouchIntervalMillis());
|
||||
}
|
||||
|
||||
@Test
|
||||
void touchIntervalBelowStuckScanFloor() {
|
||||
// 续命间隔必须小于 stuck 扫描阈值(5 分钟),否则停放作业在两跳续命之间仍会被判陈旧
|
||||
org.junit.jupiter.api.Assertions.assertTrue(properties.getDbJobTouchIntervalMillis() < 5 * 60_000L,
|
||||
"dbJobTouchIntervalMillis 应小于 stuck-timeout-minutes=5 分钟,实际 "
|
||||
+ properties.getDbJobTouchIntervalMillis());
|
||||
}
|
||||
|
||||
@Test
|
||||
void onHeartbeatWithNullTaskTouchesNothing() {
|
||||
spi.onHeartbeat(null);
|
||||
FileTaskEntity task = new FileTaskEntity();
|
||||
spi.onHeartbeat(task);
|
||||
verifyNoInteractions(taskFileJobService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void touchHeartbeatStillDelegatesToCache() {
|
||||
spi.touchHeartbeat(1L, null);
|
||||
verify(cacheService).touchTaskHeartbeat(1L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void moduleTypeMatchesRegistry() {
|
||||
org.junit.jupiter.api.Assertions.assertEquals("APPEARANCE_PATENT", spi.moduleType());
|
||||
}
|
||||
}
|
||||
+62
@@ -4,6 +4,7 @@ import cn.hutool.core.io.FileUtil;
|
||||
import com.baomidou.mybatisplus.core.MybatisConfiguration;
|
||||
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.modules.notification.service.NotificationDispatchService;
|
||||
import com.nanri.aiimage.modules.task.mapper.FileResultMapper;
|
||||
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
|
||||
@@ -25,11 +26,13 @@ import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import java.io.File;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@@ -49,6 +52,7 @@ class CollectDataPartialResultNoticeTest {
|
||||
|
||||
@Mock private FileTaskMapper fileTaskMapper;
|
||||
@Mock private FileResultMapper fileResultMapper;
|
||||
@Mock private com.nanri.aiimage.modules.task.mapper.TaskResultItemMapper taskResultItemMapper;
|
||||
@Mock private CollectDataExcelAssemblyService excelAssemblyService;
|
||||
@Mock private OssStorageService ossStorageService;
|
||||
@Mock private NotificationDispatchService notificationDispatchService;
|
||||
@@ -102,6 +106,8 @@ class CollectDataPartialResultNoticeTest {
|
||||
when(fileTaskMapper.selectById(TASK_ID)).thenReturn(taskWithQueryFailedRows(7));
|
||||
when(fileResultMapper.selectById(5001L)).thenReturn(result());
|
||||
when(excelAssemblyService.writeWorkbookStreaming(any(), any(), any(), any())).thenReturn(12L);
|
||||
// 空明细守卫按明细表行数校验:happy path 下表内行数与写出行数一致。
|
||||
when(taskResultItemMapper.selectCount(any())).thenReturn(12L);
|
||||
when(ossStorageService.uploadResultFile(any(), anyString())).thenReturn("collect-data/29991.xlsx");
|
||||
// 条件更新返回 1:任务翻成成功,这条「部分缺失」通知才会推给用户
|
||||
when(fileTaskMapper.update(isNull(), any())).thenReturn(1);
|
||||
@@ -138,6 +144,8 @@ class CollectDataPartialResultNoticeTest {
|
||||
when(fileTaskMapper.selectById(TASK_ID)).thenReturn(taskWithQueryFailedRows(7));
|
||||
when(fileResultMapper.selectById(5001L)).thenReturn(result());
|
||||
when(excelAssemblyService.writeWorkbookStreaming(any(), any(), any(), any())).thenReturn(12L);
|
||||
// 空明细守卫按明细表行数校验:happy path 下表内行数与写出行数一致。
|
||||
when(taskResultItemMapper.selectCount(any())).thenReturn(12L);
|
||||
when(ossStorageService.uploadResultFile(any(), anyString())).thenReturn("collect-data/29991.xlsx");
|
||||
when(fileTaskMapper.update(isNull(), any())).thenReturn(0);
|
||||
|
||||
@@ -146,4 +154,58 @@ class CollectDataPartialResultNoticeTest {
|
||||
verify(notificationDispatchService, org.mockito.Mockito.never())
|
||||
.pushPartialResult(anyLong(), anyLong(), anyString(), anyString(), anyString());
|
||||
}
|
||||
|
||||
/** 空明细守卫:明细表有 20 行而本次只写出 12 行=静默丢行,必须让作业重试而不是出缺行文件。 */
|
||||
@Test
|
||||
void 明细缺行时不得上传文件并把任务标成功() {
|
||||
when(fileTaskMapper.selectById(TASK_ID)).thenReturn(taskWithQueryFailedRows(0));
|
||||
when(fileResultMapper.selectById(5001L)).thenReturn(result());
|
||||
when(excelAssemblyService.writeWorkbookStreaming(any(), any(), any(), any())).thenReturn(12L);
|
||||
when(taskResultItemMapper.selectCount(any())).thenReturn(20L);
|
||||
|
||||
assertThatThrownBy(() -> service.processResultFileJob(job()))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("仅写出 12 行");
|
||||
|
||||
verify(ossStorageService, never()).uploadResultFile(any(), anyString());
|
||||
verify(fileTaskMapper, never()).update(isNull(), any());
|
||||
}
|
||||
|
||||
/**
|
||||
* 空明细守卫:task 31253 的形状——result_json 的插入计数写着 93,明细表却一行都没有,
|
||||
* 于是产出一份 4373 字节的纯表头 xlsx、row_count=0,任务仍被标成「已完成」。
|
||||
* 计数与唯一数据源对不上账时不许出表。
|
||||
*/
|
||||
@Test
|
||||
void 计数有行而明细表为空时不得出空文件() {
|
||||
FileTaskEntity task = taskWithQueryFailedRows(0);
|
||||
task.setResultJson("{\"finalRowCount\":93}");
|
||||
when(fileTaskMapper.selectById(TASK_ID)).thenReturn(task);
|
||||
when(fileResultMapper.selectById(5001L)).thenReturn(result());
|
||||
when(excelAssemblyService.writeWorkbookStreaming(any(), any(), any(), any())).thenReturn(0L);
|
||||
when(taskResultItemMapper.selectCount(any())).thenReturn(0L);
|
||||
|
||||
assertThatThrownBy(() -> service.processResultFileJob(job()))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("明细表为空");
|
||||
|
||||
verify(ossStorageService, never()).uploadResultFile(any(), anyString());
|
||||
}
|
||||
|
||||
/** 合法空结果:明细表 0 行且计数也是 0(全部行被过滤掉),照常出表并标成功。 */
|
||||
@Test
|
||||
void 全部行被过滤时空表仍合法出表() {
|
||||
FileTaskEntity task = taskWithQueryFailedRows(0);
|
||||
task.setResultJson("{}");
|
||||
when(fileTaskMapper.selectById(TASK_ID)).thenReturn(task);
|
||||
when(fileResultMapper.selectById(5001L)).thenReturn(result());
|
||||
when(excelAssemblyService.writeWorkbookStreaming(any(), any(), any(), any())).thenReturn(0L);
|
||||
when(taskResultItemMapper.selectCount(any())).thenReturn(0L);
|
||||
when(ossStorageService.uploadResultFile(any(), anyString())).thenReturn("collect-data/29991.xlsx");
|
||||
when(fileTaskMapper.update(isNull(), any())).thenReturn(1);
|
||||
|
||||
service.processResultFileJob(job());
|
||||
|
||||
verify(ossStorageService).uploadResultFile(any(), anyString());
|
||||
}
|
||||
}
|
||||
|
||||
+57
-21
@@ -16,6 +16,7 @@ import org.mockito.Spy;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
@@ -34,6 +35,9 @@ import static org.mockito.Mockito.when;
|
||||
* (submitResult 的 done/error/普通 chunk、failTask、finalizeStaleTasks)
|
||||
* 强制执行一次持久化,最终进度不丢失。persistStats 内容感知:
|
||||
* 序列化结果与既有 result_json 逐字节一致时不重写,重复心跳零 UPDATE。
|
||||
*
|
||||
* 节流计时一律按任务自身(updated_at),不再共享服务上的全局时间戳——全局计时会被并发
|
||||
* 任务互相重置,把内容不变的心跳饿死成永不落库,进而被陈旧巡检误杀(见并发回归用例)。
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class CollectDataProgressThrottleTest {
|
||||
@@ -96,9 +100,8 @@ class CollectDataProgressThrottleTest {
|
||||
assertThat(task.getResultJson()).contains("\"totalRows\":10");
|
||||
assertThat(task.getResultJson()).contains("\"processedRows\":1");
|
||||
|
||||
// 窗口到期后的心跳再次持久化(节流窗口重置)。
|
||||
ReflectionTestUtils.setField(service, "lastProgressFlushMillis",
|
||||
System.currentTimeMillis() - 61_000L);
|
||||
// 窗口到期后的心跳再次持久化(该任务自身计时到期)。
|
||||
task.setUpdatedAt(LocalDateTime.now().minusSeconds(61));
|
||||
TaskHeartbeatRequest third = new TaskHeartbeatRequest();
|
||||
third.setCurrent(2);
|
||||
third.setTotal(10);
|
||||
@@ -109,8 +112,8 @@ class CollectDataProgressThrottleTest {
|
||||
|
||||
@Test
|
||||
void test_task_055_merge_progress_normal_multiple_items() {
|
||||
// 多任务批量:节流窗口全局共享,窗口内多任务多心跳合并为 1 次落库,
|
||||
// 无重复 UPDATE;窗口到期后各任务依次补写最新值,进度不丢失。
|
||||
// 多任务批量:节流窗口**按任务各自计时**——每支任务在自己的窗口内合并写,
|
||||
// 别人刚落库不构成把我合并掉的理由。
|
||||
ReflectionTestUtils.setField(service, "progressThrottleMillis", 60_000L);
|
||||
ReflectionTestUtils.setField(service, "progressDirtyWindowMillis", 60_000L);
|
||||
FileTaskEntity taskA = runningTask(11L);
|
||||
@@ -127,24 +130,55 @@ class CollectDataProgressThrottleTest {
|
||||
heartbeat(service, 11L, 2, 10);
|
||||
heartbeat(service, 12L, 2, 10);
|
||||
|
||||
// 窗口内 4 次 changed 心跳只落库 1 次(首条),其余合并写。
|
||||
verify(fileTaskMapper, times(1)).updateById(any(FileTaskEntity.class));
|
||||
|
||||
// 窗口到期后:A 补写最新值,B 仍被合并。
|
||||
ReflectionTestUtils.setField(service, "lastProgressFlushMillis",
|
||||
System.currentTimeMillis() - 61_000L);
|
||||
heartbeat(service, 11L, 3, 10);
|
||||
// 每支任务首条 changed 心跳各落库 1 次,其后的窗口内心跳合并写 → 共 2 次。
|
||||
verify(fileTaskMapper, times(2)).updateById(any(FileTaskEntity.class));
|
||||
assertThat(taskA.getResultJson()).contains("\"processedRows\":1");
|
||||
assertThat(taskB.getResultJson()).contains("\"processedRows\":1");
|
||||
|
||||
// A 自身窗口到期后补写最新值;B 仍在自己窗口内,继续被合并。
|
||||
taskA.setUpdatedAt(LocalDateTime.now().minusSeconds(61));
|
||||
heartbeat(service, 11L, 3, 10);
|
||||
verify(fileTaskMapper, times(3)).updateById(any(FileTaskEntity.class));
|
||||
assertThat(taskA.getResultJson()).contains("\"processedRows\":3");
|
||||
|
||||
// B 窗口到期后同样补写,两任务最终进度均为最新值。
|
||||
ReflectionTestUtils.setField(service, "lastProgressFlushMillis",
|
||||
System.currentTimeMillis() - 61_000L);
|
||||
// B 自身窗口到期后同样补写,两任务最终进度均为最新值。
|
||||
taskB.setUpdatedAt(LocalDateTime.now().minusSeconds(61));
|
||||
heartbeat(service, 12L, 3, 10);
|
||||
verify(fileTaskMapper, times(3)).updateById(any(FileTaskEntity.class));
|
||||
verify(fileTaskMapper, times(4)).updateById(any(FileTaskEntity.class));
|
||||
assertThat(taskB.getResultJson()).contains("\"processedRows\":3");
|
||||
}
|
||||
|
||||
@Test
|
||||
void test_task_055_并发任务不得饿死单任务的updated_at() {
|
||||
// 回归 task 31253:节流计时曾是单例上的一个全局时间戳,约 20 支采集任务并跑时
|
||||
// 任一任务的落库都会重置它,于是「心跳内容不变」的那支永远落在别人刚刷过的窗口里
|
||||
// 被丢弃,updated_at 停止前进,30 分钟陈旧巡检把还在正常回传分片的活任务判死。
|
||||
// 现在计时取任务自身:只要该任务自己的窗口到期,就必须有人替它把 updated_at 顶上去。
|
||||
ReflectionTestUtils.setField(service, "progressThrottleMillis", 60_000L);
|
||||
ReflectionTestUtils.setField(service, "progressDirtyWindowMillis", 30_000L);
|
||||
FileTaskEntity busy = runningTask(71L); // 一直有新进度的邻居任务
|
||||
FileTaskEntity stuck = runningTask(72L); // 长时间卡在一个关键词、心跳内容不变
|
||||
stuck.setUpdatedAt(LocalDateTime.now().minusMinutes(20));
|
||||
when(fileTaskMapper.selectById(71L)).thenReturn(busy);
|
||||
when(fileTaskMapper.selectById(72L)).thenReturn(stuck);
|
||||
when(taskDistributedLockService.acquire(CollectDataService.MODULE_TYPE, 71L, 5_000L))
|
||||
.thenReturn(lockHandle);
|
||||
when(taskDistributedLockService.acquire(CollectDataService.MODULE_TYPE, 72L, 5_000L))
|
||||
.thenReturn(lockHandle);
|
||||
|
||||
// 邻居任务连续刷了 5 次,把「全局窗口」反复重置——旧实现正是死在这里。
|
||||
for (int i = 1; i <= 5; i++) {
|
||||
busy.setUpdatedAt(LocalDateTime.now().minusSeconds(61)); // 让它每次都够格落库
|
||||
heartbeat(service, 71L, i, 10);
|
||||
}
|
||||
assertThat(busy.getUpdatedAt()).isAfter(LocalDateTime.now().minusSeconds(5));
|
||||
|
||||
// 内容完全相同的重复心跳,仍必须靠自身脏窗口把 updated_at 顶上去。
|
||||
heartbeat(service, 72L, 2, 8);
|
||||
heartbeat(service, 72L, 2, 8);
|
||||
assertThat(stuck.getUpdatedAt()).isAfter(LocalDateTime.now().minusSeconds(5));
|
||||
}
|
||||
|
||||
@Test
|
||||
void test_task_055_merge_progress_normal_repeated_operation_is_idempotent() {
|
||||
// 幂等:内容未变化的重复心跳不触发 UPDATE;节流窗口内合并写后
|
||||
@@ -194,8 +228,7 @@ class CollectDataProgressThrottleTest {
|
||||
verify(fileTaskMapper, times(1)).updateById(any(FileTaskEntity.class));
|
||||
|
||||
// 窗口到期后补写最新值(processedRows=4),不丢失。
|
||||
ReflectionTestUtils.setField(service, "lastProgressFlushMillis",
|
||||
System.currentTimeMillis() - 61_000L);
|
||||
task.setUpdatedAt(LocalDateTime.now().minusSeconds(61));
|
||||
heartbeat(service, 31L, 4, 21);
|
||||
verify(fileTaskMapper, times(2)).updateById(any(FileTaskEntity.class));
|
||||
assertThat(task.getResultJson()).contains("\"processedRows\":4");
|
||||
@@ -219,8 +252,7 @@ class CollectDataProgressThrottleTest {
|
||||
// 窗口内 100 次心跳只落库 1 次,无无界 UPDATE 累积;窗口到期后补写最新值。
|
||||
verify(fileTaskMapper, times(1)).updateById(any(FileTaskEntity.class));
|
||||
assertThat(task.getResultJson()).contains("\"processedRows\":1");
|
||||
ReflectionTestUtils.setField(service, "lastProgressFlushMillis",
|
||||
System.currentTimeMillis() - 61_000L);
|
||||
task.setUpdatedAt(LocalDateTime.now().minusSeconds(61));
|
||||
heartbeat(service, 41L, 100, 100);
|
||||
verify(fileTaskMapper, times(2)).updateById(any(FileTaskEntity.class));
|
||||
assertThat(task.getResultJson()).contains("\"processedRows\":100");
|
||||
@@ -272,7 +304,11 @@ class CollectDataProgressThrottleTest {
|
||||
.hasMessage("db down");
|
||||
verify(lockHandle, times(1)).close();
|
||||
|
||||
// 恢复后心跳重试:窗口未到期,落库一次成功,进度持久化。
|
||||
// 恢复后心跳重试:落库一次成功,进度持久化。
|
||||
// 写失败时库里的 updated_at 并未前进,真实链路每条心跳都在 :479 重新 selectById,
|
||||
// 读到的仍是旧值 ⇒ 会立刻补刷。本用例的 mock 复用同一个实体实例,故先把它退回
|
||||
// 「库里那一版」——否则测的是对象别名,不是这条重读语义。
|
||||
task.setUpdatedAt(null);
|
||||
heartbeat(service, 61L, 2, 10);
|
||||
verify(fileTaskMapper, times(2)).updateById(any(FileTaskEntity.class));
|
||||
assertThat(task.getResultJson()).contains("\"processedRows\":2");
|
||||
|
||||
+328
@@ -0,0 +1,328 @@
|
||||
package com.nanri.aiimage.modules.collectdata.service.support;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.nanri.aiimage.modules.collectdata.mapper.CollectDataCountryPrefMapper;
|
||||
import com.nanri.aiimage.modules.collectdata.mapper.CollectDataItemMapper;
|
||||
import com.nanri.aiimage.modules.collectdata.model.dto.CollectDataParseRequest;
|
||||
import com.nanri.aiimage.modules.collectdata.model.dto.CollectDataSourceFileDto;
|
||||
import com.nanri.aiimage.modules.collectdata.model.entity.CollectDataItemEntity;
|
||||
import com.nanri.aiimage.modules.collectdata.model.vo.CollectDataParseVo;
|
||||
import com.nanri.aiimage.modules.collectdata.service.CollectDataBrandRecheckService;
|
||||
import com.nanri.aiimage.modules.collectdata.service.CollectDataService;
|
||||
import com.nanri.aiimage.modules.collectdata.util.CollectDataBatchQuery;
|
||||
import com.nanri.aiimage.modules.collectdata.util.CollectDataBrandBatchFilter;
|
||||
import com.nanri.aiimage.modules.collectdata.util.CollectDataInvalidAsinBatchWriter;
|
||||
import com.nanri.aiimage.modules.collectdata.util.CollectDataResultDetailCodec;
|
||||
import com.nanri.aiimage.modules.collectdata.util.CollectDataResultDetailReader;
|
||||
import com.nanri.aiimage.modules.collectdata.util.CollectDataResultItemBatchWriter;
|
||||
import com.nanri.aiimage.modules.file.service.LocalFileStorageService;
|
||||
import com.nanri.aiimage.modules.invalidasin.mapper.InvalidAsinDataMapper;
|
||||
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.TaskResultItemMapper;
|
||||
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.service.TaskDistributedLockService;
|
||||
import com.nanri.aiimage.modules.task.service.TaskFileJobService;
|
||||
import com.nanri.aiimage.modules.task.service.TaskProgressLightAssembler;
|
||||
import com.nanri.aiimage.modules.file.service.oss.OssStorageService;
|
||||
import org.apache.poi.ss.usermodel.Row;
|
||||
import org.apache.poi.ss.usermodel.Sheet;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Answers;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyList;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* 集采建单+解析段的现网行为快照(重构蓝图 Phase 0 · 1B,缺快照的四支之四)。
|
||||
*
|
||||
* 快照打的是真 {@link CollectDataService#parseAndCreateTask}:表头别名认列(关键词/状态)、
|
||||
* 无关键词列时「一条都不丢」、关键词为空丢行计数、尾部空列不生成占位列(2026-09-26 生产事故
|
||||
* 那条同源修复)、非 Excel 魔数拒绝、{@code taskType} 缺省回落、{@code PENDING} 建单形状,
|
||||
* 以及逐行 {@code CollectDataItemEntity} 批量落库的 extraJson 形状(Phase 3 迁移后必须仍逐字节相等)。
|
||||
*
|
||||
* 时钟与雪花 taskNo 不进快照;item 主键由 doAnswer 顺序发固定值。
|
||||
*
|
||||
* golden 文件:src/test/resources/collectdata/golden/parse-create-snapshot.txt
|
||||
*/
|
||||
class CollectDataSnapshotTest {
|
||||
|
||||
private static final File GOLDEN_PARSE =
|
||||
new File("src/test/resources/collectdata/golden/parse-create-snapshot.txt");
|
||||
|
||||
// ---- 夹具 ----
|
||||
|
||||
private static File workbook(File dir, String name, List<List<String>> rows) throws Exception {
|
||||
File file = new File(dir, name);
|
||||
try (XSSFWorkbook wb = new XSSFWorkbook(); FileOutputStream out = new FileOutputStream(file)) {
|
||||
Sheet sheet = wb.createSheet("Sheet1");
|
||||
for (int r = 0; r < rows.size(); r++) {
|
||||
Row row = sheet.createRow(r);
|
||||
List<String> cells = rows.get(r);
|
||||
for (int c = 0; c < cells.size(); c++) {
|
||||
row.createCell(c).setCellValue(cells.get(c));
|
||||
}
|
||||
}
|
||||
wb.write(out);
|
||||
}
|
||||
return file;
|
||||
}
|
||||
|
||||
private static File keywordWorkbook(File dir) throws Exception {
|
||||
return workbook(dir, "keyword.xlsx", List.of(
|
||||
List.of("关键词", "asin", "国家", "状态", "价格"),
|
||||
List.of("wirel less 耳机", "B011", "US", "在售", "19.90"),
|
||||
List.of("", "B012", "US", "", "9.90"),
|
||||
List.of("", "", "", "", ""),
|
||||
List.of(" mouse ", "", "DE", "缺少报价", "")));
|
||||
}
|
||||
|
||||
/** 没有关键词列也没有状态列:一条非空行都不该被丢。 */
|
||||
private static File noKeywordHeaderWorkbook(File dir) throws Exception {
|
||||
return workbook(dir, "no-keyword.xlsx", List.of(
|
||||
List.of("asin", "国家", "价格"),
|
||||
List.of("B021", "UK", "5.00"),
|
||||
List.of("B022", "UK", "")));
|
||||
}
|
||||
|
||||
/** 表头整行空白 ⇒「Excel 表头为空」。 */
|
||||
private static File blankHeaderWorkbook(File dir) throws Exception {
|
||||
return workbook(dir, "blank-header.xlsx", List.of(
|
||||
List.of("", "", ""),
|
||||
List.of("B031", "US", "1.00")));
|
||||
}
|
||||
|
||||
/** 关键词列存在但每行关键词都空 ⇒ 有效行 0 ⇒「未解析到有效数据行」。 */
|
||||
private static File allDroppedWorkbook(File dir) throws Exception {
|
||||
return workbook(dir, "all-dropped.xlsx", List.of(
|
||||
List.of("关键词", "asin"),
|
||||
List.of("", "B041"),
|
||||
List.of("", "B042")));
|
||||
}
|
||||
|
||||
private static File notExcel(File dir) throws Exception {
|
||||
File file = new File(dir, "fake.xlsx");
|
||||
Files.writeString(file.toPath(), "关键词,asin\nwireless,B0001\n", StandardCharsets.UTF_8);
|
||||
return file;
|
||||
}
|
||||
|
||||
// ---- 真服务 + 捕获 ----
|
||||
|
||||
private static final class Captured {
|
||||
private final List<FileTaskEntity> taskInserts = new ArrayList<>();
|
||||
private final List<CollectDataItemEntity> items = new ArrayList<>();
|
||||
private final List<FileResultEntity> resultInserts = new ArrayList<>();
|
||||
}
|
||||
|
||||
private static CollectDataService newService(LocalFileStorageService storage, Captured captured) {
|
||||
FileTaskMapper fileTaskMapper = mock(FileTaskMapper.class);
|
||||
FileResultMapper fileResultMapper = mock(FileResultMapper.class);
|
||||
CollectDataItemMapper itemMapper = mock(CollectDataItemMapper.class);
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
doAnswer(invocation -> {
|
||||
FileTaskEntity entity = invocation.getArgument(0);
|
||||
entity.setId(1001L + captured.taskInserts.size());
|
||||
captured.taskInserts.add(entity);
|
||||
return 1;
|
||||
}).when(fileTaskMapper).insert(any(FileTaskEntity.class));
|
||||
doAnswer(invocation -> {
|
||||
List<CollectDataItemEntity> batch = invocation.getArgument(0);
|
||||
for (CollectDataItemEntity entity : batch) {
|
||||
entity.setId(3001L + captured.items.size());
|
||||
captured.items.add(entity);
|
||||
}
|
||||
return batch.size();
|
||||
}).when(itemMapper).insertBatch(anyList());
|
||||
doAnswer(invocation -> {
|
||||
FileResultEntity entity = invocation.getArgument(0);
|
||||
entity.setId(2001L + captured.resultInserts.size());
|
||||
captured.resultInserts.add(entity);
|
||||
return 1;
|
||||
}).when(fileResultMapper).insert(any(FileResultEntity.class));
|
||||
|
||||
return new CollectDataService(storage, fileTaskMapper, fileResultMapper, itemMapper,
|
||||
mock(CollectDataCountryPrefMapper.class), mock(InvalidAsinDataMapper.class),
|
||||
mock(TaskChunkMapper.class), mock(TaskScopeStateMapper.class), mock(TaskResultItemMapper.class),
|
||||
mock(TaskDistributedLockService.class), mock(TaskFileJobService.class),
|
||||
mock(com.nanri.aiimage.modules.task.service.TaskHeartbeatPositionService.class),
|
||||
mock(com.nanri.aiimage.modules.task.service.TransientPayloadStorageService.class),
|
||||
mock(com.nanri.aiimage.modules.collectdata.service.CollectDataExcelAssemblyService.class),
|
||||
mock(OssStorageService.class), objectMapper,
|
||||
new TransactionTemplate(mock(PlatformTransactionManager.class)),
|
||||
mock(com.nanri.aiimage.common.service.DistributedJobLockService.class, Answers.RETURNS_MOCKS),
|
||||
mock(CollectDataBatchQuery.class), mock(CollectDataBrandBatchFilter.class),
|
||||
mock(CollectDataInvalidAsinBatchWriter.class), new CollectDataResultDetailCodec(objectMapper),
|
||||
mock(CollectDataResultItemBatchWriter.class), mock(CollectDataResultDetailReader.class),
|
||||
mock(TaskProgressLightAssembler.class),
|
||||
mock(com.nanri.aiimage.modules.notification.service.NotificationDispatchService.class),
|
||||
mock(com.nanri.aiimage.modules.asincache.service.AsinResultCacheService.class),
|
||||
mock(CollectDataBrandRecheckService.class),
|
||||
mock(com.nanri.aiimage.modules.task.service.StaleTaskHeartbeatPolicy.class));
|
||||
}
|
||||
|
||||
private static CollectDataParseRequest request(List<CollectDataSourceFileDto> files, String taskType) {
|
||||
CollectDataParseRequest request = new CollectDataParseRequest();
|
||||
request.setUserId(7L);
|
||||
request.setFiles(files);
|
||||
request.setTaskType(taskType);
|
||||
return request;
|
||||
}
|
||||
|
||||
private static CollectDataSourceFileDto source(String fileKey, String filename) {
|
||||
CollectDataSourceFileDto dto = new CollectDataSourceFileDto();
|
||||
dto.setFileKey(fileKey);
|
||||
dto.setOriginalFilename(filename);
|
||||
return dto;
|
||||
}
|
||||
|
||||
private static String nullToDash(Object value) {
|
||||
String text = value == null ? "" : String.valueOf(value);
|
||||
return text.isBlank() ? "-" : text;
|
||||
}
|
||||
|
||||
private static String runCase(String caseName, Map<String, File> filesByFileKey, CollectDataParseRequest request) {
|
||||
Captured captured = new Captured();
|
||||
LocalFileStorageService storage = mock(LocalFileStorageService.class);
|
||||
when(storage.findLocalSourceFile(anyString())).thenAnswer(invocation -> filesByFileKey.get(invocation.getArgument(0)));
|
||||
CollectDataService service = newService(storage, captured);
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("== case=").append(caseName).append('\n');
|
||||
try {
|
||||
CollectDataParseVo vo = service.parseAndCreateTask(request, "dev-1");
|
||||
sb.append("vo: taskId=").append(nullToDash(vo.getTaskId()))
|
||||
.append(" sourceFilename=").append(nullToDash(vo.getSourceFilename()))
|
||||
.append(" sourceFileCount=").append(nullToDash(vo.getSourceFileCount()))
|
||||
.append(" totalRows=").append(nullToDash(vo.getTotalRows()))
|
||||
.append(" acceptedRows=").append(nullToDash(vo.getAcceptedRows()))
|
||||
.append(" droppedRows=").append(nullToDash(vo.getDroppedRows()))
|
||||
.append(" pageSize=").append(nullToDash(vo.getPageSize()))
|
||||
.append('\n');
|
||||
} catch (Exception ex) {
|
||||
sb.append("thrown: ").append(ex.getClass().getSimpleName())
|
||||
.append(" message=").append(nullToDash(ex.getMessage())).append('\n');
|
||||
}
|
||||
for (FileTaskEntity task : captured.taskInserts) {
|
||||
sb.append("task.insert: id=").append(task.getId())
|
||||
.append(" moduleType=").append(nullToDash(task.getModuleType()))
|
||||
.append(" taskMode=").append(nullToDash(task.getTaskMode()))
|
||||
.append(" status=").append(nullToDash(task.getStatus()))
|
||||
.append(" sourceFileCount=").append(nullToDash(task.getSourceFileCount()))
|
||||
.append(" deviceId=").append(nullToDash(task.getDeviceId()))
|
||||
.append(" requestJsonTaskTypeDefault=").append(task.getRequestJson() != null
|
||||
&& task.getRequestJson().contains("\"taskType\":\"collect-data\""))
|
||||
.append(" requestJsonTaskTypeExplicit=").append(task.getRequestJson() != null
|
||||
&& task.getRequestJson().contains("\"taskType\":\"collect-data-brand\""))
|
||||
.append(" resultJsonHasFinalRowCount=").append(task.getResultJson() != null
|
||||
&& task.getResultJson().contains("finalRowCount"))
|
||||
.append('\n');
|
||||
}
|
||||
for (CollectDataItemEntity item : captured.items) {
|
||||
sb.append("item: id=").append(item.getId())
|
||||
.append(" taskId=").append(nullToDash(item.getTaskId()))
|
||||
.append(" rowIndex=").append(nullToDash(item.getRowIndex()))
|
||||
.append(" sourceFileKey=").append(nullToDash(item.getSourceFileKey()))
|
||||
.append(" sourceFilename=").append(nullToDash(item.getSourceFilename()))
|
||||
.append(" keyword=").append(nullToDash(item.getKeyword()))
|
||||
.append(" statusValue=").append(nullToDash(item.getStatusValue()))
|
||||
.append(" extraJson=").append(nullToDash(item.getExtraJson()))
|
||||
.append('\n');
|
||||
}
|
||||
for (FileResultEntity result : captured.resultInserts) {
|
||||
sb.append("result.insert: id=").append(result.getId())
|
||||
.append(" taskId=").append(nullToDash(result.getTaskId()))
|
||||
.append(" moduleType=").append(nullToDash(result.getModuleType()))
|
||||
.append(" sourceFilename=").append(nullToDash(result.getSourceFilename()))
|
||||
.append(" sourceFileUrl=").append(nullToDash(result.getSourceFileUrl()))
|
||||
.append(" rowCount=").append(nullToDash(result.getRowCount()))
|
||||
.append('\n');
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public static String runAll() throws Exception {
|
||||
File dir = Files.createTempDirectory("collect-data-snapshot-").toFile();
|
||||
dir.deleteOnExit();
|
||||
File keyword = keywordWorkbook(dir);
|
||||
File noKeyword = noKeywordHeaderWorkbook(dir);
|
||||
File blankHeader = blankHeaderWorkbook(dir);
|
||||
File allDropped = allDroppedWorkbook(dir);
|
||||
File fake = notExcel(dir);
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(runCase("keywordSheet", Map.of("fk-keyword", keyword),
|
||||
request(List.of(source("fk-keyword", "keyword.xlsx")), null)));
|
||||
sb.append(runCase("explicitTaskType", Map.of("fk-keyword", keyword),
|
||||
request(List.of(source("fk-keyword", "keyword.xlsx")), "collect-data-brand")));
|
||||
sb.append(runCase("noKeywordHeader", Map.of("fk-no-keyword", noKeyword),
|
||||
request(List.of(source("fk-no-keyword", "no-keyword.xlsx")), null)));
|
||||
sb.append(runCase("twoFiles", Map.of("fk-keyword", keyword, "fk-no-keyword", noKeyword),
|
||||
request(List.of(source("fk-keyword", "keyword.xlsx"), source("fk-no-keyword", "no-keyword.xlsx")), null)));
|
||||
sb.append(runCase("blankHeader", Map.of("fk-blank", blankHeader),
|
||||
request(List.of(source("fk-blank", "blank-header.xlsx")), null)));
|
||||
sb.append(runCase("allRowsDropped", Map.of("fk-dropped", allDropped),
|
||||
request(List.of(source("fk-dropped", "all-dropped.xlsx")), null)));
|
||||
sb.append(runCase("notExcel", Map.of("fk-fake", fake),
|
||||
request(List.of(source("fk-fake", "fake.xlsx")), null)));
|
||||
sb.append(runCase("missingSourceFile", Map.of(),
|
||||
request(List.of(source("fk-absent", "absent.xlsx")), null)));
|
||||
sb.append(runCase("blankFileKeyFiltered", Map.of("fk-keyword", keyword),
|
||||
request(List.of(source(" ", "blank.xlsx")), null)));
|
||||
sb.append(runCase("emptyFiles", Map.of(), request(List.of(), null)));
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private static String read(File file) throws Exception {
|
||||
return Files.readString(file.toPath(), StandardCharsets.UTF_8).replace("\r\n", "\n");
|
||||
}
|
||||
|
||||
@Test
|
||||
void parse_create_snapshot_matches_golden() throws Exception {
|
||||
assertEquals(read(GOLDEN_PARSE), runAll(), "建单+解析输出快照与 golden 一致");
|
||||
}
|
||||
|
||||
@Test
|
||||
void parse_create_snapshot_is_reproducible() throws Exception {
|
||||
assertEquals(runAll(), runAll(), "同一夹具跑两次结果一致(时钟与雪花 taskNo 不得进快照)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void parse_create_snapshot_golden_is_committed() {
|
||||
assertTrue(GOLDEN_PARSE.isFile(), "golden 文件必须存在并入库: " + GOLDEN_PARSE.getAbsolutePath());
|
||||
assertTrue(GOLDEN_PARSE.length() > 0, "golden 文件非空");
|
||||
}
|
||||
|
||||
@Test
|
||||
void parse_create_snapshot_tamper_is_detected() throws Exception {
|
||||
String original = read(GOLDEN_PARSE);
|
||||
assertTrue(original.contains("== case=keywordSheet"), "golden 内容合法");
|
||||
try {
|
||||
Files.writeString(GOLDEN_PARSE.toPath(), original + "\n# tampered", StandardCharsets.UTF_8);
|
||||
assertTrue(!read(GOLDEN_PARSE).equals(runAll()), "篡改 golden 后断言应失败");
|
||||
} finally {
|
||||
Files.writeString(GOLDEN_PARSE.toPath(), original, StandardCharsets.UTF_8);
|
||||
}
|
||||
assertEquals(original, read(GOLDEN_PARSE), "恢复原始 golden");
|
||||
}
|
||||
}
|
||||
+394
@@ -0,0 +1,394 @@
|
||||
package com.nanri.aiimage.modules.deletebrand.service.support;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.nanri.aiimage.config.DeleteBrandProgressProperties;
|
||||
import com.nanri.aiimage.config.TaskPressureProperties;
|
||||
import com.nanri.aiimage.modules.deletebrand.model.cache.DeleteBrandParsedFileCacheDto;
|
||||
import com.nanri.aiimage.modules.deletebrand.model.dto.DeleteBrandRunRequest;
|
||||
import com.nanri.aiimage.modules.deletebrand.model.dto.DeleteBrandSourceFileDto;
|
||||
import com.nanri.aiimage.modules.deletebrand.model.vo.DeleteBrandCountryAsinVo;
|
||||
import com.nanri.aiimage.modules.deletebrand.model.vo.DeleteBrandCountryGroupVo;
|
||||
import com.nanri.aiimage.modules.deletebrand.model.vo.DeleteBrandPreviewRowVo;
|
||||
import com.nanri.aiimage.modules.deletebrand.model.vo.DeleteBrandResultItemVo;
|
||||
import com.nanri.aiimage.modules.deletebrand.model.vo.DeleteBrandRunVo;
|
||||
import com.nanri.aiimage.modules.deletebrand.service.DeleteBrandRunService;
|
||||
import com.nanri.aiimage.modules.deletebrand.service.DeleteBrandTaskCacheService;
|
||||
import com.nanri.aiimage.modules.deletebrand.service.DeleteBrandTaskStorageService;
|
||||
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;
|
||||
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.service.TaskDistributedLockService;
|
||||
import com.nanri.aiimage.modules.task.service.TaskFileJobService;
|
||||
import com.nanri.aiimage.modules.task.service.TaskProgressLightAssembler;
|
||||
import com.nanri.aiimage.modules.ziniao.model.vo.ZiniaoShopMatchResultVo;
|
||||
import com.nanri.aiimage.modules.ziniao.service.ZiniaoShopSwitchService;
|
||||
import org.apache.poi.ss.usermodel.Row;
|
||||
import org.apache.poi.ss.usermodel.Sheet;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* 删除品牌建单+解析段的现网行为快照(重构蓝图 Phase 0 · 1B,缺快照的四支之一)。
|
||||
*
|
||||
* 与 {@code AppearancePatentSnapshotTest} 那套约定的区别,也是这一支的价值所在:
|
||||
* 快照打的是**真服务**({@link DeleteBrandRunService#run} 一路走到私有内联上下文
|
||||
* {@code DeleteBrandSheetContext}),不是在测试里照抄一遍管线——Phase 3 要动的正是这条链,
|
||||
* 测试里重写的管线会跟着旧代码一起留在原地,对迁移毫无保护。
|
||||
* 落库侧用 Mockito 捕获 {@code fileTaskMapper}/{@code fileResultMapper} 的 insert/update 入参,
|
||||
* 回传载荷侧捕获 {@code saveParsedPayload} 的 map(Phase 3 迁移后必须逐字节仍相等)。
|
||||
*
|
||||
* 时钟/雪花 id 不进快照:taskNo、createdAt/updatedAt/finishedAt 与 requestJson/resultJson 一律不渲染,
|
||||
* 主键由 doAnswer 按调用顺序发固定值(1001/2001…),所以整串输出可复现。
|
||||
*
|
||||
* golden 文件:src/test/resources/deletebrand/golden/run-snapshot.txt
|
||||
*/
|
||||
class DeleteBrandSnapshotTest {
|
||||
|
||||
private static final File GOLDEN_RUN =
|
||||
new File("src/test/resources/deletebrand/golden/run-snapshot.txt");
|
||||
|
||||
// ---- 夹具 ----
|
||||
|
||||
/** 两行表头(国家标题行 + 字段行)+ 数据行;BOM/全角空格/大小写/去重都在这支里吃到。 */
|
||||
private static File fixtureMain() throws Exception {
|
||||
return workbook(List.of(
|
||||
List.of("美国", "", "德国", ""),
|
||||
List.of("删除ASIN", "状态", "删除ASIN", "状态"),
|
||||
List.of("b011 1", "在售", "B021", ""),
|
||||
List.of("B011 1", "已删除", "", "状态值不该单独成行"),
|
||||
List.of("B012", "", "B022", "在售"),
|
||||
List.of("", "", "", "")));
|
||||
}
|
||||
|
||||
/** 只有一行表头(没有字段行)⇒ 与旧实现一致的「Excel 表头不完整」。 */
|
||||
private static File fixtureHeaderOnly() throws Exception {
|
||||
return workbook(List.of(List.of("美国", "状态")));
|
||||
}
|
||||
|
||||
/**
|
||||
* 「店铺名」列被标题字面排除、其余列走 dataStartRowIndex=1 那条分支:
|
||||
* 表头行自身会被当数据行吃进去(ASIN="ASIN"、状态="状态")——今天真实存在的行为,
|
||||
* Phase 3 把解析段抽走时这条必须仍然相等,所以进快照而不是修掉。
|
||||
*/
|
||||
private static File fixtureSingleHeaderRowShape() throws Exception {
|
||||
return workbook(List.of(
|
||||
List.of("店铺名", "英国", ""),
|
||||
List.of("负责人", "ASIN", "状态"),
|
||||
List.of("张三", "B031", "在售"),
|
||||
List.of("李四", "B032", "缺少报价")));
|
||||
}
|
||||
|
||||
/** 后缀是 xlsx、内容却是 CSV 文本 ⇒ 魔数拦下,不许被 EasyExcel 静默当 CSV 解析成功。 */
|
||||
private static File fixtureNotExcel() throws Exception {
|
||||
File file = File.createTempFile("delete-brand-snapshot-not-excel-", ".xlsx");
|
||||
Files.writeString(file.toPath(), "国家,ASIN\nUS,B0001\n", StandardCharsets.UTF_8);
|
||||
return file;
|
||||
}
|
||||
|
||||
private static File workbook(List<List<String>> rows) throws Exception {
|
||||
File file = File.createTempFile("delete-brand-snapshot-", ".xlsx");
|
||||
try (XSSFWorkbook wb = new XSSFWorkbook(); FileOutputStream out = new FileOutputStream(file)) {
|
||||
Sheet sheet = wb.createSheet("Sheet1");
|
||||
for (int r = 0; r < rows.size(); r++) {
|
||||
Row row = sheet.createRow(r);
|
||||
for (int c = 0; c < rows.get(r).size(); c++) {
|
||||
row.createCell(c).setCellValue(rows.get(r).get(c));
|
||||
}
|
||||
}
|
||||
wb.write(out);
|
||||
}
|
||||
return file;
|
||||
}
|
||||
|
||||
// ---- 真服务 + 捕获 ----
|
||||
|
||||
private static final class Captured {
|
||||
private final List<FileTaskEntity> taskInserts = new ArrayList<>();
|
||||
private final List<FileTaskEntity> taskUpdates = new ArrayList<>();
|
||||
private final List<FileResultEntity> resultInserts = new ArrayList<>();
|
||||
private final Map<String, DeleteBrandParsedFileCacheDto> payload = new LinkedHashMap<>();
|
||||
}
|
||||
|
||||
/** 每个夹具一个「店铺名→紫鸟匹配结果」开关:未匹配的店铺解析成功但不进待跑清单。 */
|
||||
private static DeleteBrandRunService newService(Map<String, File> filesByFileKey,
|
||||
Captured captured,
|
||||
List<String> matchedShops) {
|
||||
FileTaskMapper fileTaskMapper = mock(FileTaskMapper.class);
|
||||
FileResultMapper fileResultMapper = mock(FileResultMapper.class);
|
||||
LocalFileStorageService storage = mock(LocalFileStorageService.class);
|
||||
DeleteBrandTaskCacheService cacheService = mock(DeleteBrandTaskCacheService.class);
|
||||
DeleteBrandTaskStorageService taskStorage = mock(DeleteBrandTaskStorageService.class);
|
||||
ZiniaoShopSwitchService ziniao = mock(ZiniaoShopSwitchService.class);
|
||||
OssStorageService oss = mock(OssStorageService.class);
|
||||
// ObjectMapper 用真身:mock 它会让 toCompactTaskResultJsonForDb 静默失败(clone is null),
|
||||
// 快照就锁在了「resultJson 组装失败也能建单」这个假形状上。
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
DeleteBrandProgressProperties progressProperties = mock(DeleteBrandProgressProperties.class);
|
||||
TaskPressureProperties pressureProperties = mock(TaskPressureProperties.class);
|
||||
TaskDistributedLockService lockService = mock(TaskDistributedLockService.class);
|
||||
TaskFileJobService taskFileJobService = mock(TaskFileJobService.class);
|
||||
PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class);
|
||||
TaskProgressLightAssembler progressLightAssembler = mock(TaskProgressLightAssembler.class);
|
||||
|
||||
doAnswer(invocation -> {
|
||||
FileTaskEntity entity = invocation.getArgument(0);
|
||||
entity.setId(1001L + captured.taskInserts.size());
|
||||
captured.taskInserts.add(entity);
|
||||
return 1;
|
||||
}).when(fileTaskMapper).insert(any(FileTaskEntity.class));
|
||||
doAnswer(invocation -> {
|
||||
captured.taskUpdates.add(invocation.getArgument(0));
|
||||
return 1;
|
||||
}).when(fileTaskMapper).updateById(any(FileTaskEntity.class));
|
||||
doAnswer(invocation -> {
|
||||
FileResultEntity entity = invocation.getArgument(0);
|
||||
entity.setId(2001L + captured.resultInserts.size());
|
||||
captured.resultInserts.add(entity);
|
||||
return 1;
|
||||
}).when(fileResultMapper).insert(any(FileResultEntity.class));
|
||||
when(storage.findLocalSourceFile(anyString()))
|
||||
.thenAnswer(invocation -> filesByFileKey.get(invocation.getArgument(0)));
|
||||
// 注意别写 `String.valueOf(invocation.getArgument(0))`:泛型 T 会推断成 char[],
|
||||
// 编译期挑中 valueOf(char[]) 重载,运行时 String 强转 [C 直接抛 ClassCastException。
|
||||
when(ziniao.normalizeShopName(any())).thenAnswer(invocation -> {
|
||||
String shopName = invocation.getArgument(0);
|
||||
return shopName == null ? "" : shopName;
|
||||
});
|
||||
when(ziniao.findIndexedStoreByName(anyString(), anyBoolean())).thenAnswer(invocation -> {
|
||||
String shopName = invocation.getArgument(0);
|
||||
ZiniaoShopMatchResultVo result = new ZiniaoShopMatchResultVo();
|
||||
if (!matchedShops.contains(shopName)) {
|
||||
result.setMatched(false);
|
||||
result.setMatchStatus("NOT_FOUND");
|
||||
result.setMatchMessage("店铺未匹配");
|
||||
return result;
|
||||
}
|
||||
result.setMatched(true);
|
||||
result.setMatchStatus("MATCHED");
|
||||
result.setShopId("shop-" + shopName);
|
||||
result.setCompanyName("公司-" + shopName);
|
||||
result.setPlatform("amazon");
|
||||
result.setOpenStoreUrl("https://example.invalid/" + shopName);
|
||||
return result;
|
||||
});
|
||||
doAnswer(invocation -> {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, DeleteBrandParsedFileCacheDto> payload = invocation.getArgument(1);
|
||||
captured.payload.putAll(payload);
|
||||
return null;
|
||||
}).when(taskStorage).saveParsedPayload(any(), any());
|
||||
|
||||
return new DeleteBrandRunService(fileTaskMapper, fileResultMapper, storage, cacheService,
|
||||
taskStorage, ziniao, oss, objectMapper, progressProperties, pressureProperties,
|
||||
lockService, taskFileJobService, transactionManager, progressLightAssembler);
|
||||
}
|
||||
|
||||
private static DeleteBrandRunRequest request(List<String> fileKeys) {
|
||||
DeleteBrandRunRequest request = new DeleteBrandRunRequest();
|
||||
request.setUserId(7L);
|
||||
List<DeleteBrandSourceFileDto> files = new ArrayList<>();
|
||||
for (String fileKey : fileKeys) {
|
||||
DeleteBrandSourceFileDto sourceFile = new DeleteBrandSourceFileDto();
|
||||
sourceFile.setFileKey(fileKey);
|
||||
sourceFile.setOriginalFilename(fileKey.substring(fileKey.lastIndexOf('/') + 1));
|
||||
files.add(sourceFile);
|
||||
}
|
||||
request.setFiles(files);
|
||||
return request;
|
||||
}
|
||||
|
||||
// ---- 快照渲染 ----
|
||||
|
||||
private static String nullToDash(Object value) {
|
||||
String text = value == null ? "" : String.valueOf(value);
|
||||
return text.isBlank() ? "-" : text;
|
||||
}
|
||||
|
||||
private static String runCase(String caseName, Map<String, File> filesByFileKey,
|
||||
List<String> fileKeys, List<String> matchedShops) {
|
||||
Captured captured = new Captured();
|
||||
DeleteBrandRunService service = newService(filesByFileKey, captured, matchedShops);
|
||||
DeleteBrandRunVo vo = service.run(request(fileKeys), "dev-1");
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("== case=").append(caseName).append(" files=").append(fileKeys.size()).append('\n');
|
||||
for (FileTaskEntity task : captured.taskInserts) {
|
||||
sb.append("task.insert: id=").append(task.getId())
|
||||
.append(" moduleType=").append(nullToDash(task.getModuleType()))
|
||||
.append(" status=").append(nullToDash(task.getStatus()))
|
||||
.append(" taskMode=").append(nullToDash(task.getTaskMode()))
|
||||
.append(" userId=").append(nullToDash(task.getUserId()))
|
||||
.append(" createdBy=").append(nullToDash(task.getCreatedBy()))
|
||||
.append(" deviceId=").append(nullToDash(task.getDeviceId()))
|
||||
.append(" sourceFileCount=").append(nullToDash(task.getSourceFileCount()))
|
||||
.append('\n');
|
||||
}
|
||||
for (FileTaskEntity task : captured.taskUpdates) {
|
||||
sb.append("task.update: id=").append(task.getId())
|
||||
.append(" status=").append(nullToDash(task.getStatus()))
|
||||
.append(" sourceFileCount=").append(nullToDash(task.getSourceFileCount()))
|
||||
.append(" successFileCount=").append(nullToDash(task.getSuccessFileCount()))
|
||||
.append(" failedFileCount=").append(nullToDash(task.getFailedFileCount()))
|
||||
.append(" errorMessage=").append(nullToDash(task.getErrorMessage()))
|
||||
.append('\n');
|
||||
}
|
||||
for (FileResultEntity result : captured.resultInserts) {
|
||||
sb.append("result.insert: id=").append(result.getId())
|
||||
.append(" taskId=").append(nullToDash(result.getTaskId()))
|
||||
.append(" moduleType=").append(nullToDash(result.getModuleType()))
|
||||
.append(" sourceFileUrl=").append(nullToDash(result.getSourceFileUrl()))
|
||||
.append(" rowCount=").append(nullToDash(result.getRowCount()))
|
||||
.append(" success=").append(nullToDash(result.getSuccess()))
|
||||
.append(" resultFilename=").append(nullToDash(result.getResultFilename()))
|
||||
.append(" errorMessage=").append(nullToDash(result.getErrorMessage()))
|
||||
.append('\n');
|
||||
}
|
||||
sb.append("vo: total=").append(vo.getTotal())
|
||||
.append(" successCount=").append(vo.getSuccessCount())
|
||||
.append(" failedCount=").append(vo.getFailedCount()).append('\n');
|
||||
for (DeleteBrandResultItemVo item : vo.getItems()) {
|
||||
sb.append("item: resultId=").append(nullToDash(item.getResultId()))
|
||||
.append(" fileKey=").append(nullToDash(item.getFileKey()))
|
||||
.append(" shopName=").append(nullToDash(item.getShopName()))
|
||||
.append(" matched=").append(item.isMatched())
|
||||
.append(" matchStatus=").append(nullToDash(item.getMatchStatus()))
|
||||
.append(" countryCount=").append(nullToDash(item.getCountryCount()))
|
||||
.append(" totalRows=").append(nullToDash(item.getTotalRows()))
|
||||
.append(" truncated=").append(item.isTruncated())
|
||||
.append(" success=").append(item.isSuccess())
|
||||
.append(" error=").append(nullToDash(item.getError()))
|
||||
.append(" taskStatus=").append(nullToDash(item.getTaskStatus()))
|
||||
.append('\n');
|
||||
renderCountries(sb, " parsed ", item.getCountries());
|
||||
for (DeleteBrandPreviewRowVo preview : item.getPreviewRows()) {
|
||||
sb.append(" preview: row=").append(preview.getRowIndex())
|
||||
.append(" country=").append(nullToDash(preview.getCountry()))
|
||||
.append(" asin=").append(nullToDash(preview.getAsin()))
|
||||
.append(" status=").append(nullToDash(preview.getStatus()))
|
||||
.append('\n');
|
||||
}
|
||||
}
|
||||
sb.append("payload.files=").append(captured.payload.size()).append('\n');
|
||||
for (DeleteBrandParsedFileCacheDto dto : captured.payload.values()) {
|
||||
sb.append(" payload: fileKey=").append(nullToDash(dto.getFileKey()))
|
||||
.append(" shopId=").append(nullToDash(dto.getShopId()))
|
||||
.append(" companyName=").append(nullToDash(dto.getCompanyName()))
|
||||
.append(" platform=").append(nullToDash(dto.getPlatform()))
|
||||
.append(" totalRows=").append(nullToDash(dto.getTotalRows()))
|
||||
.append('\n');
|
||||
renderCountries(sb, " ", dto.getCountries());
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private static void renderCountries(StringBuilder sb, String indent, List<DeleteBrandCountryGroupVo> countries) {
|
||||
for (DeleteBrandCountryGroupVo country : countries) {
|
||||
sb.append(indent).append("country=").append(nullToDash(country.getCountry()))
|
||||
.append(" asinCount=").append(nullToDash(country.getAsinCount())).append('\n');
|
||||
for (DeleteBrandCountryAsinVo asin : country.getItems()) {
|
||||
sb.append(indent).append(" asin: row=").append(asin.getRowIndex())
|
||||
.append(" value=").append(nullToDash(asin.getAsin()))
|
||||
.append(" status=").append(nullToDash(asin.getStatus()))
|
||||
.append('\n');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static String runAll() {
|
||||
Map<String, File> main = Map.of("uploads/魏振峰.xlsx", fixtureMainOrNull());
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(runCase("main", main, List.of("uploads/魏振峰.xlsx"), List.of("魏振峰")));
|
||||
sb.append(runCase("unmatched", single("uploads/魏振峰.xlsx"), List.of("uploads/魏振峰.xlsx"), List.of()));
|
||||
sb.append(runCase("headerOnly", single("uploads/缺字段行.xlsx"), List.of("uploads/缺字段行.xlsx"), List.of("缺字段行")));
|
||||
sb.append(runCase("shopNameColumnSkipped", single("uploads/英国.xlsx"), List.of("uploads/英国.xlsx"), List.of("英国")));
|
||||
sb.append(runCase("notExcel", single("uploads/伪装.csv.xlsx"), List.of("uploads/伪装.csv.xlsx"), List.of("伪装")));
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private static File fixtureMainOrNull() {
|
||||
try {
|
||||
return fixtureMain();
|
||||
} catch (Exception ex) {
|
||||
throw new IllegalStateException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
private static Map<String, File> single(String fileKey) {
|
||||
try {
|
||||
File file = switch (fileKey) {
|
||||
case "uploads/缺字段行.xlsx" -> fixtureHeaderOnly();
|
||||
case "uploads/英国.xlsx" -> fixtureSingleHeaderRowShape();
|
||||
case "uploads/伪装.csv.xlsx" -> fixtureNotExcel();
|
||||
default -> fixtureMain();
|
||||
};
|
||||
return Map.of(fileKey, file);
|
||||
} catch (Exception ex) {
|
||||
throw new IllegalStateException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
private static String read(File file) throws Exception {
|
||||
return Files.readString(file.toPath(), StandardCharsets.UTF_8).replace("\r\n", "\n");
|
||||
}
|
||||
|
||||
// ---- 用例 ----
|
||||
|
||||
@Test
|
||||
void run_snapshot_matches_golden() throws Exception {
|
||||
assertEquals(read(GOLDEN_RUN), runAll(), "建单+解析输出快照与 golden 一致");
|
||||
}
|
||||
|
||||
@Test
|
||||
void run_snapshot_is_reproducible() {
|
||||
assertEquals(runAll(), runAll(), "同一夹具跑两次结果一致(时钟与雪花 id 不得进快照)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void run_snapshot_golden_is_committed() {
|
||||
assertTrue(GOLDEN_RUN.isFile(), "golden 文件必须存在并入库: " + GOLDEN_RUN.getAbsolutePath());
|
||||
assertTrue(GOLDEN_RUN.length() > 0, "golden 文件非空");
|
||||
}
|
||||
|
||||
@Test
|
||||
void run_snapshot_tamper_is_detected() throws Exception {
|
||||
String original = read(GOLDEN_RUN);
|
||||
assertTrue(original.contains("== case=main"), "golden 内容合法");
|
||||
try {
|
||||
Files.writeString(GOLDEN_RUN.toPath(), original + "\n# tampered", StandardCharsets.UTF_8);
|
||||
assertTrue(assertDoesNotEqualGolden(), "篡改 golden 后断言应失败");
|
||||
} finally {
|
||||
Files.writeString(GOLDEN_RUN.toPath(), original, StandardCharsets.UTF_8);
|
||||
}
|
||||
assertEquals(original, read(GOLDEN_RUN), "恢复原始 golden");
|
||||
}
|
||||
|
||||
private static boolean assertDoesNotEqualGolden() {
|
||||
try {
|
||||
return !read(GOLDEN_RUN).equals(runAll());
|
||||
} catch (Exception ex) {
|
||||
throw new IllegalStateException(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
+362
@@ -0,0 +1,362 @@
|
||||
package com.nanri.aiimage.modules.pricetrack.service.support;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.nanri.aiimage.common.service.ResultDownloadResolver;
|
||||
import com.nanri.aiimage.config.TaskPressureProperties;
|
||||
import com.nanri.aiimage.modules.file.service.LocalFileStorageService;
|
||||
import com.nanri.aiimage.modules.file.service.oss.OssStorageService;
|
||||
import com.nanri.aiimage.modules.pricetrack.mapper.PriceTrackShopCandidateMapper;
|
||||
import com.nanri.aiimage.modules.pricetrack.model.dto.PriceTrackCreateTaskRequest;
|
||||
import com.nanri.aiimage.modules.pricetrack.model.vo.PriceTrackCreateTaskVo;
|
||||
import com.nanri.aiimage.modules.pricetrack.model.vo.PriceTrackMatchShopsVo;
|
||||
import com.nanri.aiimage.modules.pricetrack.model.vo.PriceTrackResultItemVo;
|
||||
import com.nanri.aiimage.modules.pricetrack.service.PriceTrackExcelAssemblyService;
|
||||
import com.nanri.aiimage.modules.pricetrack.service.PriceTrackLoopRunService;
|
||||
import com.nanri.aiimage.modules.pricetrack.service.PriceTrackTaskCacheService;
|
||||
import com.nanri.aiimage.modules.pricetrack.service.PriceTrackTaskService;
|
||||
import com.nanri.aiimage.modules.shopkey.service.SkipPriceAsinService;
|
||||
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.service.TaskDistributedLockService;
|
||||
import com.nanri.aiimage.modules.task.service.TaskFileJobService;
|
||||
import com.nanri.aiimage.modules.task.service.TaskProgressLightAssembler;
|
||||
import com.nanri.aiimage.modules.task.service.TaskResultPayloadService;
|
||||
import com.nanri.aiimage.modules.ziniao.service.ZiniaoShopSwitchService;
|
||||
import org.apache.poi.ss.usermodel.Row;
|
||||
import org.apache.poi.ss.usermodel.Sheet;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* 跟价建单+ASIN 文件解析段的现网行为快照(重构蓝图 Phase 0 · 1B,缺快照的四支之三)。
|
||||
*
|
||||
* 快照打的是真 {@link PriceTrackTaskService#createTask}:模式二选一校验、按归一化店名去重、
|
||||
* 未匹配店铺在建单前就拒、ASIN 文件路径的三种形态与「必须落在上传临时目录内」的穿越校验、
|
||||
* 表头别名映射(商品ASIN/价格/最低价 → asin/price/minimumPrice)、按 sheet 名认国家、
|
||||
* 单国家时的 sheet 名兜底、空 ASIN 行丢弃、BOM 与全角空格归一化,以及解析结果落到
|
||||
* {@code TaskResultPayloadService.saveLatest} 的载荷形状——parse 与 report 两段同时钉住。
|
||||
* 心跳也在本支钉住:建单即 {@code touchTaskHeartbeat}(蓝图 §1A 那一格,本支从建单侧取证)。
|
||||
*
|
||||
* 时钟与临时目录绝对路径不进快照(后者统一擦成 {@code <root>}),否则逐字节对撞无从谈起。
|
||||
*
|
||||
* golden 文件:src/test/resources/pricetrack/golden/create-task-snapshot.txt
|
||||
*/
|
||||
class PriceTrackSnapshotTest {
|
||||
|
||||
private static final File GOLDEN_CREATE =
|
||||
new File("src/test/resources/pricetrack/golden/create-task-snapshot.txt");
|
||||
|
||||
// ---- 夹具 ----
|
||||
|
||||
private record SheetCells(String name, List<List<String>> rows) {
|
||||
}
|
||||
|
||||
private static File workbook(File root, String name, List<SheetCells> sheets) throws Exception {
|
||||
File file = new File(root, name);
|
||||
try (XSSFWorkbook wb = new XSSFWorkbook(); FileOutputStream out = new FileOutputStream(file)) {
|
||||
for (SheetCells sheet : sheets) {
|
||||
Sheet created = wb.createSheet(sheet.name());
|
||||
for (int r = 0; r < sheet.rows().size(); r++) {
|
||||
Row row = created.createRow(r);
|
||||
List<String> cells = sheet.rows().get(r);
|
||||
for (int c = 0; c < cells.size(); c++) {
|
||||
row.createCell(c).setCellValue(cells.get(c));
|
||||
}
|
||||
}
|
||||
}
|
||||
wb.write(out);
|
||||
}
|
||||
return file;
|
||||
}
|
||||
|
||||
/** 英国 sheet 用「商品ASIN/价格/最低价/备注」四列别名,德国 sheet 用最小两列;含空 ASIN 行与 BOM/全角 ASIN。 */
|
||||
private static File asinWorkbookTwoSheets(File root) throws Exception {
|
||||
return workbook(root, "asin.xlsx", List.of(
|
||||
new SheetCells("英国", List.of(
|
||||
List.of("商品ASIN", "价格", "最低价", "备注"),
|
||||
List.of("B011", "19.90", "18.00", "note"),
|
||||
List.of("", "9.90", "", ""),
|
||||
List.of("b012 ", "20.00", "", ""))),
|
||||
new SheetCells("德国", List.of(
|
||||
List.of("ASIN", "价格"),
|
||||
List.of("B021", "5.00")))));
|
||||
}
|
||||
|
||||
/** sheet 名不在国家词表里(葡萄牙)——国家归属只能靠 countryCodes 兜底。 */
|
||||
private static File unknownSheetWorkbook(File root) throws Exception {
|
||||
return workbook(root, "unknown-sheet.xlsx", List.of(
|
||||
new SheetCells("葡萄牙", List.of(
|
||||
List.of("ASIN", "价格"),
|
||||
List.of("B099", "1.00")))));
|
||||
}
|
||||
|
||||
// ---- 真服务 + 捕获 ----
|
||||
|
||||
private static final class Captured {
|
||||
private final List<FileTaskEntity> taskInserts = new ArrayList<>();
|
||||
private final List<FileTaskEntity> taskUpdates = new ArrayList<>();
|
||||
private final List<FileResultEntity> resultInserts = new ArrayList<>();
|
||||
private final List<Map<String, List<Map<String, String>>>> payloads = new ArrayList<>();
|
||||
private int heartbeats;
|
||||
}
|
||||
|
||||
private static PriceTrackTaskService newService(Captured captured, File root) {
|
||||
FileTaskMapper fileTaskMapper = mock(FileTaskMapper.class);
|
||||
FileResultMapper fileResultMapper = mock(FileResultMapper.class);
|
||||
ZiniaoShopSwitchService ziniao = mock(ZiniaoShopSwitchService.class);
|
||||
PriceTrackTaskCacheService cacheService = mock(PriceTrackTaskCacheService.class);
|
||||
LocalFileStorageService storage = mock(LocalFileStorageService.class);
|
||||
TaskResultPayloadService payloadService = mock(TaskResultPayloadService.class);
|
||||
|
||||
doAnswer(invocation -> {
|
||||
FileTaskEntity entity = invocation.getArgument(0);
|
||||
entity.setId(1001L + captured.taskInserts.size());
|
||||
captured.taskInserts.add(entity);
|
||||
return 1;
|
||||
}).when(fileTaskMapper).insert(any(FileTaskEntity.class));
|
||||
doAnswer(invocation -> {
|
||||
captured.taskUpdates.add(invocation.getArgument(0));
|
||||
return 1;
|
||||
}).when(fileTaskMapper).updateById(any(FileTaskEntity.class));
|
||||
doAnswer(invocation -> {
|
||||
FileResultEntity entity = invocation.getArgument(0);
|
||||
entity.setId(2001L + captured.resultInserts.size());
|
||||
captured.resultInserts.add(entity);
|
||||
return 1;
|
||||
}).when(fileResultMapper).insert(any(FileResultEntity.class));
|
||||
// 去重键是「归一化后的店名」,这里给一条去首尾空白的最小归一化(紫鸟归一化本身归它自己的套件)
|
||||
when(ziniao.normalizeShopName(any())).thenAnswer(invocation -> {
|
||||
String shopName = invocation.getArgument(0);
|
||||
return shopName == null ? "" : shopName.trim();
|
||||
});
|
||||
when(storage.localTempRoot()).thenReturn(root);
|
||||
doAnswer(invocation -> {
|
||||
captured.heartbeats++;
|
||||
return null;
|
||||
}).when(cacheService).touchTaskHeartbeat(any());
|
||||
doAnswer(invocation -> {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, List<Map<String, String>>> rows = invocation.getArgument(3);
|
||||
captured.payloads.add(rows);
|
||||
return null;
|
||||
}).when(payloadService).saveLatest(any(), anyString(), anyString(), any());
|
||||
|
||||
return new PriceTrackTaskService(fileTaskMapper, fileResultMapper,
|
||||
mock(PriceTrackShopCandidateMapper.class), ziniao, mock(OssStorageService.class),
|
||||
mock(ResultDownloadResolver.class), new ObjectMapper(), mock(SkipPriceAsinService.class),
|
||||
mock(PriceTrackExcelAssemblyService.class), cacheService, mock(PriceTrackLoopRunService.class),
|
||||
mock(TaskPressureProperties.class), payloadService, mock(TaskFileJobService.class),
|
||||
mock(TaskDistributedLockService.class), mock(TaskProgressLightAssembler.class),
|
||||
storage, mock(PlatformTransactionManager.class));
|
||||
}
|
||||
|
||||
private static PriceTrackMatchShopsVo.PriceTrackShopQueueItem shop(String shopName, Boolean matched) {
|
||||
PriceTrackMatchShopsVo.PriceTrackShopQueueItem item = new PriceTrackMatchShopsVo.PriceTrackShopQueueItem();
|
||||
item.setShopName(shopName);
|
||||
item.setMatched(matched);
|
||||
item.setShopId(Boolean.TRUE.equals(matched) ? "shop-" + shopName : null);
|
||||
item.setPlatform("amazon");
|
||||
item.setCompanyName("公司-" + shopName);
|
||||
item.setMatchStatus(Boolean.TRUE.equals(matched) ? "MATCHED" : "NOT_FOUND");
|
||||
return item;
|
||||
}
|
||||
|
||||
private static PriceTrackCreateTaskRequest request(List<PriceTrackMatchShopsVo.PriceTrackShopQueueItem> items,
|
||||
boolean statusMode,
|
||||
boolean asinMode,
|
||||
List<String> asinFiles,
|
||||
List<String> countryCodes) {
|
||||
PriceTrackCreateTaskRequest request = new PriceTrackCreateTaskRequest();
|
||||
request.setUserId(7L);
|
||||
request.setItems(items);
|
||||
request.setStatusMode(statusMode);
|
||||
request.setAsinMode(asinMode);
|
||||
request.setAsinFiles(asinFiles);
|
||||
request.setCountryCodes(countryCodes);
|
||||
request.setListingStatuses(List.of("在售", "缺少报价"));
|
||||
return request;
|
||||
}
|
||||
|
||||
private static String nullToDash(Object value) {
|
||||
String text = value == null ? "" : String.valueOf(value);
|
||||
return text.isBlank() ? "-" : text;
|
||||
}
|
||||
|
||||
private static String runCase(String caseName, PriceTrackCreateTaskRequest request, File root, File outsideRoot) {
|
||||
Captured captured = new Captured();
|
||||
PriceTrackTaskService service = newService(captured, root);
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("== case=").append(caseName).append('\n');
|
||||
try {
|
||||
PriceTrackCreateTaskVo vo = service.createTask(request, "dev-1");
|
||||
sb.append("vo: taskId=").append(nullToDash(vo.getTaskId()))
|
||||
.append(" items=").append(vo.getItems().size()).append('\n');
|
||||
for (PriceTrackResultItemVo item : vo.getItems()) {
|
||||
sb.append(" item: resultId=").append(nullToDash(item.getResultId()))
|
||||
.append(" shopName=").append(nullToDash(item.getShopName()))
|
||||
.append(" matched=").append(nullToDash(item.getMatched()))
|
||||
.append(" taskStatus=").append(nullToDash(item.getTaskStatus()))
|
||||
.append(" success=").append(nullToDash(item.getSuccess()))
|
||||
.append('\n');
|
||||
}
|
||||
// 载荷在 parse 段就落库了;VO 上那三个 map 今天恒空(注释掉的那几行),钉住「别再往回加」
|
||||
sb.append("vo: asinRowsByCountry=").append(vo.getAsinRowsByCountry().size())
|
||||
.append(" skipAsinsByCountry=").append(vo.getSkipAsinsByCountry().size())
|
||||
.append(" minimumPriceByCountry=").append(vo.getMinimumPriceByCountryAndAsin().size())
|
||||
.append('\n');
|
||||
} catch (Exception ex) {
|
||||
sb.append("thrown: ").append(ex.getClass().getSimpleName())
|
||||
.append(" message=").append(nullToDash(ex.getMessage())).append('\n');
|
||||
}
|
||||
for (FileTaskEntity task : captured.taskInserts) {
|
||||
sb.append("task.insert: id=").append(task.getId())
|
||||
.append(" moduleType=").append(nullToDash(task.getModuleType()))
|
||||
.append(" taskMode=").append(nullToDash(task.getTaskMode()))
|
||||
.append(" status=").append(nullToDash(task.getStatus()))
|
||||
.append(" sourceFileCount=").append(nullToDash(task.getSourceFileCount()))
|
||||
.append('\n');
|
||||
}
|
||||
for (FileTaskEntity task : captured.taskUpdates) {
|
||||
sb.append("task.update: id=").append(task.getId())
|
||||
.append(" status=").append(nullToDash(task.getStatus()))
|
||||
.append(" requestJsonHasAsinFiles=").append(task.getRequestJson() != null
|
||||
&& task.getRequestJson().contains("asinFiles"))
|
||||
.append(" requestJsonHasListingStatuses=").append(task.getRequestJson() != null
|
||||
&& task.getRequestJson().contains("listingStatuses"))
|
||||
.append(" resultJsonItems=").append(task.getResultJson() == null ? -1
|
||||
: count(task.getResultJson(), "\"resultId\""))
|
||||
.append('\n');
|
||||
}
|
||||
for (FileResultEntity result : captured.resultInserts) {
|
||||
sb.append("result.insert: id=").append(result.getId())
|
||||
.append(" moduleType=").append(nullToDash(result.getModuleType()))
|
||||
.append(" sourceFilename=").append(nullToDash(result.getSourceFilename()))
|
||||
.append(" sourceFileUrl=").append(nullToDash(result.getSourceFileUrl()))
|
||||
.append(" success=").append(nullToDash(result.getSuccess()))
|
||||
.append('\n');
|
||||
}
|
||||
sb.append("payloadSaves=").append(captured.payloads.size()).append('\n');
|
||||
for (Map<String, List<Map<String, String>>> payload : captured.payloads) {
|
||||
for (Map.Entry<String, List<Map<String, String>>> entry : payload.entrySet()) {
|
||||
sb.append(" payload country=").append(entry.getKey())
|
||||
.append(" rows=").append(entry.getValue().size()).append('\n');
|
||||
for (Map<String, String> row : entry.getValue()) {
|
||||
sb.append(" row:");
|
||||
for (Map.Entry<String, String> cell : row.entrySet()) {
|
||||
sb.append(' ').append(cell.getKey()).append('=').append(nullToDash(cell.getValue()));
|
||||
}
|
||||
sb.append('\n');
|
||||
}
|
||||
}
|
||||
}
|
||||
sb.append("heartbeatTouches=").append(captured.heartbeats).append('\n');
|
||||
return scrub(scrub(sb.toString(), root, "<root>"), outsideRoot, "<outside>");
|
||||
}
|
||||
|
||||
private static int count(String text, String needle) {
|
||||
int occurrences = 0;
|
||||
int index = text.indexOf(needle);
|
||||
while (index >= 0) {
|
||||
occurrences++;
|
||||
index = text.indexOf(needle, index + needle.length());
|
||||
}
|
||||
return occurrences;
|
||||
}
|
||||
|
||||
/** 临时目录绝对路径每次跑都不一样(拒收文案里也带原路径),统一擦成固定记号才谈得上逐字节对撞。 */
|
||||
private static String scrub(String text, File dir, String token) {
|
||||
return text.replace(dir.getAbsolutePath(), token);
|
||||
}
|
||||
|
||||
public static String runAll() throws Exception {
|
||||
File root = Files.createTempDirectory("price-track-snapshot-root-").toFile();
|
||||
root.deleteOnExit();
|
||||
File outsideRoot = Files.createTempDirectory("price-track-snapshot-outside-").toFile();
|
||||
outsideRoot.deleteOnExit();
|
||||
asinWorkbookTwoSheets(root);
|
||||
unknownSheetWorkbook(root);
|
||||
File outside = new File(outsideRoot, "outside.xlsx");
|
||||
try (FileOutputStream ignored = new FileOutputStream(outside)) {
|
||||
ignored.write("PK\u0003\u0004-not-inside-temp-root".getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
List<PriceTrackMatchShopsVo.PriceTrackShopQueueItem> twoShops =
|
||||
List.of(shop("店铺A", true), shop(" 店铺A ", true), shop("店铺B", true));
|
||||
List<PriceTrackMatchShopsVo.PriceTrackShopQueueItem> oneShop = List.of(shop("店铺A", true));
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(runCase("asinModeTwoSheets",
|
||||
request(twoShops, false, true, List.of("asin.xlsx"), List.of("UK", "DE")), root, outsideRoot));
|
||||
sb.append(runCase("singleSheetFallback",
|
||||
request(oneShop, false, true, List.of("unknown-sheet.xlsx"), List.of("FR")), root, outsideRoot));
|
||||
sb.append(runCase("unknownSheetWithoutFallback",
|
||||
request(oneShop, false, true, List.of("unknown-sheet.xlsx"), List.of("UK", "DE")), root, outsideRoot));
|
||||
sb.append(runCase("multipleFilesSameCountryMerged",
|
||||
request(oneShop, false, true, List.of("asin.xlsx", "unknown-sheet.xlsx"), List.of("FR")), root, outsideRoot));
|
||||
sb.append(runCase("fileOutsideTempRootRejected",
|
||||
request(oneShop, false, true, List.of(outside.getAbsolutePath()), List.of("UK")), root, outsideRoot));
|
||||
sb.append(runCase("missingFile",
|
||||
request(oneShop, false, true, List.of("不存在的.xlsx"), List.of("UK")), root, outsideRoot));
|
||||
sb.append(runCase("blankPathSkipped",
|
||||
request(oneShop, false, true, List.of("", "asin.xlsx"), List.of("FR")), root, outsideRoot));
|
||||
sb.append(runCase("statusMode", request(oneShop, true, false, List.of(), List.of("UK")), root, outsideRoot));
|
||||
sb.append(runCase("bothModes",
|
||||
request(oneShop, true, true, List.of("asin.xlsx"), List.of("UK")), root, outsideRoot));
|
||||
sb.append(runCase("neitherMode", request(oneShop, false, false, List.of(), List.of("UK")), root, outsideRoot));
|
||||
sb.append(runCase("asinModeWithoutFiles", request(oneShop, false, true, List.of(), List.of("UK")), root, outsideRoot));
|
||||
sb.append(runCase("unmatchedShop", request(List.of(shop("店铺C", false)), true, false, List.of(), List.of("UK")), root, outsideRoot));
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private static String read(File file) throws Exception {
|
||||
return Files.readString(file.toPath(), StandardCharsets.UTF_8).replace("\r\n", "\n");
|
||||
}
|
||||
|
||||
@Test
|
||||
void create_task_snapshot_matches_golden() throws Exception {
|
||||
assertEquals(read(GOLDEN_CREATE), runAll(), "建单+ASIN 解析输出快照与 golden 一致");
|
||||
}
|
||||
|
||||
@Test
|
||||
void create_task_snapshot_is_reproducible() throws Exception {
|
||||
assertEquals(runAll(), runAll(), "同一夹具跑两次结果一致(时钟与临时目录路径不得进快照)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void create_task_snapshot_golden_is_committed() {
|
||||
assertTrue(GOLDEN_CREATE.isFile(), "golden 文件必须存在并入库: " + GOLDEN_CREATE.getAbsolutePath());
|
||||
assertTrue(GOLDEN_CREATE.length() > 0, "golden 文件非空");
|
||||
}
|
||||
|
||||
@Test
|
||||
void create_task_snapshot_tamper_is_detected() throws Exception {
|
||||
String original = read(GOLDEN_CREATE);
|
||||
assertTrue(original.contains("== case=asinModeTwoSheets"), "golden 内容合法");
|
||||
try {
|
||||
Files.writeString(GOLDEN_CREATE.toPath(), original + "\n# tampered", StandardCharsets.UTF_8);
|
||||
assertTrue(!read(GOLDEN_CREATE).equals(runAll()), "篡改 golden 后断言应失败");
|
||||
} finally {
|
||||
Files.writeString(GOLDEN_CREATE.toPath(), original, StandardCharsets.UTF_8);
|
||||
}
|
||||
assertEquals(original, read(GOLDEN_CREATE), "恢复原始 golden");
|
||||
}
|
||||
}
|
||||
+503
@@ -0,0 +1,503 @@
|
||||
package com.nanri.aiimage.modules.pricetrack.service.support;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.service.ResultDownloadResolver;
|
||||
import com.nanri.aiimage.config.TaskPressureProperties;
|
||||
import com.nanri.aiimage.modules.file.service.LocalFileStorageService;
|
||||
import com.nanri.aiimage.modules.file.service.oss.OssStorageService;
|
||||
import com.nanri.aiimage.modules.pricetrack.mapper.PriceTrackShopCandidateMapper;
|
||||
import com.nanri.aiimage.modules.pricetrack.model.dto.PriceTrackSubmitResultRequest;
|
||||
import com.nanri.aiimage.modules.pricetrack.service.PriceTrackExcelAssemblyService;
|
||||
import com.nanri.aiimage.modules.pricetrack.service.PriceTrackLoopRunService;
|
||||
import com.nanri.aiimage.modules.pricetrack.service.PriceTrackTaskCacheService;
|
||||
import com.nanri.aiimage.modules.pricetrack.service.PriceTrackTaskService;
|
||||
import com.nanri.aiimage.modules.shopkey.service.SkipPriceAsinService;
|
||||
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.service.TaskDistributedLockService;
|
||||
import com.nanri.aiimage.modules.task.service.TaskFileJobService;
|
||||
import com.nanri.aiimage.modules.task.service.TaskProgressLightAssembler;
|
||||
import com.nanri.aiimage.modules.task.service.TaskResultPayloadService;
|
||||
import com.nanri.aiimage.modules.ziniao.service.ZiniaoShopSwitchService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
|
||||
import java.io.File;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* 跟价回传落库(段 3)+出结果排队(段 4 入口)的现网行为快照——Phase 3 首迁的护身符(孪生支之二)。
|
||||
*
|
||||
* <p>补这一支的理由与 {@code ShopMatchSubmitResultSnapshotTest} 同:蓝图 §5 写明「{@code submitResult}
|
||||
* 未打快照,Phase 3 要动那一段先补再动」,而 {@code AbstractShopPayloadTaskPipeline} 的模板
|
||||
* 恰好就是这两支的 {@code submitResult} 形状。两支**刻意不是同一份夹具**——
|
||||
* 下面这几处差异正是本支存在的理由,也是迁移时最容易被「顺手统一」掉的东西:
|
||||
* <ul>
|
||||
* <li><b>闸门不同</b>:本支看 {@code merged.getSuccess()==TRUE}(与行数是两回事),
|
||||
* 所以「回传说完成了但一行可用 ASIN 都没有」在本支可达、在 ShopMatch 不可达;</li>
|
||||
* <li><b>失败判定在前</b>:{@code error} 与 {@code success==FALSE} 两道都在合并之前判,
|
||||
* ShopMatch 是先合并再判 {@code error};</li>
|
||||
* <li><b>任务收尾多做两件事</b>:{@code sourceFileCount} 被重算成行数(ShopMatch 不写这列)、
|
||||
* 终态后额外 {@code syncLoopRunAfterChildTerminal}(循环跟价子任务要回写父轮次);</li>
|
||||
* <li><b>错误分隔符是半角 {@code "; "},ShopMatch 是全角「;」</b>——现网两种都有,不许归一;</li>
|
||||
* <li><b>排队前先算服务端改价次数</b>({@code applyServerModifyCounts}):基线读
|
||||
* {@code price-track-asin-rows} 载荷,本夹具里读不到 ⇒ 一律从 0 起算,
|
||||
* 所以 {@code 改价成功} 那行的 modifyCount 必须是 1(ShopMatch 没有这一段)。</li>
|
||||
* </ul>
|
||||
*
|
||||
* golden:src/test/resources/pricetrack/golden/submit-result-snapshot.txt
|
||||
* 重新生成:{@code SHUFU_SNAPSHOT_WRITE=true mvn -o test -Dtest=PriceTrackSubmitResultSnapshotTest}
|
||||
*/
|
||||
class PriceTrackSubmitResultSnapshotTest {
|
||||
|
||||
private static final File GOLDEN_SUBMIT =
|
||||
new File("src/test/resources/pricetrack/golden/submit-result-snapshot.txt");
|
||||
private static final long TASK_ID = 1001L;
|
||||
|
||||
private static final class Fixture {
|
||||
private final List<String> events = new ArrayList<>();
|
||||
private final Map<String, PriceTrackSubmitResultRequest.ShopResult> mergedPayloads = new LinkedHashMap<>();
|
||||
private final FileTaskEntity task = new FileTaskEntity();
|
||||
private final List<FileResultEntity> rows = new ArrayList<>();
|
||||
private PriceTrackTaskService service;
|
||||
private int heartbeats;
|
||||
private int lockCloses;
|
||||
|
||||
private Fixture withRows(String... shopNames) {
|
||||
long id = 2001L;
|
||||
for (String shopName : shopNames) {
|
||||
FileResultEntity row = new FileResultEntity();
|
||||
row.setId(id++);
|
||||
row.setTaskId(TASK_ID);
|
||||
row.setModuleType("PRICE_TRACK");
|
||||
row.setSourceFilename(shopName);
|
||||
row.setSourceFileUrl("shop-" + shopName);
|
||||
row.setUserId(7L);
|
||||
row.setSuccess(0);
|
||||
rows.add(row);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
private Fixture withTask(String status, String moduleType) {
|
||||
task.setId(TASK_ID);
|
||||
task.setUserId(7L);
|
||||
task.setModuleType(moduleType);
|
||||
task.setStatus(status);
|
||||
// 本支的 loadTaskForExecution 要求缓存行 requestJson 非空才认这条缓存(蓝图 §1A 点名的非同构变体)
|
||||
task.setRequestJson("{}");
|
||||
return this;
|
||||
}
|
||||
|
||||
private PriceTrackTaskService service() {
|
||||
if (service != null) {
|
||||
return service;
|
||||
}
|
||||
FileTaskMapper fileTaskMapper = mock(FileTaskMapper.class);
|
||||
FileResultMapper fileResultMapper = mock(FileResultMapper.class);
|
||||
PriceTrackTaskCacheService cacheService = mock(PriceTrackTaskCacheService.class);
|
||||
ZiniaoShopSwitchService ziniao = mock(ZiniaoShopSwitchService.class);
|
||||
PriceTrackExcelAssemblyService assembly = mock(PriceTrackExcelAssemblyService.class);
|
||||
TaskResultPayloadService payloadService = mock(TaskResultPayloadService.class);
|
||||
TaskFileJobService fileJobService = mock(TaskFileJobService.class);
|
||||
TaskDistributedLockService lockService = mock(TaskDistributedLockService.class);
|
||||
PriceTrackLoopRunService loopRunService = mock(PriceTrackLoopRunService.class);
|
||||
TaskDistributedLockService.LockHandle lock = mock(TaskDistributedLockService.LockHandle.class);
|
||||
|
||||
when(fileResultMapper.selectList(any())).thenAnswer(invocation -> List.copyOf(rows));
|
||||
doAnswer(invocation -> {
|
||||
events.add("result.update: " + renderRow(invocation.getArgument(0)));
|
||||
return 1;
|
||||
}).when(fileResultMapper).updateById(any(FileResultEntity.class));
|
||||
doAnswer(invocation -> {
|
||||
events.add("task.update: " + renderTask(invocation.getArgument(0)));
|
||||
return 1;
|
||||
}).when(fileTaskMapper).updateById(any(FileTaskEntity.class));
|
||||
|
||||
when(lockService.acquire(anyString(), anyLong())).thenReturn(lock);
|
||||
doAnswer(invocation -> {
|
||||
lockCloses++;
|
||||
return null;
|
||||
}).when(lock).close();
|
||||
|
||||
when(cacheService.getTaskCacheBatch(any())).thenAnswer(invocation -> Map.of(TASK_ID, task));
|
||||
doAnswer(invocation -> {
|
||||
heartbeats++;
|
||||
return null;
|
||||
}).when(cacheService).touchTaskHeartbeat(any());
|
||||
when(cacheService.getShopMergedPayload(anyLong(), anyString()))
|
||||
.thenAnswer(invocation -> mergedPayloads.get(invocation.<String>getArgument(1)));
|
||||
doAnswer(invocation -> {
|
||||
String shopKey = invocation.getArgument(1);
|
||||
PriceTrackSubmitResultRequest.ShopResult payload = invocation.getArgument(2);
|
||||
mergedPayloads.put(shopKey, payload);
|
||||
events.add("mergedSave: taskId=" + invocation.<Long>getArgument(0)
|
||||
+ " shopKey=" + shopKey + " " + renderPayload(payload));
|
||||
return null;
|
||||
}).when(cacheService).saveShopMergedPayload(anyLong(), anyString(), any());
|
||||
doAnswer(invocation -> {
|
||||
events.add("mergedRemove: taskId=" + invocation.getArgument(0)
|
||||
+ " shopKey=" + invocation.getArgument(1));
|
||||
mergedPayloads.remove(invocation.<String>getArgument(1));
|
||||
return null;
|
||||
}).when(cacheService).removeShopMergedPayload(anyLong(), anyString());
|
||||
doAnswer(invocation -> {
|
||||
events.add("taskCacheDelete: taskId=" + invocation.getArgument(0));
|
||||
return null;
|
||||
}).when(cacheService).deleteTaskCache(any());
|
||||
|
||||
doAnswer(invocation -> {
|
||||
events.add("payloadSave: taskId=" + invocation.getArgument(0)
|
||||
+ " moduleType=" + invocation.getArgument(1)
|
||||
+ " scopeKey=" + invocation.getArgument(2)
|
||||
+ " " + renderPayload(invocation.getArgument(3)));
|
||||
return null;
|
||||
}).when(payloadService).saveLatest(anyLong(), anyString(), anyString(), any());
|
||||
// 原 ASIN 载荷读不到 ⇒ 改价次数基线一律 0(本支另一条同名用例钉的就是这条回落)
|
||||
when(payloadService.getLatest(anyLong(), anyString(), anyString(), any())).thenReturn(null);
|
||||
when(fileJobService.findAssembleJobsByResultIds(anyString(), any())).thenReturn(Map.of());
|
||||
when(fileJobService.findAssembleJob(any(), anyString(), any())).thenReturn(null);
|
||||
doAnswer(invocation -> {
|
||||
events.add("enqueue: taskId=" + invocation.getArgument(0)
|
||||
+ " moduleType=" + invocation.getArgument(1)
|
||||
+ " resultId=" + invocation.getArgument(2)
|
||||
+ " scopeKey=" + invocation.getArgument(3));
|
||||
return null;
|
||||
}).when(fileJobService).enqueueAssembleResult(anyLong(), anyString(), anyLong(), anyString());
|
||||
doAnswer(invocation -> {
|
||||
events.add("loopRunSync: taskId=" + invocation.getArgument(0));
|
||||
return null;
|
||||
}).when(loopRunService).syncLoopRunAfterChildTerminal(anyLong());
|
||||
|
||||
when(ziniao.normalizeShopName(any())).thenAnswer(invocation -> {
|
||||
String shopName = invocation.<String>getArgument(0);
|
||||
return shopName == null ? "" : shopName.trim();
|
||||
});
|
||||
when(assembly.normalizeCountriesMap(any())).thenAnswer(invocation -> invocation.getArgument(0));
|
||||
when(assembly.countRows(any())).thenAnswer(invocation -> {
|
||||
Map<String, List<PriceTrackSubmitResultRequest.AsinResult>> countries = invocation.getArgument(0);
|
||||
int count = 0;
|
||||
if (countries != null) {
|
||||
for (List<PriceTrackSubmitResultRequest.AsinResult> list : countries.values()) {
|
||||
count += list == null ? 0 : list.size();
|
||||
}
|
||||
}
|
||||
return count;
|
||||
});
|
||||
|
||||
service = new PriceTrackTaskService(fileTaskMapper, fileResultMapper,
|
||||
mock(PriceTrackShopCandidateMapper.class), ziniao, mock(OssStorageService.class),
|
||||
mock(ResultDownloadResolver.class), new ObjectMapper(), mock(SkipPriceAsinService.class),
|
||||
assembly, cacheService, loopRunService, mock(TaskPressureProperties.class),
|
||||
payloadService, fileJobService, lockService, mock(TaskProgressLightAssembler.class),
|
||||
mock(LocalFileStorageService.class), mock(PlatformTransactionManager.class));
|
||||
return service;
|
||||
}
|
||||
}
|
||||
|
||||
private static String renderRow(FileResultEntity row) {
|
||||
return "id=" + row.getId()
|
||||
+ " success=" + row.getSuccess()
|
||||
+ " error=" + dash(row.getErrorMessage())
|
||||
+ " filename=" + dash(row.getResultFilename())
|
||||
+ " urlPresent=" + (row.getResultFileUrl() != null && !row.getResultFileUrl().isBlank())
|
||||
+ " size=" + row.getResultFileSize()
|
||||
+ " contentType=" + dash(row.getResultContentType())
|
||||
+ " rowCount=" + row.getRowCount();
|
||||
}
|
||||
|
||||
private static String renderTask(FileTaskEntity task) {
|
||||
return "id=" + task.getId()
|
||||
+ " status=" + dash(task.getStatus())
|
||||
+ " ok=" + task.getSuccessFileCount()
|
||||
+ " fail=" + task.getFailedFileCount()
|
||||
+ " sourceFileCount=" + task.getSourceFileCount()
|
||||
+ " error=" + dash(task.getErrorMessage())
|
||||
+ " resultJsonItems=" + (task.getResultJson() == null ? -1
|
||||
: count(task.getResultJson(), "\"resultId\""))
|
||||
+ " finishedPresent=" + (task.getFinishedAt() != null);
|
||||
}
|
||||
|
||||
private static String renderPayload(Object payload) {
|
||||
if (!(payload instanceof PriceTrackSubmitResultRequest.ShopResult result)) {
|
||||
return "payload=" + (payload == null ? "<null>" : "<" + payload.getClass().getSimpleName() + ">");
|
||||
}
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("shopName=").append(dash(result.getShopName()))
|
||||
.append(" error=").append(dash(result.getError()))
|
||||
.append(" success=").append(dash(result.getSuccess()));
|
||||
Map<String, List<PriceTrackSubmitResultRequest.AsinResult>> countries = result.getCountries();
|
||||
sb.append(" countries=").append(countries == null ? 0 : countries.size());
|
||||
int rows = 0;
|
||||
if (countries != null) {
|
||||
for (Map.Entry<String, List<PriceTrackSubmitResultRequest.AsinResult>> entry : countries.entrySet()) {
|
||||
List<PriceTrackSubmitResultRequest.AsinResult> list = entry.getValue();
|
||||
rows += list == null ? 0 : list.size();
|
||||
if (list == null) {
|
||||
continue;
|
||||
}
|
||||
for (PriceTrackSubmitResultRequest.AsinResult row : list) {
|
||||
sb.append("\n row: country=").append(entry.getKey())
|
||||
.append(" asin=").append(dash(row == null ? null : row.getAsin()))
|
||||
.append(" price=").append(dash(row == null ? null : row.getPrice()))
|
||||
.append(" changeStatus=").append(dash(row == null ? null : row.getPriceChangeStatus()))
|
||||
.append(" modifyCount=").append(dash(row == null ? null : row.getModifyCount()));
|
||||
}
|
||||
}
|
||||
}
|
||||
return sb.append(" rows=").append(rows).toString();
|
||||
}
|
||||
|
||||
private static String dash(Object value) {
|
||||
String text = value == null ? "" : String.valueOf(value);
|
||||
return text.isBlank() ? "-" : text;
|
||||
}
|
||||
|
||||
private static int count(String text, String needle) {
|
||||
int occurrences = 0;
|
||||
int index = text.indexOf(needle);
|
||||
while (index >= 0) {
|
||||
occurrences++;
|
||||
index = text.indexOf(needle, index + needle.length());
|
||||
}
|
||||
return occurrences;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// 请求构造
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
private static PriceTrackSubmitResultRequest.AsinResult asinRow(String asin, String price, String changeStatus) {
|
||||
PriceTrackSubmitResultRequest.AsinResult row = new PriceTrackSubmitResultRequest.AsinResult();
|
||||
row.setShopMallName("店铺商城名");
|
||||
row.setAsin(asin);
|
||||
row.setPrice(price);
|
||||
row.setStatus("在售");
|
||||
row.setPriceChangeStatus(changeStatus);
|
||||
return row;
|
||||
}
|
||||
|
||||
private static PriceTrackSubmitResultRequest.ShopResult shop(String shopName, String error, Boolean success,
|
||||
String country,
|
||||
PriceTrackSubmitResultRequest.AsinResult... rows) {
|
||||
PriceTrackSubmitResultRequest.ShopResult result = new PriceTrackSubmitResultRequest.ShopResult();
|
||||
result.setShopName(shopName);
|
||||
result.setError(error);
|
||||
result.setSuccess(success);
|
||||
Map<String, List<PriceTrackSubmitResultRequest.AsinResult>> countries = new LinkedHashMap<>();
|
||||
if (country != null) {
|
||||
countries.put(country, List.of(rows));
|
||||
}
|
||||
result.setCountries(countries);
|
||||
return result;
|
||||
}
|
||||
|
||||
private static PriceTrackSubmitResultRequest request(PriceTrackSubmitResultRequest.ShopResult... shops) {
|
||||
PriceTrackSubmitResultRequest request = new PriceTrackSubmitResultRequest();
|
||||
request.setShops(List.of(shops));
|
||||
return request;
|
||||
}
|
||||
|
||||
private interface Emit {
|
||||
String render() throws Exception;
|
||||
}
|
||||
|
||||
private static void appendCase(StringBuilder sb, String caseName, Emit emit) {
|
||||
sb.append("== case=").append(caseName).append('\n');
|
||||
try {
|
||||
sb.append(emit.render());
|
||||
} catch (Exception ex) {
|
||||
sb.append("thrown: ").append(ex.getClass().getSimpleName())
|
||||
.append(" code=").append(ex instanceof BusinessException businessException
|
||||
? dash(businessException.getCode()) : "-")
|
||||
.append(" message=").append(dash(ex.getMessage())).append('\n');
|
||||
}
|
||||
}
|
||||
|
||||
private static String counters(Fixture fixture) {
|
||||
return "events=" + fixture.events.size()
|
||||
+ " heartbeatTouches=" + fixture.heartbeats
|
||||
+ " lockCloses=" + fixture.lockCloses + '\n';
|
||||
}
|
||||
|
||||
private static String submit(Fixture fixture, PriceTrackSubmitResultRequest request) {
|
||||
fixture.service().submitResult(TASK_ID, request);
|
||||
StringBuilder sb = new StringBuilder();
|
||||
fixture.events.forEach(line -> sb.append(line).append('\n'));
|
||||
return sb.append(counters(fixture)).toString();
|
||||
}
|
||||
|
||||
private static Fixture runningFixture() {
|
||||
Fixture fixture = new Fixture();
|
||||
fixture.withRows("店铺A", "店铺B").withTask("RUNNING", "PRICE_TRACK");
|
||||
return fixture;
|
||||
}
|
||||
|
||||
public static String runAll() throws Exception {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
// 1. 单店跑完:合并→改价次数→载荷落库→行标「文件名已定、文件待组装」→Job 排队→清理合并载荷
|
||||
// 任务表留在 RUNNING(Job 未落地不许提前终态);改价成功那行 modifyCount 从 0 基线抬到 1
|
||||
Fixture happy = runningFixture();
|
||||
appendCase(sb, "happyShop", () -> submit(happy, request(
|
||||
shop("店铺A", null, true, "UK", asinRow("B001", "19.90", "改价成功")))));
|
||||
|
||||
// 2. 回传的店铺不在任务行里 ⇒ changed=false ⇒ 任务表一次都不许写
|
||||
Fixture unknown = runningFixture();
|
||||
appendCase(sb, "unknownShopWritesNothing", () -> submit(unknown, request(
|
||||
shop("店铺Z", null, true, "UK", asinRow("B009", "1.00", null)))));
|
||||
|
||||
// 3. success=false(没有 error)⇒ 走失败收尾,但已有行仍产出部分结果(error 文案是硬编码 "shop processing failed")
|
||||
Fixture softFail = runningFixture();
|
||||
appendCase(sb, "successFalseWithRowsProducesPartial", () -> submit(softFail, request(
|
||||
shop("店铺A", null, false, "UK", asinRow("B001", "19.90", null)))));
|
||||
|
||||
// 4. error 非空 ⇒ 第一道闸门就拦下(合并仍发生在前,因为 finalizeFailedShop 里还要 merge 一次)
|
||||
Fixture errored = runningFixture();
|
||||
appendCase(sb, "errorWithRows", () -> submit(errored, request(
|
||||
shop("店铺A", "店铺登录失败", true, "UK", asinRow("B001", "19.90", null)))));
|
||||
|
||||
// 5. error 且一行都没有 ⇒ 只标失败、不排队(文件名必须清空)
|
||||
Fixture erroredEmpty = runningFixture();
|
||||
appendCase(sb, "errorWithoutRows", () -> submit(erroredEmpty, request(
|
||||
shop("店铺A", "店铺登录失败", true, null))));
|
||||
|
||||
// 6. success=true 但 ASIN 全空 ⇒ 本支可达(闸门只看 success,不看行数)⇒ 落「未收到有效跟价数据」
|
||||
Fixture noUsable = runningFixture();
|
||||
appendCase(sb, "completedWithoutUsableRows", () -> submit(noUsable, request(
|
||||
shop("店铺A", null, true, "DE", asinRow("", "1.00", null)))));
|
||||
|
||||
// 7. error 是纯空白:第一道判据不认(isBlank),落到无可用行那条文案
|
||||
// ——钉住「buildNoUsableRowsMessage 里读 payload.error 的那一支在现网拿不到非空白 error」
|
||||
Fixture blankError = runningFixture();
|
||||
appendCase(sb, "blankErrorFallsBackToNoUsableRowsMessage", () -> submit(blankError, request(
|
||||
shop("店铺A", " ", true, "DE", asinRow("", "1.00", null)))));
|
||||
|
||||
// 8. 有行但 success 缺失 ⇒ 等更多分片:只有 mergedSave,没有排队、没有清理
|
||||
Fixture waiting = runningFixture();
|
||||
appendCase(sb, "chunkWithoutSuccessWaits", () -> submit(waiting, request(
|
||||
shop("店铺A", null, null, "UK", asinRow("B001", "19.90", null)))));
|
||||
|
||||
// 9. 同一店铺分两片:第一片没 success、第二片带同一 ASIN 的价格并 success=true
|
||||
// 合并必须读缓存里那份(第二片不许把第一片的行丢掉),改价次数在排队前按合并后的行重算
|
||||
Fixture chunked = runningFixture();
|
||||
chunked.service().submitResult(TASK_ID, request(
|
||||
shop("店铺A", null, null, "UK", asinRow("B001", null, null))));
|
||||
chunked.events.clear();
|
||||
appendCase(sb, "chunkedMergeAcrossTwoSubmissions", () -> submit(chunked, request(
|
||||
shop("店铺A", null, true, "UK", asinRow("B001", "19.90", "UPDATED")))));
|
||||
|
||||
// 10. 删除跳过 ASIN 的信号只是日志(今天不回传任何写副作用),不得改变本行结局
|
||||
Fixture signal = runningFixture();
|
||||
PriceTrackSubmitResultRequest.AsinResult deleteSignal = asinRow("B002", "8.00", null);
|
||||
deleteSignal.setDeleteSkipAsin(true);
|
||||
deleteSignal.setRemoveAsin("B002");
|
||||
deleteSignal.setDeleteReason("已下架");
|
||||
appendCase(sb, "skipAsinDeleteSignalChangesNothing", () -> submit(signal, request(
|
||||
shop("店铺A", null, true, "UK", deleteSignal))));
|
||||
|
||||
// 11. 两店都 success=false 且无行 ⇒ 每行都有交代 ⇒ FAILED(半角 "; " 连接)
|
||||
// + sourceFileCount 被重算 + 缓存清理 + 循环轮次同步(ShopMatch 没有最后这一件)
|
||||
Fixture bothFailed = runningFixture();
|
||||
appendCase(sb, "allShopsFailedFinalizesTask", () -> submit(bothFailed, request(
|
||||
shop("店铺A", null, false, null),
|
||||
shop("店铺B", null, false, null))));
|
||||
|
||||
// 12. 任务已终态 ⇒ 40901(幂等忽略并停止重试)
|
||||
Fixture terminal = new Fixture();
|
||||
terminal.withRows("店铺A").withTask("SUCCESS", "PRICE_TRACK");
|
||||
appendCase(sb, "terminalTaskRejectedWith40901", () -> submit(terminal, request(
|
||||
shop("店铺A", null, true, "UK", asinRow("B001", "1.00", null)))));
|
||||
|
||||
// 13. 缓存里的行属于别的模块 ⇒ 「任务不存在」(不带 code)
|
||||
Fixture wrongModule = new Fixture();
|
||||
wrongModule.withRows("店铺A").withTask("RUNNING", "SHOP_DATA_CRAWL");
|
||||
appendCase(sb, "wrongModuleTaskNotFound", () -> submit(wrongModule, request(
|
||||
shop("店铺A", null, true, "UK", asinRow("B001", "1.00", null)))));
|
||||
|
||||
// 14. taskId 非法 ⇒ 抢锁之前就拒:锁一次都不该被碰
|
||||
Fixture badId = runningFixture();
|
||||
badId.service();
|
||||
appendCase(sb, "invalidTaskIdRejectedBeforeLock", () -> {
|
||||
StringBuilder inner = new StringBuilder();
|
||||
try {
|
||||
badId.service.submitResult(0L, request(shop("店铺A", null, true, "UK",
|
||||
asinRow("B001", "1.00", null))));
|
||||
inner.append("thrown: none\n");
|
||||
} catch (Exception ex) {
|
||||
inner.append("thrown: ").append(ex.getClass().getSimpleName())
|
||||
.append(" code=").append(ex instanceof BusinessException businessException
|
||||
? dash(businessException.getCode()) : "-")
|
||||
.append(" message=").append(dash(ex.getMessage())).append('\n');
|
||||
}
|
||||
return inner.append(counters(badId)).toString();
|
||||
});
|
||||
|
||||
// 15. shops 为空 / 整个请求为 null ⇒ 同一句「shops 不能为空」,且都在抢锁之前
|
||||
Fixture emptyShops = runningFixture();
|
||||
appendCase(sb, "emptyShops", () -> submit(emptyShops, request()));
|
||||
Fixture nullRequest = runningFixture();
|
||||
appendCase(sb, "nullRequest", () -> submit(nullRequest, null));
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private static String read(File file) throws Exception {
|
||||
return Files.readString(file.toPath(), StandardCharsets.UTF_8).replace("\r\n", "\n");
|
||||
}
|
||||
|
||||
@Test
|
||||
void submit_result_snapshot_matches_golden() throws Exception {
|
||||
assertEquals(read(GOLDEN_SUBMIT), runAll(), "回传段落库流水与 golden 一致");
|
||||
}
|
||||
|
||||
@Test
|
||||
void submit_result_snapshot_is_reproducible() throws Exception {
|
||||
assertEquals(runAll(), runAll(), "同一夹具跑两次流水一致(时钟与雪花 id 不得进快照)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void submit_result_snapshot_golden_is_committed() {
|
||||
assertTrue(GOLDEN_SUBMIT.isFile(), "golden 文件必须存在并入库: " + GOLDEN_SUBMIT.getAbsolutePath());
|
||||
assertTrue(GOLDEN_SUBMIT.length() > 0, "golden 文件非空");
|
||||
}
|
||||
|
||||
@Test
|
||||
void submit_result_snapshot_tamper_is_detected() throws Exception {
|
||||
String original = read(GOLDEN_SUBMIT);
|
||||
assertTrue(original.contains("== case=happyShop"), "golden 内容合法");
|
||||
try {
|
||||
Files.writeString(GOLDEN_SUBMIT.toPath(), original + "\n# tampered", StandardCharsets.UTF_8);
|
||||
assertTrue(!read(GOLDEN_SUBMIT).equals(runAll()), "篡改 golden 后断言应失败");
|
||||
} finally {
|
||||
Files.writeString(GOLDEN_SUBMIT.toPath(), original, StandardCharsets.UTF_8);
|
||||
}
|
||||
assertEquals(original, read(GOLDEN_SUBMIT), "恢复原始 golden");
|
||||
}
|
||||
|
||||
/** 只在显式点名时写 golden:默认跑测试永远不许改是非源(pom 的 argLine 是显式配置,-D 传不进 fork,故用环境变量)。 */
|
||||
@Test
|
||||
@EnabledIfEnvironmentVariable(named = "SHUFU_SNAPSHOT_WRITE", matches = "true")
|
||||
void write_golden_on_demand() throws Exception {
|
||||
Files.createDirectories(GOLDEN_SUBMIT.getParentFile().toPath());
|
||||
Files.writeString(GOLDEN_SUBMIT.toPath(), runAll(), StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
+292
@@ -0,0 +1,292 @@
|
||||
package com.nanri.aiimage.modules.shopmatch.service.support;
|
||||
|
||||
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 com.nanri.aiimage.common.service.ResultDownloadResolver;
|
||||
import com.nanri.aiimage.config.TaskPressureProperties;
|
||||
import com.nanri.aiimage.modules.file.service.oss.OssStorageService;
|
||||
import com.nanri.aiimage.modules.shopkey.mapper.QueryAsinMapper;
|
||||
import com.nanri.aiimage.modules.shopkey.service.SkipPriceAsinService;
|
||||
import com.nanri.aiimage.modules.shopmatch.mapper.ShopMatchShopCandidateMapper;
|
||||
import com.nanri.aiimage.modules.shopmatch.model.dto.ShopMatchCreateTaskRequest;
|
||||
import com.nanri.aiimage.modules.shopmatch.model.dto.ShopMatchTaskItemDto;
|
||||
import com.nanri.aiimage.modules.shopmatch.model.vo.ShopMatchCreateTaskVo;
|
||||
import com.nanri.aiimage.modules.shopmatch.service.ShopMatchExcelAssemblyService;
|
||||
import com.nanri.aiimage.modules.shopmatch.service.ShopMatchTaskCacheService;
|
||||
import com.nanri.aiimage.modules.shopmatch.service.ShopMatchTaskService;
|
||||
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.service.TaskDistributedLockService;
|
||||
import com.nanri.aiimage.modules.task.service.TaskFileJobService;
|
||||
import com.nanri.aiimage.modules.task.service.TaskProgressLightAssembler;
|
||||
import com.nanri.aiimage.modules.task.service.TaskResultPayloadService;
|
||||
import com.nanri.aiimage.modules.ziniao.service.ZiniaoShopSwitchService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
|
||||
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.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* 匹配店铺建单段的现网行为快照(重构蓝图 Phase 0 · 1B,缺快照的四支之二)。
|
||||
*
|
||||
* 本模块此前只有 1 支测试/264 行,对 3,275 行源码——蓝图把 3C(collectdata+shopmatch)
|
||||
* 的开工红线钉在「快照补齐之前不得动」,这一支就是那条红线的解。
|
||||
* 快照打的是真 {@link ShopMatchTaskService#createTask}:建单校验的顺序、按归一化店名去重、
|
||||
* 国家代码白名单、排期分出的 SCHEDULED/RUNNING 两条状态,以及「心跳只在 RUNNING 时打」
|
||||
* 这条跨模块契约(蓝图 §1A 要接的心跳,本支在建单侧一并钉住)。
|
||||
* 落库侧捕获 fileTaskMapper/fileResultMapper 的 insert/update 入参;时钟不进快照——
|
||||
* scheduleTimes 用「现在 + N 天」构造,scheduledAt 只渲染「有没有」。
|
||||
*
|
||||
* 这支没有 Excel 输入:它的「解析」是把 {@code ShopMatchTaskItemDto} 队列归一化成任务项
|
||||
* ({@code toQueueItems → dedupeQueueItems → toTaskItems}),所以夹具直接喂请求对象。
|
||||
*
|
||||
* golden 文件:src/test/resources/shopmatch/golden/create-task-snapshot.txt
|
||||
*/
|
||||
class ShopMatchSnapshotTest {
|
||||
|
||||
private static final File GOLDEN_CREATE =
|
||||
new File("src/test/resources/shopmatch/golden/create-task-snapshot.txt");
|
||||
|
||||
private static final class Captured {
|
||||
private final List<FileTaskEntity> taskInserts = new ArrayList<>();
|
||||
private final List<FileTaskEntity> taskUpdates = new ArrayList<>();
|
||||
private final List<FileResultEntity> resultInserts = new ArrayList<>();
|
||||
private int heartbeats;
|
||||
}
|
||||
|
||||
/**
|
||||
* Spring 注入的那只 ObjectMapper 不是 {@code new ObjectMapper()}:Boot 会把 classpath 上的
|
||||
* jackson-datatype-jsr310 注册进去(本仓 2.18.11 在),并把 WRITE_DATES_AS_TIMESTAMPS 关掉。
|
||||
* 用裸 mapper 会让 {@code scheduleTimes}(List<LocalDateTime>)序列化失败,被建单那段
|
||||
* 的 {@code catch (Exception)} 吞成「task 不存在」——快照就会锁在一个生产里不存在的假形状上。
|
||||
*/
|
||||
private static ObjectMapper bootLikeObjectMapper() {
|
||||
return JsonMapper.builder()
|
||||
.addModule(new JavaTimeModule())
|
||||
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
|
||||
.build();
|
||||
}
|
||||
|
||||
private static ShopMatchTaskService newService(Captured captured) {
|
||||
FileTaskMapper fileTaskMapper = mock(FileTaskMapper.class);
|
||||
FileResultMapper fileResultMapper = mock(FileResultMapper.class);
|
||||
ZiniaoShopSwitchService ziniao = mock(ZiniaoShopSwitchService.class);
|
||||
ShopMatchTaskCacheService cacheService = mock(ShopMatchTaskCacheService.class);
|
||||
|
||||
doAnswer(invocation -> {
|
||||
FileTaskEntity entity = invocation.getArgument(0);
|
||||
entity.setId(1001L + captured.taskInserts.size());
|
||||
captured.taskInserts.add(entity);
|
||||
return 1;
|
||||
}).when(fileTaskMapper).insert(any(FileTaskEntity.class));
|
||||
doAnswer(invocation -> {
|
||||
captured.taskUpdates.add(invocation.getArgument(0));
|
||||
return 1;
|
||||
}).when(fileTaskMapper).updateById(any(FileTaskEntity.class));
|
||||
doAnswer(invocation -> {
|
||||
FileResultEntity entity = invocation.getArgument(0);
|
||||
entity.setId(2001L + captured.resultInserts.size());
|
||||
captured.resultInserts.add(entity);
|
||||
return 1;
|
||||
}).when(fileResultMapper).insert(any(FileResultEntity.class));
|
||||
// 去重键是「归一化后的店名」,这里给一条去首尾空白的最小归一化:
|
||||
// 本支要钉的是「按归一化名去重、不按原始名」这条形状,紫鸟归一化本身归它自己的套件。
|
||||
when(ziniao.normalizeShopName(any())).thenAnswer(invocation -> {
|
||||
String shopName = invocation.getArgument(0);
|
||||
return shopName == null ? "" : shopName.trim();
|
||||
});
|
||||
doAnswer(invocation -> {
|
||||
captured.heartbeats++;
|
||||
return null;
|
||||
}).when(cacheService).touchTaskHeartbeat(any());
|
||||
|
||||
return new ShopMatchTaskService(fileTaskMapper, fileResultMapper,
|
||||
mock(ShopMatchShopCandidateMapper.class), ziniao,
|
||||
mock(ShopMatchExcelAssemblyService.class), mock(OssStorageService.class),
|
||||
mock(ResultDownloadResolver.class), bootLikeObjectMapper(), cacheService,
|
||||
mock(TaskPressureProperties.class), mock(TaskResultPayloadService.class),
|
||||
mock(TaskFileJobService.class), mock(TaskDistributedLockService.class),
|
||||
mock(SkipPriceAsinService.class), mock(QueryAsinMapper.class),
|
||||
mock(TaskProgressLightAssembler.class), mock(PlatformTransactionManager.class));
|
||||
}
|
||||
|
||||
private static ShopMatchTaskItemDto shop(String shopName, boolean matched) {
|
||||
ShopMatchTaskItemDto item = new ShopMatchTaskItemDto();
|
||||
item.setShopName(shopName);
|
||||
item.setMatched(matched);
|
||||
item.setShopId(matched ? "shop-" + shopName.trim() : null);
|
||||
item.setPlatform("amazon");
|
||||
item.setCompanyName("公司-" + shopName.trim());
|
||||
item.setOpenStoreUrl("https://example.invalid/" + shopName.trim());
|
||||
item.setMatchedUserId(9L);
|
||||
item.setMatchStatus(matched ? "MATCHED" : "NOT_FOUND");
|
||||
item.setMatchMessage(matched ? "" : "店铺未匹配");
|
||||
return item;
|
||||
}
|
||||
|
||||
private static ShopMatchCreateTaskRequest request(List<ShopMatchTaskItemDto> items,
|
||||
List<String> countryCodes,
|
||||
List<LocalDateTime> scheduleTimes) {
|
||||
ShopMatchCreateTaskRequest request = new ShopMatchCreateTaskRequest();
|
||||
request.setUserId(7L);
|
||||
request.setItems(items);
|
||||
request.setCountryCodes(countryCodes);
|
||||
request.setScheduleTimes(scheduleTimes);
|
||||
return request;
|
||||
}
|
||||
|
||||
private static String nullToDash(Object value) {
|
||||
String text = value == null ? "" : String.valueOf(value);
|
||||
return text.isBlank() ? "-" : text;
|
||||
}
|
||||
|
||||
private static int countOccurrences(String text, String needle) {
|
||||
int count = 0;
|
||||
int index = text.indexOf(needle);
|
||||
while (index >= 0) {
|
||||
count++;
|
||||
index = text.indexOf(needle, index + needle.length());
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
private static String runCase(String caseName, ShopMatchCreateTaskRequest request) {
|
||||
Captured captured = new Captured();
|
||||
ShopMatchTaskService service = newService(captured);
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("== case=").append(caseName).append('\n');
|
||||
try {
|
||||
ShopMatchCreateTaskVo vo = service.createTask(request, "dev-1");
|
||||
sb.append("vo: taskId=").append(nullToDash(vo.getTaskId()))
|
||||
.append(" items=").append(vo.getItems().size()).append('\n');
|
||||
for (ShopMatchCreateTaskVo.Item item : vo.getItems()) {
|
||||
sb.append(" item: resultId=").append(nullToDash(item.getResultId()))
|
||||
.append(" shopName=").append(nullToDash(item.getShopName()))
|
||||
.append(" shopId=").append(nullToDash(item.getShopId()))
|
||||
.append(" matched=").append(item.isMatched())
|
||||
.append(" matchStatus=").append(nullToDash(item.getMatchStatus()))
|
||||
.append(" taskStatus=").append(nullToDash(item.getTaskStatus()))
|
||||
.append(" success=").append(nullToDash(item.getSuccess()))
|
||||
.append(" scheduledAtPresent=").append(item.getScheduledAt() != null)
|
||||
.append('\n');
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
sb.append("thrown: ").append(ex.getClass().getSimpleName())
|
||||
.append(" message=").append(nullToDash(ex.getMessage())).append('\n');
|
||||
}
|
||||
for (FileTaskEntity task : captured.taskInserts) {
|
||||
sb.append("task.insert: id=").append(task.getId())
|
||||
.append(" moduleType=").append(nullToDash(task.getModuleType()))
|
||||
.append(" taskMode=").append(nullToDash(task.getTaskMode()))
|
||||
.append(" status=").append(nullToDash(task.getStatus()))
|
||||
.append(" sourceFileCount=").append(nullToDash(task.getSourceFileCount()))
|
||||
.append(" deviceId=").append(nullToDash(task.getDeviceId()))
|
||||
.append(" scheduledAtPresent=").append(task.getScheduledAt() != null)
|
||||
.append('\n');
|
||||
}
|
||||
for (FileTaskEntity task : captured.taskUpdates) {
|
||||
sb.append("task.update: id=").append(task.getId())
|
||||
.append(" status=").append(nullToDash(task.getStatus()))
|
||||
.append(" requestJsonStageIndexZero=").append(task.getRequestJson() != null
|
||||
&& task.getRequestJson().contains("\"current_stage_index\":0"))
|
||||
.append(" requestJsonStageIndexNull=").append(task.getRequestJson() != null
|
||||
&& task.getRequestJson().contains("\"current_stage_index\":null"))
|
||||
.append(" resultJsonResultIds=").append(task.getResultJson() == null ? -1
|
||||
: countOccurrences(task.getResultJson(), "\"resultId\""))
|
||||
.append('\n');
|
||||
}
|
||||
for (FileResultEntity result : captured.resultInserts) {
|
||||
sb.append("result.insert: id=").append(result.getId())
|
||||
.append(" taskId=").append(nullToDash(result.getTaskId()))
|
||||
.append(" moduleType=").append(nullToDash(result.getModuleType()))
|
||||
.append(" sourceFilename=").append(nullToDash(result.getSourceFilename()))
|
||||
.append(" sourceFileUrl=").append(nullToDash(result.getSourceFileUrl()))
|
||||
.append(" success=").append(nullToDash(result.getSuccess()))
|
||||
.append('\n');
|
||||
}
|
||||
sb.append("heartbeatTouches=").append(captured.heartbeats).append('\n');
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public static String runAll() {
|
||||
List<ShopMatchTaskItemDto> twoShops = List.of(shop("店铺A", true), shop("店铺B", true));
|
||||
StringBuilder sb = new StringBuilder();
|
||||
// 国家代码:去空白+转大写+去重,且只认 ProductRiskCountryCode 那五个(US 不在内)
|
||||
sb.append(runCase("immediate", request(twoShops, List.of("uk", "UK", " uk ", ""), List.of())));
|
||||
sb.append(runCase("usNotSupportedCountry", request(twoShops, List.of("US"), List.of())));
|
||||
sb.append(runCase("dedupedByNormalizedName", request(
|
||||
List.of(shop("店铺A", true), shop(" 店铺A ", true), shop("店铺B", true)),
|
||||
List.of("DE"), List.of())));
|
||||
sb.append(runCase("scheduled", request(twoShops, List.of("UK"),
|
||||
List.of(LocalDateTime.now().plusDays(1), LocalDateTime.now().plusDays(2)))));
|
||||
sb.append(runCase("unmatchedShop", request(
|
||||
List.of(shop("店铺A", true), shop("店铺C", false)), List.of("UK"), List.of())));
|
||||
sb.append(runCase("badCountryCode", request(twoShops, List.of("CN"), List.of())));
|
||||
sb.append(runCase("emptyCountryCodes", request(twoShops, List.of(), List.of())));
|
||||
sb.append(runCase("scheduleInPast", request(twoShops, List.of("UK"),
|
||||
List.of(LocalDateTime.now().minusDays(1)))));
|
||||
sb.append(runCase("scheduleNotIncreasing", request(twoShops, List.of("UK"),
|
||||
List.of(LocalDateTime.now().plusDays(2), LocalDateTime.now().plusDays(1)))));
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private static String read(File file) throws Exception {
|
||||
return Files.readString(file.toPath(), StandardCharsets.UTF_8).replace("\r\n", "\n");
|
||||
}
|
||||
|
||||
@Test
|
||||
void create_task_snapshot_matches_golden() throws Exception {
|
||||
assertEquals(read(GOLDEN_CREATE), runAll(), "建单输出快照与 golden 一致");
|
||||
}
|
||||
|
||||
@Test
|
||||
void create_task_snapshot_is_reproducible() {
|
||||
assertEquals(runAll(), runAll(), "同一夹具跑两次结果一致(时钟与雪花 id 不得进快照)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void create_task_snapshot_golden_is_committed() {
|
||||
assertTrue(GOLDEN_CREATE.isFile(), "golden 文件必须存在并入库: " + GOLDEN_CREATE.getAbsolutePath());
|
||||
assertTrue(GOLDEN_CREATE.length() > 0, "golden 文件非空");
|
||||
}
|
||||
|
||||
@Test
|
||||
void create_task_snapshot_tamper_is_detected() throws Exception {
|
||||
String original = read(GOLDEN_CREATE);
|
||||
assertTrue(original.contains("== case=immediate"), "golden 内容合法");
|
||||
try {
|
||||
Files.writeString(GOLDEN_CREATE.toPath(), original + "\n# tampered", StandardCharsets.UTF_8);
|
||||
assertTrue(!read(GOLDEN_CREATE).equals(runAll()), "篡改 golden 后断言应失败");
|
||||
} finally {
|
||||
Files.writeString(GOLDEN_CREATE.toPath(), original, StandardCharsets.UTF_8);
|
||||
}
|
||||
assertEquals(original, read(GOLDEN_CREATE), "恢复原始 golden");
|
||||
}
|
||||
|
||||
/** 逐行 insert 的自增主键回填是 resultId 的来源——改成批量插入会让快照 resultId 变 null。 */
|
||||
@Test
|
||||
void create_task_backfills_result_id_per_row() {
|
||||
Captured captured = new Captured();
|
||||
ShopMatchCreateTaskVo vo = newService(captured).createTask(
|
||||
request(List.of(shop("店铺A", true), shop("店铺B", true)), List.of("UK"), List.of()), "dev-1");
|
||||
assertEquals(2, vo.getItems().size());
|
||||
assertEquals(2001L, vo.getItems().get(0).getResultId());
|
||||
assertEquals(2002L, vo.getItems().get(1).getResultId());
|
||||
}
|
||||
}
|
||||
+540
@@ -0,0 +1,540 @@
|
||||
package com.nanri.aiimage.modules.shopmatch.service.support;
|
||||
|
||||
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 com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.service.ResultDownloadResolver;
|
||||
import com.nanri.aiimage.config.TaskPressureProperties;
|
||||
import com.nanri.aiimage.modules.file.service.oss.OssStorageService;
|
||||
import com.nanri.aiimage.modules.productrisk.model.enums.ProductRiskCountryCode;
|
||||
import com.nanri.aiimage.modules.shopkey.mapper.QueryAsinMapper;
|
||||
import com.nanri.aiimage.modules.shopkey.service.SkipPriceAsinService;
|
||||
import com.nanri.aiimage.modules.shopmatch.mapper.ShopMatchShopCandidateMapper;
|
||||
import com.nanri.aiimage.modules.shopmatch.model.dto.ShopMatchCreateTaskRequest;
|
||||
import com.nanri.aiimage.modules.shopmatch.model.dto.ShopMatchRowDto;
|
||||
import com.nanri.aiimage.modules.shopmatch.model.dto.ShopMatchShopPayloadDto;
|
||||
import com.nanri.aiimage.modules.shopmatch.model.dto.ShopMatchSubmitResultRequest;
|
||||
import com.nanri.aiimage.modules.shopmatch.model.dto.ShopMatchTaskItemDto;
|
||||
import com.nanri.aiimage.modules.shopmatch.service.ShopMatchExcelAssemblyService;
|
||||
import com.nanri.aiimage.modules.shopmatch.service.ShopMatchTaskCacheService;
|
||||
import com.nanri.aiimage.modules.shopmatch.service.ShopMatchTaskService;
|
||||
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.service.TaskDistributedLockService;
|
||||
import com.nanri.aiimage.modules.task.service.TaskFileJobService;
|
||||
import com.nanri.aiimage.modules.task.service.TaskProgressLightAssembler;
|
||||
import com.nanri.aiimage.modules.task.service.TaskResultPayloadService;
|
||||
import com.nanri.aiimage.modules.ziniao.service.ZiniaoShopSwitchService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
|
||||
import java.io.File;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* 匹配店铺回传落库(段 3)+出结果排队(段 4 入口)的现网行为快照——Phase 3 首迁的护身符。
|
||||
*
|
||||
* <p><b>为什么补这一支。</b>Phase 0 的 {@link ShopMatchSnapshotTest} 只锁到「建单+解析+载荷」,
|
||||
* 蓝图 §5 收口实录明文写着「{@code submitResult} 出结果段本轮未打快照——Phase 3 要动那一段,先补再动」。
|
||||
* Phase 3 首迁要改的正是那一段(取锁→准入→按店名建索引→逐行合并→changed 闸门→重算状态换成
|
||||
* {@code AbstractShopPayloadTaskPipeline.submitShopScopedResults}),所以这一支必须落在迁移**之前**:
|
||||
* 迁移后 golden 逐字节不动,才谈得上「对外行为未变」。
|
||||
*
|
||||
* <p><b>快照吃的是事件流水,不是分组清单。</b>建单快照按类型分组渲染够用(建单只写一次库);
|
||||
* 回传段的风险恰恰在副作用**先后**:先标失败还是先挂文件、mergedRemove 在不在 enqueue 之后、
|
||||
* changed=false 时任务表一次都不许写。所以这里把 result.update / task.update / payloadSave /
|
||||
* enqueue / mergedSave / mergedRemove / taskCacheSave / taskCacheDelete 全按真实调用顺序落成一条流水,
|
||||
* 顺序换了就红——那正是「抽公共段」最容易悄悄改掉的东西。
|
||||
*
|
||||
* <p><b>替身只实现这条链真吃到的部分</b>:结果行是一份内存表({@code selectList} 每次返回同一批活实体,
|
||||
* 所以重读天然看见上一次 update 的写入——模拟的是同一次调用内的重读,不是数据库隔离级别);
|
||||
* 店铺合并载荷是一份 HashMap 接住 get/save/remove,于是分片回传的合并语义是真的
|
||||
* (第二片确实读得到第一片),不是把合并跳过。时钟、雪花 id、OSS 直链一律不进快照。
|
||||
*
|
||||
* golden:src/test/resources/shopmatch/golden/submit-result-snapshot.txt
|
||||
* 重新生成:{@code SHUFU_SNAPSHOT_WRITE=true mvn -o test -Dtest=ShopMatchSubmitResultSnapshotTest}
|
||||
* (用环境变量而不是 -D:pom 里 {@code <argLine>} 是显式配置,命令行 -DargLine 覆盖不动它,
|
||||
* 系统属性传不进 fork;forked JVM 继承父进程环境,所以这条才真能点名)
|
||||
* (只在被迁支改动**之前**生成一次,此后这条 golden 就是不可动的是非源)
|
||||
*/
|
||||
class ShopMatchSubmitResultSnapshotTest {
|
||||
|
||||
private static final File GOLDEN_SUBMIT =
|
||||
new File("src/test/resources/shopmatch/golden/submit-result-snapshot.txt");
|
||||
private static final long TASK_ID = 1001L;
|
||||
|
||||
/** 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();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// 夹具
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
private static final class Fixture {
|
||||
private final ObjectMapper objectMapper = bootLikeObjectMapper();
|
||||
private final List<String> events = new ArrayList<>();
|
||||
private final Map<String, ShopMatchShopPayloadDto> mergedPayloads = new LinkedHashMap<>();
|
||||
private final FileTaskEntity task = new FileTaskEntity();
|
||||
private final List<FileResultEntity> rows = new ArrayList<>();
|
||||
private ShopMatchTaskService service;
|
||||
private int heartbeats;
|
||||
private int lockCloses;
|
||||
|
||||
private Fixture withRows(String... shopNames) {
|
||||
long id = 2001L;
|
||||
for (String shopName : shopNames) {
|
||||
FileResultEntity row = new FileResultEntity();
|
||||
row.setId(id++);
|
||||
row.setTaskId(TASK_ID);
|
||||
row.setModuleType("SHOP_MATCH");
|
||||
row.setSourceFilename(shopName);
|
||||
row.setSourceFileUrl("shop-" + shopName);
|
||||
row.setUserId(7L);
|
||||
row.setSuccess(0);
|
||||
rows.add(row);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
private Fixture withTask(String status, String moduleType, String requestJson) {
|
||||
task.setId(TASK_ID);
|
||||
task.setUserId(7L);
|
||||
task.setModuleType(moduleType);
|
||||
task.setStatus(status);
|
||||
task.setRequestJson(requestJson);
|
||||
return this;
|
||||
}
|
||||
|
||||
private ShopMatchTaskService service() {
|
||||
if (service != null) {
|
||||
return service;
|
||||
}
|
||||
FileTaskMapper fileTaskMapper = mock(FileTaskMapper.class);
|
||||
FileResultMapper fileResultMapper = mock(FileResultMapper.class);
|
||||
ShopMatchTaskCacheService cacheService = mock(ShopMatchTaskCacheService.class);
|
||||
ZiniaoShopSwitchService ziniao = mock(ZiniaoShopSwitchService.class);
|
||||
ShopMatchExcelAssemblyService assembly = mock(ShopMatchExcelAssemblyService.class);
|
||||
TaskResultPayloadService payloadService = mock(TaskResultPayloadService.class);
|
||||
TaskFileJobService fileJobService = mock(TaskFileJobService.class);
|
||||
TaskDistributedLockService lockService = mock(TaskDistributedLockService.class);
|
||||
TaskDistributedLockService.LockHandle lock = mock(TaskDistributedLockService.LockHandle.class);
|
||||
|
||||
when(fileResultMapper.selectList(any())).thenAnswer(invocation -> List.copyOf(rows));
|
||||
doAnswer(invocation -> {
|
||||
events.add("result.update: " + renderRow(invocation.getArgument(0)));
|
||||
return 1;
|
||||
}).when(fileResultMapper).updateById(any(FileResultEntity.class));
|
||||
doAnswer(invocation -> {
|
||||
events.add("task.update: " + renderTask(invocation.getArgument(0)));
|
||||
return 1;
|
||||
}).when(fileTaskMapper).updateById(any(FileTaskEntity.class));
|
||||
|
||||
when(lockService.acquire(anyString(), anyLong())).thenReturn(lock);
|
||||
doAnswer(invocation -> {
|
||||
lockCloses++;
|
||||
return null;
|
||||
}).when(lock).close();
|
||||
|
||||
when(cacheService.getTaskCacheBatch(any())).thenAnswer(invocation -> Map.of(TASK_ID, task));
|
||||
doAnswer(invocation -> {
|
||||
heartbeats++;
|
||||
return null;
|
||||
}).when(cacheService).touchTaskHeartbeat(any());
|
||||
when(cacheService.getShopMergedPayload(anyLong(), anyString()))
|
||||
.thenAnswer(invocation -> mergedPayloads.get(invocation.<String>getArgument(1)));
|
||||
doAnswer(invocation -> {
|
||||
String shopKey = invocation.getArgument(1);
|
||||
ShopMatchShopPayloadDto payload = invocation.getArgument(2);
|
||||
mergedPayloads.put(shopKey, payload);
|
||||
events.add("mergedSave: taskId=" + invocation.<Long>getArgument(0)
|
||||
+ " shopKey=" + shopKey + " " + renderPayload(payload));
|
||||
return null;
|
||||
}).when(cacheService).saveShopMergedPayload(anyLong(), anyString(), any());
|
||||
doAnswer(invocation -> {
|
||||
events.add("mergedRemove: taskId=" + invocation.getArgument(0)
|
||||
+ " shopKey=" + invocation.getArgument(1));
|
||||
mergedPayloads.remove(invocation.<String>getArgument(1));
|
||||
return null;
|
||||
}).when(cacheService).removeShopMergedPayload(anyLong(), anyString());
|
||||
doAnswer(invocation -> {
|
||||
events.add("taskCacheSave: id=" + ((FileTaskEntity) invocation.getArgument(0)).getId());
|
||||
return null;
|
||||
}).when(cacheService).saveTaskCache(any(FileTaskEntity.class));
|
||||
doAnswer(invocation -> {
|
||||
events.add("taskCacheDelete: taskId=" + invocation.getArgument(0));
|
||||
return null;
|
||||
}).when(cacheService).deleteTaskCache(any());
|
||||
|
||||
doAnswer(invocation -> {
|
||||
events.add("payloadSave: taskId=" + invocation.getArgument(0)
|
||||
+ " moduleType=" + invocation.getArgument(1)
|
||||
+ " scopeKey=" + invocation.getArgument(2)
|
||||
+ " " + renderPayload(invocation.getArgument(3)));
|
||||
return null;
|
||||
}).when(payloadService).saveLatest(anyLong(), anyString(), anyString(), any());
|
||||
// 组装 Job 一律「查不到」:提交时刚排队、Job 还没跑完,任务因此必须留在 RUNNING
|
||||
when(fileJobService.findAssembleJobsByResultIds(anyString(), any())).thenReturn(Map.of());
|
||||
when(fileJobService.findAssembleJob(any(), anyString(), any())).thenReturn(null);
|
||||
doAnswer(invocation -> {
|
||||
events.add("enqueue: taskId=" + invocation.getArgument(0)
|
||||
+ " moduleType=" + invocation.getArgument(1)
|
||||
+ " resultId=" + invocation.getArgument(2)
|
||||
+ " scopeKey=" + invocation.getArgument(3));
|
||||
return null;
|
||||
}).when(fileJobService).enqueueAssembleResult(anyLong(), anyString(), anyLong(), anyString());
|
||||
|
||||
when(ziniao.normalizeShopName(any())).thenAnswer(invocation -> {
|
||||
String shopName = invocation.<String>getArgument(0);
|
||||
return shopName == null ? "" : shopName.trim();
|
||||
});
|
||||
when(assembly.normalizeCountriesMap(any())).thenAnswer(invocation -> {
|
||||
Map<ProductRiskCountryCode, List<ShopMatchRowDto>> raw = invocation.getArgument(0);
|
||||
Map<String, List<ShopMatchRowDto>> out = new LinkedHashMap<>();
|
||||
if (raw != null) {
|
||||
raw.forEach((country, list) -> out.put(String.valueOf(country), list));
|
||||
}
|
||||
return out;
|
||||
});
|
||||
when(assembly.countRows(any())).thenAnswer(invocation -> {
|
||||
Map<String, List<ShopMatchRowDto>> countries = invocation.getArgument(0);
|
||||
int count = 0;
|
||||
for (List<ShopMatchRowDto> list : countries.values()) {
|
||||
count += list == null ? 0 : list.size();
|
||||
}
|
||||
return count;
|
||||
});
|
||||
|
||||
service = new ShopMatchTaskService(fileTaskMapper, fileResultMapper,
|
||||
mock(ShopMatchShopCandidateMapper.class), ziniao, assembly,
|
||||
mock(OssStorageService.class), mock(ResultDownloadResolver.class), objectMapper,
|
||||
cacheService, mock(TaskPressureProperties.class), payloadService, fileJobService,
|
||||
lockService, mock(SkipPriceAsinService.class), mock(QueryAsinMapper.class),
|
||||
mock(TaskProgressLightAssembler.class), mock(PlatformTransactionManager.class));
|
||||
return service;
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// 渲染(时钟/雪花 id/OSS 直链不进快照)
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
private static String renderRow(FileResultEntity row) {
|
||||
return "id=" + row.getId()
|
||||
+ " success=" + row.getSuccess()
|
||||
+ " error=" + dash(row.getErrorMessage())
|
||||
+ " filename=" + dash(row.getResultFilename())
|
||||
+ " urlPresent=" + (row.getResultFileUrl() != null && !row.getResultFileUrl().isBlank())
|
||||
+ " size=" + row.getResultFileSize()
|
||||
+ " contentType=" + dash(row.getResultContentType())
|
||||
+ " rowCount=" + row.getRowCount();
|
||||
}
|
||||
|
||||
private static String renderTask(FileTaskEntity task) {
|
||||
return "id=" + task.getId()
|
||||
+ " status=" + dash(task.getStatus())
|
||||
+ " ok=" + task.getSuccessFileCount()
|
||||
+ " fail=" + task.getFailedFileCount()
|
||||
+ " sourceFileCount=" + task.getSourceFileCount()
|
||||
+ " error=" + dash(task.getErrorMessage())
|
||||
+ " resultJsonItems=" + (task.getResultJson() == null ? -1
|
||||
: count(task.getResultJson(), "\"resultId\""))
|
||||
+ " finishedPresent=" + (task.getFinishedAt() != null);
|
||||
}
|
||||
|
||||
private static String renderPayload(Object payload) {
|
||||
if (!(payload instanceof ShopMatchShopPayloadDto dto)) {
|
||||
return "payload=" + (payload == null ? "<null>" : "<" + payload.getClass().getSimpleName() + ">");
|
||||
}
|
||||
int countries = dto.getCountries() == null ? 0 : dto.getCountries().size();
|
||||
int rows = 0;
|
||||
if (dto.getCountries() != null) {
|
||||
for (List<ShopMatchRowDto> list : dto.getCountries().values()) {
|
||||
rows += list == null ? 0 : list.size();
|
||||
}
|
||||
}
|
||||
int skipDetails = dto.getSkipAsinDetailsByCountry() == null ? 0 : dto.getSkipAsinDetailsByCountry().size();
|
||||
return "shopName=" + dash(dto.getShopName()) + " error=" + dash(dto.getError())
|
||||
+ " countries=" + countries + " rows=" + rows + " skipDetailCountries=" + skipDetails;
|
||||
}
|
||||
|
||||
private static String dash(Object value) {
|
||||
String text = value == null ? "" : String.valueOf(value);
|
||||
return text.isBlank() ? "-" : text;
|
||||
}
|
||||
|
||||
private static int count(String text, String needle) {
|
||||
int occurrences = 0;
|
||||
int index = text.indexOf(needle);
|
||||
while (index >= 0) {
|
||||
occurrences++;
|
||||
index = text.indexOf(needle, index + needle.length());
|
||||
}
|
||||
return occurrences;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// 请求构造
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
private static ShopMatchRowDto row(String asin, String minimumPrice, boolean done) {
|
||||
ShopMatchRowDto row = new ShopMatchRowDto();
|
||||
row.setAsin(asin);
|
||||
row.setMinimumPrice(minimumPrice);
|
||||
row.setStatus("在售");
|
||||
row.setDone(done);
|
||||
return row;
|
||||
}
|
||||
|
||||
private static ShopMatchShopPayloadDto shop(String shopName, String error,
|
||||
ProductRiskCountryCode country, ShopMatchRowDto... rows) {
|
||||
ShopMatchShopPayloadDto dto = new ShopMatchShopPayloadDto();
|
||||
dto.setShopName(shopName);
|
||||
dto.setError(error);
|
||||
Map<ProductRiskCountryCode, List<ShopMatchRowDto>> countries = new LinkedHashMap<>();
|
||||
if (country != null) {
|
||||
countries.put(country, List.of(rows));
|
||||
}
|
||||
dto.setCountries(countries);
|
||||
return dto;
|
||||
}
|
||||
|
||||
private static ShopMatchSubmitResultRequest request(ShopMatchShopPayloadDto... shops) {
|
||||
ShopMatchSubmitResultRequest request = new ShopMatchSubmitResultRequest();
|
||||
request.setShops(List.of(shops));
|
||||
return request;
|
||||
}
|
||||
|
||||
/** 队列里两个店各带一条明细:{@code mergeQueueFieldsFromRequest} 会按归一化店名回填这些字段。 */
|
||||
private static String requestJsonOf(ObjectMapper objectMapper, List<String> shopNames) throws Exception {
|
||||
ShopMatchCreateTaskRequest persisted = new ShopMatchCreateTaskRequest();
|
||||
persisted.setUserId(7L);
|
||||
List<ShopMatchTaskItemDto> items = new ArrayList<>();
|
||||
for (String shopName : shopNames) {
|
||||
ShopMatchTaskItemDto item = new ShopMatchTaskItemDto();
|
||||
item.setShopName(shopName);
|
||||
item.setMatched(true);
|
||||
item.setShopId("shop-" + shopName);
|
||||
item.setPlatform("amazon");
|
||||
item.setCompanyName("公司-" + shopName);
|
||||
item.setMatchedUserId(9L);
|
||||
item.setMatchStatus("MATCHED");
|
||||
item.setMatchMessage("");
|
||||
items.add(item);
|
||||
}
|
||||
persisted.setItems(items);
|
||||
persisted.setCountryCodes(List.of("UK"));
|
||||
persisted.setScheduleTimes(List.of());
|
||||
return objectMapper.writeValueAsString(persisted);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// 用例
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
private interface Emit {
|
||||
String render() throws Exception;
|
||||
}
|
||||
|
||||
private static void appendCase(StringBuilder sb, String caseName, Emit emit) {
|
||||
sb.append("== case=").append(caseName).append('\n');
|
||||
try {
|
||||
sb.append(emit.render());
|
||||
} catch (Exception ex) {
|
||||
sb.append("thrown: ").append(ex.getClass().getSimpleName())
|
||||
.append(" code=").append(ex instanceof BusinessException businessException
|
||||
? dash(businessException.getCode()) : "-")
|
||||
.append(" message=").append(dash(ex.getMessage())).append('\n');
|
||||
}
|
||||
}
|
||||
|
||||
/** 一次回传的全部可观测面:调用顺序流水+心跳与锁收尾计数。 */
|
||||
private static String submit(Fixture fixture, ShopMatchSubmitResultRequest request) {
|
||||
fixture.service().submitResult(TASK_ID, request);
|
||||
StringBuilder sb = new StringBuilder();
|
||||
fixture.events.forEach(line -> sb.append(line).append('\n'));
|
||||
return sb.append(counters(fixture)).toString();
|
||||
}
|
||||
|
||||
private static String counters(Fixture fixture) {
|
||||
return "events=" + fixture.events.size()
|
||||
+ " heartbeatTouches=" + fixture.heartbeats
|
||||
+ " lockCloses=" + fixture.lockCloses + '\n';
|
||||
}
|
||||
|
||||
/** 每个用例一套全新夹具:默认「RUNNING + 店铺A/店铺B 两行 + 合法 requestJson」。 */
|
||||
private static Fixture runningFixture() throws Exception {
|
||||
Fixture fixture = new Fixture();
|
||||
fixture.withRows("店铺A", "店铺B")
|
||||
.withTask("RUNNING", "SHOP_MATCH",
|
||||
requestJsonOf(fixture.objectMapper, List.of("店铺A", "店铺B")));
|
||||
return fixture;
|
||||
}
|
||||
|
||||
public static String runAll() throws Exception {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
// 1. 两店都跑完:合并→载荷落库→行标「文件名已定、文件待组装」→Job 排队→合并载荷清理
|
||||
// → 任务表**必须**留在 RUNNING:Job 没落地就标终态,前端一停轮询、下载按钮永远不出现
|
||||
Fixture happy = runningFixture();
|
||||
appendCase(sb, "happyTwoShops", () -> submit(happy, request(
|
||||
shop("店铺A", null, ProductRiskCountryCode.UK, row("B001", "19.90", true)),
|
||||
shop("店铺B", null, ProductRiskCountryCode.UK, row("B002", "20.00", true)))));
|
||||
|
||||
// 2. 回传的店铺不在任务行里 ⇒ changed=false ⇒ 任务表一次都不许写(心跳照打)
|
||||
Fixture unknown = runningFixture();
|
||||
appendCase(sb, "unknownShopWritesNothing", () -> submit(unknown, request(
|
||||
shop("店铺Z", null, ProductRiskCountryCode.UK, row("B009", "1.00", true)))));
|
||||
|
||||
// 3. shops 里夹 null 与空白店名:建索引时双双跳过 ⇒ 走「没命中任何行」同一条出口
|
||||
Fixture blanks = runningFixture();
|
||||
List<ShopMatchShopPayloadDto> withNulls = new ArrayList<>();
|
||||
withNulls.add(null);
|
||||
withNulls.add(shop(" ", null, ProductRiskCountryCode.UK, row("B010", "1.00", true)));
|
||||
withNulls.add(null);
|
||||
ShopMatchSubmitResultRequest nullish = new ShopMatchSubmitResultRequest();
|
||||
nullish.setShops(withNulls);
|
||||
appendCase(sb, "nullAndBlankShopSkipped", () -> submit(blanks, nullish));
|
||||
|
||||
// 4. 店铺报错但已有可用行 ⇒ 先标失败、再把部分结果排队(preserveFailure:success 保持 0、原因保留)
|
||||
Fixture partial = runningFixture();
|
||||
appendCase(sb, "failedShopWithPartialRows", () -> submit(partial, request(
|
||||
shop("店铺A", "会话掉线", ProductRiskCountryCode.UK, row("B001", "19.90", false)))));
|
||||
|
||||
// 5. 报错且一行都没有 ⇒ 不排队,只标失败(文件名清空,否则下载按钮指向空文件)
|
||||
Fixture failedOnly = runningFixture();
|
||||
appendCase(sb, "failedShopWithoutRows", () -> submit(failedOnly, request(
|
||||
shop("店铺A", "店铺打不开", null))));
|
||||
|
||||
// 6. 两个店铺都失败且都没行 ⇒ 每行都有交代 ⇒ 任务终态 FAILED + 缓存清理(分隔符是全角「;」)
|
||||
Fixture bothFailed = runningFixture();
|
||||
appendCase(sb, "allShopsFailedFinalizesTask", () -> submit(bothFailed, request(
|
||||
shop("店铺A", "店铺打不开", null),
|
||||
shop("店铺B", "国家页超时", null))));
|
||||
|
||||
// 7. done=true 但行里 ASIN 全空 ⇒ 本支闸门是 countPayloadRows>0 && anyDone,
|
||||
// 所以这条落的是「等更多分片」,**:689 那句「未收到可用于组装的结果数据」在 submitResult 路径上到不了**
|
||||
// (它只在 tryFinalizeTask 的不同判序下可达)。本例把这层不可达钉住:迁移若改掉了闸门形状,这里立刻红。
|
||||
Fixture noUsable = runningFixture();
|
||||
appendCase(sb, "blankAsinWithDoneFlagStillWaits", () -> submit(noUsable, request(
|
||||
shop("店铺A", null, ProductRiskCountryCode.UK, row("", "1.00", true)))));
|
||||
|
||||
// 8. 有行但没 done ⇒ 闸门在「等更多分片」:不排队、不清合并载荷
|
||||
Fixture waiting = runningFixture();
|
||||
appendCase(sb, "partialChunkWaitsForMore", () -> submit(waiting, request(
|
||||
shop("店铺A", null, ProductRiskCountryCode.UK, row("B001", "19.90", false)))));
|
||||
|
||||
// 9. 同一店铺分两片回传:第一片没 done,第二片补同一 ASIN 的最低价并 done。
|
||||
// 合并必须发生在缓存里那份合并载荷上(不是本次入参),否则第二片会把第一片的行丢掉。
|
||||
Fixture chunked = runningFixture();
|
||||
chunked.service().submitResult(TASK_ID, request(
|
||||
shop("店铺A", null, ProductRiskCountryCode.UK, row("B001", null, false))));
|
||||
chunked.events.clear();
|
||||
appendCase(sb, "chunkedMergeAcrossTwoSubmissions", () -> submit(chunked, request(
|
||||
shop("店铺A", null, ProductRiskCountryCode.UK, row("B001", "19.90", true)))));
|
||||
|
||||
// 10. 任务已终态 ⇒ 40901(Python 侧按幂等忽略并停止重试;换成无 code 就是另一种线协议)
|
||||
Fixture terminal = new Fixture();
|
||||
terminal.withRows("店铺A").withTask("SUCCESS", "SHOP_MATCH",
|
||||
requestJsonOf(terminal.objectMapper, List.of("店铺A")));
|
||||
appendCase(sb, "terminalTaskRejectedWith40901", () -> submit(terminal, request(
|
||||
shop("店铺A", null, ProductRiskCountryCode.UK, row("B001", "1.00", true)))));
|
||||
|
||||
// 11. 缓存里的行属于别的模块 ⇒ 「任务不存在」(不带 code,与上一例正好是两种线协议)
|
||||
Fixture wrongModule = new Fixture();
|
||||
wrongModule.withRows("店铺A").withTask("RUNNING", "APPEARANCE_PATENT",
|
||||
requestJsonOf(wrongModule.objectMapper, List.of("店铺A")));
|
||||
appendCase(sb, "wrongModuleTaskNotFound", () -> submit(wrongModule, request(
|
||||
shop("店铺A", null, ProductRiskCountryCode.UK, row("B001", "1.00", true)))));
|
||||
|
||||
// 12. taskId 非法 ⇒ 抢锁之前就拒:锁一次都不该被碰(自己吞掉异常,否则计数行渲染不出来)
|
||||
Fixture badId = runningFixture();
|
||||
badId.service();
|
||||
appendCase(sb, "invalidTaskIdRejectedBeforeLock", () -> {
|
||||
StringBuilder inner = new StringBuilder();
|
||||
try {
|
||||
badId.service.submitResult(0L, request(shop("店铺A", null, ProductRiskCountryCode.UK,
|
||||
row("B001", "1.00", true))));
|
||||
inner.append("thrown: none\n");
|
||||
} catch (Exception ex) {
|
||||
inner.append("thrown: ").append(ex.getClass().getSimpleName())
|
||||
.append(" code=").append(ex instanceof BusinessException businessException
|
||||
? dash(businessException.getCode()) : "-")
|
||||
.append(" message=").append(dash(ex.getMessage())).append('\n');
|
||||
}
|
||||
return inner.append(counters(badId)).toString();
|
||||
});
|
||||
|
||||
// 13. shops 为空 / 整个请求为 null ⇒ 同一句「shops 不能为空」
|
||||
Fixture emptyShops = runningFixture();
|
||||
appendCase(sb, "emptyShops", () -> submit(emptyShops, request()));
|
||||
Fixture nullRequest = runningFixture();
|
||||
appendCase(sb, "nullRequest", () -> submit(nullRequest, null));
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private static String read(File file) throws Exception {
|
||||
return Files.readString(file.toPath(), StandardCharsets.UTF_8).replace("\r\n", "\n");
|
||||
}
|
||||
|
||||
@Test
|
||||
void submit_result_snapshot_matches_golden() throws Exception {
|
||||
assertEquals(read(GOLDEN_SUBMIT), runAll(), "回传段落库流水与 golden 一致");
|
||||
}
|
||||
|
||||
@Test
|
||||
void submit_result_snapshot_is_reproducible() throws Exception {
|
||||
assertEquals(runAll(), runAll(), "同一夹具跑两次流水一致(时钟与雪花 id 不得进快照)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void submit_result_snapshot_golden_is_committed() {
|
||||
assertTrue(GOLDEN_SUBMIT.isFile(), "golden 文件必须存在并入库: " + GOLDEN_SUBMIT.getAbsolutePath());
|
||||
assertTrue(GOLDEN_SUBMIT.length() > 0, "golden 文件非空");
|
||||
}
|
||||
|
||||
@Test
|
||||
void submit_result_snapshot_tamper_is_detected() throws Exception {
|
||||
String original = read(GOLDEN_SUBMIT);
|
||||
assertTrue(original.contains("== case=happyTwoShops"), "golden 内容合法");
|
||||
try {
|
||||
Files.writeString(GOLDEN_SUBMIT.toPath(), original + "\n# tampered", StandardCharsets.UTF_8);
|
||||
assertTrue(!read(GOLDEN_SUBMIT).equals(runAll()), "篡改 golden 后断言应失败");
|
||||
} finally {
|
||||
Files.writeString(GOLDEN_SUBMIT.toPath(), original, StandardCharsets.UTF_8);
|
||||
}
|
||||
assertEquals(original, read(GOLDEN_SUBMIT), "恢复原始 golden");
|
||||
}
|
||||
|
||||
/** 只在显式点名时写 golden:默认跑测试永远不许改是非源(否则改坏了顺手把 golden 也改掉)。 */
|
||||
@Test
|
||||
@EnabledIfEnvironmentVariable(named = "SHUFU_SNAPSHOT_WRITE", matches = "true")
|
||||
void write_golden_on_demand() throws Exception {
|
||||
Files.createDirectories(GOLDEN_SUBMIT.getParentFile().toPath());
|
||||
Files.writeString(GOLDEN_SUBMIT.toPath(), runAll(), StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
+277
@@ -0,0 +1,277 @@
|
||||
package com.nanri.aiimage.modules.task.contract;
|
||||
|
||||
import com.baomidou.mybatisplus.core.MybatisConfiguration;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.nanri.aiimage.modules.task.mapper.TaskProgressSnapshotMapper;
|
||||
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
|
||||
import com.nanri.aiimage.modules.task.model.dto.TaskHeartbeatRequest;
|
||||
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
|
||||
import com.nanri.aiimage.modules.task.model.entity.TaskProgressSnapshotEntity;
|
||||
import com.nanri.aiimage.modules.task.model.vo.TaskHeartbeatVo;
|
||||
import com.nanri.aiimage.modules.task.service.TaskHeartbeatLivenessService;
|
||||
import com.nanri.aiimage.modules.task.service.TaskHeartbeatService;
|
||||
import com.nanri.aiimage.modules.task.service.TaskProgressSnapshotService;
|
||||
import com.nanri.aiimage.modules.task.spi.TaskModuleHeartbeatSpi;
|
||||
import org.apache.ibatis.builder.MapperBuilderAssistant;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* 中断上报 → 进度快照终态同步的跨模块契约(重构蓝图 Phase 0 · 1A)。
|
||||
*
|
||||
* 为什么这一格值得单独钉:心跳轴本身早被别的路钉透了——{@code TaskModuleHeartbeatSpiCoverageTest}
|
||||
* (12 支 SPI 与 moduleType 一一对上)、{@code TaskHeartbeatServiceTest}(进度随心跳转发)、
|
||||
* {@code StaleTaskHeartbeatPolicyTest}(首次心跳前的宽限)、
|
||||
* {@code TaskProgressSnapshotServiceThrottleTest}(节流与终态豁免)。
|
||||
* 但把终态写回快照的那个出口 {@code markTerminal} 在 {@code src/test} 里**一处引用都没有**,
|
||||
* 而它对应的是一起真机事故:2026-09-13 客户端重启后店铺数据采集一直显示 28094「处理中」并阻塞
|
||||
* 该工具后续任务——因为 progress/batch 读的是缓存/快照(Redis,跨实例共享、不随 JVM 重启清空),
|
||||
* DB 行已终态而快照还停在 RUNNING。Phase 2/3 把管线四段抽成公共件时,这个出口最容易被当成
|
||||
* 「顺手的小方法」漏在新契约之外,故在此钉死。
|
||||
*
|
||||
* 覆盖面:{@code markTerminal} 的幂等与「不凭空造行」、终态写完必须清节流记录(否则后续补写
|
||||
* 被自己刚写的窗口吞掉),以及 {@code markInterrupted} 两条路径(DB 现值 RUNNING/已终态自愈)
|
||||
* 都必须把终态同步到缓存与快照,且**快照写失败不得让中断接口本身失败**。
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class TerminalProgressSyncContractTest {
|
||||
|
||||
private static final Long TASK_ID = 28094L;
|
||||
private static final String MODULE_TYPE = "SHOP_DATA_CRAWL";
|
||||
|
||||
@BeforeAll
|
||||
static void initializeMybatisMetadata() {
|
||||
MapperBuilderAssistant assistant = new MapperBuilderAssistant(new MybatisConfiguration(), "");
|
||||
TableInfoHelper.initTableInfo(assistant, TaskProgressSnapshotEntity.class);
|
||||
TableInfoHelper.initTableInfo(assistant, FileTaskEntity.class);
|
||||
}
|
||||
|
||||
@Mock private TaskProgressSnapshotMapper snapshotMapper;
|
||||
@Mock private FileTaskMapper fileTaskMapper;
|
||||
|
||||
private TaskProgressSnapshotService snapshotService() {
|
||||
return new TaskProgressSnapshotService(snapshotMapper, new ObjectMapper());
|
||||
}
|
||||
|
||||
private static TaskProgressSnapshotEntity snapshot(String status, String message) {
|
||||
TaskProgressSnapshotEntity existing = new TaskProgressSnapshotEntity();
|
||||
existing.setId(77L);
|
||||
existing.setTaskId(TASK_ID);
|
||||
existing.setModuleType(MODULE_TYPE);
|
||||
existing.setStatus(status);
|
||||
existing.setTotalCount(10);
|
||||
existing.setSuccessCount(4);
|
||||
existing.setFailedCount(1);
|
||||
existing.setPendingCount(5);
|
||||
existing.setCurrentScopeKey("scope-1");
|
||||
existing.setMessage(message);
|
||||
return existing;
|
||||
}
|
||||
|
||||
// ---- markTerminal 自身 ----
|
||||
|
||||
@Test
|
||||
void markTerminalDoesNotCreateSnapshotRowWhenAbsent() {
|
||||
when(snapshotMapper.selectOne(any(LambdaQueryWrapper.class))).thenReturn(null);
|
||||
|
||||
snapshotService().markTerminal(TASK_ID, MODULE_TYPE, "FAILED", "客户端异常中断");
|
||||
|
||||
verify(snapshotMapper, never()).update(isNull(), any(LambdaUpdateWrapper.class));
|
||||
verify(snapshotMapper, never()).insert(any(TaskProgressSnapshotEntity.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void markTerminalIsIdempotentOnSameStatusAndMessage() {
|
||||
when(snapshotMapper.selectOne(any(LambdaQueryWrapper.class)))
|
||||
.thenReturn(snapshot("FAILED", "客户端异常中断"));
|
||||
|
||||
snapshotService().markTerminal(TASK_ID, MODULE_TYPE, "FAILED", "客户端异常中断");
|
||||
|
||||
verify(snapshotMapper, never()).update(isNull(), any(LambdaUpdateWrapper.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void markTerminalWritesWhenOnlyMessageChanged() {
|
||||
when(snapshotMapper.selectOne(any(LambdaQueryWrapper.class)))
|
||||
.thenReturn(snapshot("FAILED", "旧文案"));
|
||||
|
||||
snapshotService().markTerminal(TASK_ID, MODULE_TYPE, "FAILED", "客户端异常中断: crash");
|
||||
|
||||
verify(snapshotMapper).update(isNull(), any(LambdaUpdateWrapper.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void markTerminalIgnoresInvalidArguments() {
|
||||
for (Object[] args : List.of(
|
||||
new Object[]{null, MODULE_TYPE, "FAILED", "x"},
|
||||
new Object[]{0L, MODULE_TYPE, "FAILED", "x"},
|
||||
new Object[]{TASK_ID, null, "FAILED", "x"},
|
||||
new Object[]{TASK_ID, "", "FAILED", "x"},
|
||||
new Object[]{TASK_ID, MODULE_TYPE, null, "x"},
|
||||
new Object[]{TASK_ID, MODULE_TYPE, " ", "x"})) {
|
||||
snapshotService().markTerminal((Long) args[0], (String) args[1], (String) args[2], (String) args[3]);
|
||||
}
|
||||
verify(snapshotMapper, never()).update(isNull(), any(LambdaUpdateWrapper.class));
|
||||
verify(snapshotMapper, never()).selectOne(any(LambdaQueryWrapper.class));
|
||||
}
|
||||
|
||||
/**
|
||||
* 终态写完必须把节流记录一起清掉。限写窗(默认 500ms)按 {@code taskId:moduleType} 记:
|
||||
* 若终态不摘这条记录,紧随其后那笔非终态补写(纠正文案、或同一 key 复用的下一轮进度)
|
||||
* 会被自己刚写的窗口吞掉,前端就又回到「永远处理中」。
|
||||
* 本用例把三步摆在一起:进度写(顺带武装限写窗)⇒ 终态写(必须摘窗)⇒ 补写(必须还落得下去)。
|
||||
*/
|
||||
@Test
|
||||
void markTerminalClearsThrottleWindowForFollowingWrites() {
|
||||
TaskProgressSnapshotService service = snapshotService();
|
||||
when(snapshotMapper.selectOne(any(LambdaQueryWrapper.class)))
|
||||
.thenReturn(snapshot("RUNNING", "processing"));
|
||||
|
||||
service.save(TASK_ID, MODULE_TYPE, "RUNNING", 10, 4, 1, "scope-1", "第一步", null);
|
||||
service.markTerminal(TASK_ID, MODULE_TYPE, "FAILED", "客户端异常中断");
|
||||
service.save(TASK_ID, MODULE_TYPE, "RUNNING", 10, 5, 0, "scope-1", "第二步", null);
|
||||
|
||||
verify(snapshotMapper, times(3)).update(isNull(), any(LambdaUpdateWrapper.class));
|
||||
}
|
||||
|
||||
/**
|
||||
* 上一条的对照组:同样两笔进度写之间**不**插终态写,第二笔就被限写窗吞掉。
|
||||
* 没有这条对照,上一条的「三笔都落」说不清是摘窗摘对了,还是限写窗压根没生效。
|
||||
*/
|
||||
@Test
|
||||
void followUpWriteIsThrottledWhenNoTerminalSyncHappens() {
|
||||
TaskProgressSnapshotService service = snapshotService();
|
||||
when(snapshotMapper.selectOne(any(LambdaQueryWrapper.class)))
|
||||
.thenReturn(snapshot("RUNNING", "processing"));
|
||||
|
||||
service.save(TASK_ID, MODULE_TYPE, "RUNNING", 10, 4, 1, "scope-1", "第一步", null);
|
||||
service.save(TASK_ID, MODULE_TYPE, "RUNNING", 10, 5, 0, "scope-1", "第二步", null);
|
||||
|
||||
verify(snapshotMapper, times(1)).update(isNull(), any(LambdaUpdateWrapper.class));
|
||||
}
|
||||
|
||||
// ---- markInterrupted 与快照的接线 ----
|
||||
|
||||
private static final class RecordingSpi implements TaskModuleHeartbeatSpi {
|
||||
private final List<FileTaskEntity> cacheWrites = new java.util.ArrayList<>();
|
||||
|
||||
@Override
|
||||
public String moduleType() {
|
||||
return MODULE_TYPE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void touchHeartbeat(Long taskId, TaskHeartbeatRequest request) {
|
||||
// 本支只验终态同步,心跳刷新另有归属用例
|
||||
}
|
||||
|
||||
@Override
|
||||
public void saveTaskCache(FileTaskEntity task) {
|
||||
cacheWrites.add(task);
|
||||
}
|
||||
}
|
||||
|
||||
private TaskHeartbeatService heartbeatService(TaskProgressSnapshotService snapshotService, RecordingSpi spi) {
|
||||
return new TaskHeartbeatService(fileTaskMapper, snapshotService,
|
||||
mock(com.nanri.aiimage.modules.task.spi.BrandTaskHeartbeatSpi.class),
|
||||
mock(TaskHeartbeatLivenessService.class), List.of(spi));
|
||||
}
|
||||
|
||||
private static FileTaskEntity runningTask() {
|
||||
FileTaskEntity task = new FileTaskEntity();
|
||||
task.setId(TASK_ID);
|
||||
task.setModuleType(MODULE_TYPE);
|
||||
task.setStatus("RUNNING");
|
||||
task.setUserId(7L);
|
||||
return task;
|
||||
}
|
||||
|
||||
@Test
|
||||
void markInterruptedSyncsCacheAndSnapshotWhenTaskStillRunning() {
|
||||
when(fileTaskMapper.selectOne(any(LambdaQueryWrapper.class))).thenReturn(runningTask());
|
||||
when(fileTaskMapper.update(isNull(), any(LambdaUpdateWrapper.class))).thenReturn(1);
|
||||
TaskProgressSnapshotService snapshotService = mock(TaskProgressSnapshotService.class);
|
||||
RecordingSpi spi = new RecordingSpi();
|
||||
|
||||
TaskHeartbeatVo vo = heartbeatService(snapshotService, spi).markInterrupted(TASK_ID, "客户端崩溃重启");
|
||||
|
||||
assertFalse(vo.isAlive());
|
||||
assertEquals("FAILED", vo.getStatus());
|
||||
ArgumentCaptor<String> message = ArgumentCaptor.forClass(String.class);
|
||||
verify(snapshotService).markTerminal(eq(TASK_ID), eq(MODULE_TYPE), eq("FAILED"), message.capture());
|
||||
assertEquals("客户端异常中断: 客户端崩溃重启", message.getValue());
|
||||
assertEquals(1, spi.cacheWrites.size(), "模块缓存也得同步终态,否则读缓存的那侧仍是 RUNNING");
|
||||
assertEquals("FAILED", spi.cacheWrites.get(0).getStatus());
|
||||
}
|
||||
|
||||
/** DB 已是终态(重复上报)时仍要按 DB 现值自愈刷一遍快照——历史遗留的旧缓存就是在这儿卡住前端的。 */
|
||||
@Test
|
||||
void markInterruptedHealsStaleSnapshotWhenTaskAlreadyTerminal() {
|
||||
FileTaskEntity terminal = runningTask();
|
||||
terminal.setStatus("CANCELLED");
|
||||
terminal.setErrorMessage("用户取消");
|
||||
when(fileTaskMapper.selectOne(any(LambdaQueryWrapper.class))).thenReturn(terminal);
|
||||
when(fileTaskMapper.update(isNull(), any(LambdaUpdateWrapper.class))).thenReturn(0);
|
||||
TaskProgressSnapshotService snapshotService = mock(TaskProgressSnapshotService.class);
|
||||
|
||||
TaskHeartbeatVo vo = heartbeatService(snapshotService, new RecordingSpi())
|
||||
.markInterrupted(TASK_ID, "重复上报");
|
||||
|
||||
assertFalse(vo.isAlive());
|
||||
assertEquals("CANCELLED", vo.getStatus());
|
||||
verify(snapshotService, times(1)).markTerminal(TASK_ID, MODULE_TYPE, "CANCELLED", "用户取消");
|
||||
}
|
||||
|
||||
/** 快照/缓存写失败只该告警:中断接口本身的成功语义不能被它拖下水。 */
|
||||
@Test
|
||||
void markInterruptedStillSucceedsWhenSnapshotWriteFails() {
|
||||
when(fileTaskMapper.selectOne(any(LambdaQueryWrapper.class))).thenReturn(runningTask());
|
||||
when(fileTaskMapper.update(isNull(), any(LambdaUpdateWrapper.class))).thenReturn(1);
|
||||
TaskProgressSnapshotService snapshotService = mock(TaskProgressSnapshotService.class);
|
||||
doThrow(new IllegalStateException("redis down"))
|
||||
.when(snapshotService).markTerminal(any(), any(), any(), any());
|
||||
|
||||
TaskHeartbeatVo vo = heartbeatService(snapshotService, new RecordingSpi())
|
||||
.markInterrupted(TASK_ID, "客户端崩溃重启");
|
||||
|
||||
assertFalse(vo.isAlive());
|
||||
assertEquals("FAILED", vo.getStatus(), "快照写失败不得让中断上报变成失败");
|
||||
}
|
||||
|
||||
@Test
|
||||
void markInterruptedIgnoresInvalidTaskId() {
|
||||
TaskProgressSnapshotService snapshotService = mock(TaskProgressSnapshotService.class);
|
||||
|
||||
// List.of 不收 null,非法值只能走 Arrays.asList
|
||||
for (Long taskId : java.util.Arrays.asList(null, 0L, -1L)) {
|
||||
TaskHeartbeatVo vo = heartbeatService(snapshotService, new RecordingSpi()).markInterrupted(taskId, "x");
|
||||
assertFalse(vo.isAlive(), "非法 taskId 也必须回「不活着」,不能让客户端以为任务还在跑");
|
||||
}
|
||||
verify(snapshotService, never()).markTerminal(any(), any(), any(), any());
|
||||
verify(fileTaskMapper, never()).selectOne(any(LambdaQueryWrapper.class));
|
||||
}
|
||||
}
|
||||
+17
@@ -77,4 +77,21 @@ class AppearancePatentResultFileJobHandlerTest {
|
||||
handler.cleanup(null);
|
||||
org.mockito.Mockito.verify(appearancePatentTaskService).cleanupResultFileJob(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void fallbackAssembleDelegates() {
|
||||
// 重试耗尽(含 WAIT_LLM 停放被 stuck 棘轮判死)时委托 Service 出部分结果文件
|
||||
TaskFileJobEntity job = new TaskFileJobEntity();
|
||||
when(appearancePatentTaskService.fallbackAssembleResultFile(job)).thenReturn(true);
|
||||
assertTrue(handler.fallbackAssembleOnFailure(job, "文件生成任务运行超时,已达到最大重试次数"),
|
||||
"兜底产出可下载结果时返回 true");
|
||||
}
|
||||
|
||||
@Test
|
||||
void fallbackAssembleFailureReturnsFalse() {
|
||||
TaskFileJobEntity job = new TaskFileJobEntity();
|
||||
when(appearancePatentTaskService.fallbackAssembleResultFile(job)).thenReturn(false);
|
||||
assertFalse(handler.fallbackAssembleOnFailure(job, "结果文件生成失败"),
|
||||
"兜底也失败时返回 false,不影响作业已终态失败的事实");
|
||||
}
|
||||
}
|
||||
|
||||
+83
-2
@@ -5,7 +5,9 @@ import com.baomidou.mybatisplus.core.conditions.Wrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
||||
import com.nanri.aiimage.common.service.DistributedJobLockService;
|
||||
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.spi.BrandTaskStaleRepairSpi;
|
||||
import org.apache.ibatis.builder.MapperBuilderAssistant;
|
||||
@@ -39,16 +41,20 @@ import static org.mockito.Mockito.when;
|
||||
class StaleTaskRepairServiceTest {
|
||||
|
||||
private final FileTaskMapper fileTaskMapper = mock(FileTaskMapper.class);
|
||||
private final FileResultMapper fileResultMapper = mock(FileResultMapper.class);
|
||||
private final TaskFileJobService taskFileJobService = mock(TaskFileJobService.class);
|
||||
private final BrandTaskStaleRepairSpi brandTaskStaleRepairSpi = mock(BrandTaskStaleRepairSpi.class);
|
||||
private final DistributedJobLockService distributedJobLockService = mock(DistributedJobLockService.class);
|
||||
private final StaleTaskHeartbeatPolicy staleTaskHeartbeatPolicy = mock(StaleTaskHeartbeatPolicy.class);
|
||||
private final StaleTaskRepairService service = new StaleTaskRepairService(
|
||||
fileTaskMapper, brandTaskStaleRepairSpi, distributedJobLockService, staleTaskHeartbeatPolicy);
|
||||
fileTaskMapper, fileResultMapper, taskFileJobService, brandTaskStaleRepairSpi, distributedJobLockService,
|
||||
staleTaskHeartbeatPolicy);
|
||||
|
||||
@BeforeEach
|
||||
void initTableInfo() {
|
||||
// LambdaWrapper 需要实体列缓存,单测无 Spring/MyBatis 上下文,手动初始化
|
||||
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""), FileTaskEntity.class);
|
||||
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""), FileResultEntity.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -96,9 +102,55 @@ class StaleTaskRepairServiceTest {
|
||||
|
||||
ReflectionTestUtils.invokeMethod(service, "repairFileTaskStaleIdle");
|
||||
ReflectionTestUtils.invokeMethod(service, "repairFileTaskStaleScheduled");
|
||||
ReflectionTestUtils.invokeMethod(service, "repairFileTaskStaleRunning");
|
||||
|
||||
verify(fileTaskMapper, never()).update(any(), any());
|
||||
verify(fileResultMapper, never()).update(any(), any());
|
||||
verifyNoMoreInteractions(brandTaskStaleRepairSpi);
|
||||
verify(taskFileJobService, never()).failUnfinishedJobs(any(), any());
|
||||
}
|
||||
|
||||
// 2026-10-16 任务 31060:客户端只回传 51/510 个分片后被本方法判死,但 biz_file_result.success
|
||||
// 是 `NOT NULL DEFAULT 1` 的列、只有正常收尾才回写,于是历史列表拿这一位显示「已完成」,
|
||||
// 而结果文件从未存在(下载按钮的判据 result_file_url 为空)。判死必须同时把结果行改口。
|
||||
@Test
|
||||
void 心跳判死必须同步把无结果文件的结果行改判失败() {
|
||||
when(fileTaskMapper.selectList(any())).thenReturn(List.of(task(31060L, "RUNNING")));
|
||||
when(fileTaskMapper.update(isNull(), any())).thenReturn(1);
|
||||
when(fileResultMapper.update(isNull(), any())).thenReturn(1);
|
||||
|
||||
ReflectionTestUtils.invokeMethod(service, "repairFileTaskStaleRunning");
|
||||
|
||||
ArgumentCaptor<LambdaUpdateWrapper<FileResultEntity>> captor = resultUpdateCaptor();
|
||||
verify(fileResultMapper).update(isNull(), captor.capture());
|
||||
LambdaUpdateWrapper<FileResultEntity> wrapper = captor.getValue();
|
||||
String set = wrapper.getSqlSet();
|
||||
assertTrue(set.contains("success"), "结果行的 success 位必须被改写,否则前端仍读到默认值 1");
|
||||
assertTrue(set.contains("error_message"), "判死原因要留痕到结果行,页面才说得出为什么失败");
|
||||
assertFalse(set.contains("updated_at"),
|
||||
"updated_at 由数据库维护,显式写会冻结结果行的版本信号(见 FileResultEntity 注释)");
|
||||
Map<String, Object> params = paramsOf(wrapper);
|
||||
assertTrue(params.containsValue(0), "success 写 0");
|
||||
assertTrue(containsMessage(params, "心跳超时"), "留痕文案与任务行同源");
|
||||
|
||||
String where = wrapper.getSqlSegment();
|
||||
assertTrue(where.contains("result_file_url"),
|
||||
"只改没有结果文件的行:文件已生成的任务不许被抹掉部分交付提示");
|
||||
assertTrue(where.contains("task_id"), "按本次判死的任务圈定");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 心跳判死必须终结仍_RUNNING_的组装作业() {
|
||||
when(fileTaskMapper.selectList(any())).thenReturn(List.of(task(31060L, "RUNNING")));
|
||||
when(fileTaskMapper.update(isNull(), any())).thenReturn(1);
|
||||
|
||||
ReflectionTestUtils.invokeMethod(service, "repairFileTaskStaleRunning");
|
||||
|
||||
ArgumentCaptor<List<Long>> ids = listCaptor();
|
||||
ArgumentCaptor<String> reason = ArgumentCaptor.forClass(String.class);
|
||||
verify(taskFileJobService).failUnfinishedJobs(ids.capture(), reason.capture());
|
||||
assertEquals(List.of(31060L), ids.getValue());
|
||||
assertTrue(reason.getValue().contains("心跳超时"), "作业行的判死原因与任务行同源");
|
||||
}
|
||||
|
||||
// 2026-10-17 实录:任务一被认领就记 RUNNING,而客户端要等执行器真开始跑才发心跳(同店占用 /
|
||||
@@ -117,6 +169,17 @@ class StaleTaskRepairServiceTest {
|
||||
verify(fileTaskMapper, never()).update(isNull(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void 未被领取判死同样要回写结果行并终结作业() {
|
||||
when(fileTaskMapper.selectList(any())).thenReturn(List.of(task(31176L, "PENDING")));
|
||||
when(fileTaskMapper.update(isNull(), any())).thenReturn(1);
|
||||
|
||||
ReflectionTestUtils.invokeMethod(service, "repairFileTaskStaleIdle");
|
||||
|
||||
verify(fileResultMapper).update(isNull(), any());
|
||||
verify(taskFileJobService).failUnfinishedJobs(eq(List.of(31176L)), any());
|
||||
}
|
||||
|
||||
private Map<String, Object> selectParams() {
|
||||
ArgumentCaptor<Wrapper<FileTaskEntity>> captor = wrapperCaptor();
|
||||
verify(fileTaskMapper).selectList(captor.capture());
|
||||
@@ -134,12 +197,22 @@ class StaleTaskRepairServiceTest {
|
||||
return ArgumentCaptor.forClass(Wrapper.class);
|
||||
}
|
||||
|
||||
@SuppressWarnings({"rawtypes", "unchecked"})
|
||||
private static ArgumentCaptor<LambdaUpdateWrapper<FileResultEntity>> resultUpdateCaptor() {
|
||||
return ArgumentCaptor.forClass((Class) LambdaUpdateWrapper.class);
|
||||
}
|
||||
|
||||
@SuppressWarnings({"rawtypes", "unchecked"})
|
||||
private static ArgumentCaptor<List<Long>> listCaptor() {
|
||||
return ArgumentCaptor.forClass((Class) List.class);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取 wrapper 参数容器:用来断言判死谓词与写入值。
|
||||
* 注意 MyBatis-Plus 是在生成 SQL 片段时才把参数写进 paramNameValuePairs,故先触发一次。
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
private static Map<String, Object> paramsOf(Wrapper<FileTaskEntity> wrapper) {
|
||||
private static Map<String, Object> paramsOf(Wrapper<?> wrapper) {
|
||||
wrapper.getSqlSegment();
|
||||
if (wrapper instanceof LambdaUpdateWrapper) {
|
||||
((LambdaUpdateWrapper<FileTaskEntity>) wrapper).getSqlSet();
|
||||
@@ -164,4 +237,12 @@ class StaleTaskRepairServiceTest {
|
||||
task.setScheduledAt(LocalDateTime.now().plusHours(3));
|
||||
return task;
|
||||
}
|
||||
|
||||
private static FileTaskEntity task(Long id, String status) {
|
||||
FileTaskEntity task = task(id);
|
||||
task.setModuleType("SIMILAR_ASIN");
|
||||
task.setStatus(status);
|
||||
task.setScheduledAt(null);
|
||||
return task;
|
||||
}
|
||||
}
|
||||
|
||||
+39
@@ -261,6 +261,45 @@ class TaskFileJobServiceTest {
|
||||
verify(applicationEventPublisher, times(2)).publishEvent(any(Object.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void 父任务判死后未结束的组装作业必须被终结而不是被无限defer() {
|
||||
when(taskFileJobMapper.update(isNull(), any(LambdaUpdateWrapper.class))).thenReturn(1);
|
||||
TaskFileJobService service = new TaskFileJobService(taskFileJobMapper, applicationEventPublisher);
|
||||
|
||||
int failed = service.failUnfinishedJobs(List.of(31060L), "任务心跳超时,已自动失败");
|
||||
|
||||
assertEquals(1, failed, "返回值即被终结的作业数,修复日志要靠它");
|
||||
ArgumentCaptor<LambdaUpdateWrapper<TaskFileJobEntity>> update = updateCaptor();
|
||||
verify(taskFileJobMapper).update(isNull(), update.capture());
|
||||
LambdaUpdateWrapper<TaskFileJobEntity> wrapper = update.getValue();
|
||||
String where = wrapper.getSqlSegment();
|
||||
assertTrue(where.contains("task_id"), "必须按父任务圈定作业");
|
||||
assertTrue(where.contains("status"), "必须按作业状态圈定");
|
||||
assertFalse(where.contains("SUCCESS"), "已成功的作业不许被改口");
|
||||
|
||||
String set = wrapper.getSqlSet();
|
||||
assertTrue(set.contains("retry_count"),
|
||||
"重试必须拉满:FAILED 而 retry_count=0 的作业仍会被 listRunnableJobs 捞起重试");
|
||||
assertTrue(set.contains("terminal_callback_at"),
|
||||
"必须打终态回调标记,否则失败收尾扫描会再去回调已被判死的父任务");
|
||||
assertTrue(set.contains("finished_at"), "终态作业要有结束时间");
|
||||
|
||||
var params = wrapper.getParamNameValuePairs();
|
||||
assertTrue(params.containsValue("FAILED"), "作业状态写 FAILED");
|
||||
assertTrue(params.containsValue(TaskFileJobService.MAX_RETRY_COUNT), "重试次数拉满到上限");
|
||||
assertTrue(params.values().stream().anyMatch(value -> value instanceof String text && text.contains("心跳超时")),
|
||||
"判死原因要落到作业行,否则排查时只知道它红了");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 空任务清单不去碰作业表() {
|
||||
TaskFileJobService service = new TaskFileJobService(taskFileJobMapper, applicationEventPublisher);
|
||||
|
||||
assertEquals(0, service.failUnfinishedJobs(List.of(), "任务心跳超时,已自动失败"));
|
||||
|
||||
verify(taskFileJobMapper, never()).update(any(), any());
|
||||
}
|
||||
|
||||
private void assertUpdateContains(int nextRetry, LocalDateTime updatedAt) {
|
||||
ArgumentCaptor<LambdaUpdateWrapper<TaskFileJobEntity>> update = updateCaptor();
|
||||
verify(taskFileJobMapper).update(isNull(), update.capture());
|
||||
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package com.nanri.aiimage.modules.task.service;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* 模块归属谓词出口的语义(2026-10-18,随 31302/31354 兜底收口补位)。
|
||||
*
|
||||
* <p>TaskLifecycleDebtRatchetTest 钉的是「散在各页的手抄遍数只许降」;这里钉出口本身的行为:
|
||||
* expected 为 null 视为不归属(防御空模块标识漏判成「谁都能读」)。
|
||||
*/
|
||||
class TaskFinalizeSupportTest {
|
||||
|
||||
@Test
|
||||
void matchingModuleTypeBelongs() {
|
||||
assertTrue(TaskFinalizeSupport.belongsToModule("APPEARANCE_PATENT", "APPEARANCE_PATENT"),
|
||||
"模块标识一致即归属");
|
||||
}
|
||||
|
||||
@Test
|
||||
void mismatchedOrMissingRecordModuleTypeDoesNotBelong() {
|
||||
assertFalse(TaskFinalizeSupport.belongsToModule("APPEARANCE_PATENT", "PRICE_TRACK"),
|
||||
"模块标识不一致不归属");
|
||||
assertFalse(TaskFinalizeSupport.belongsToModule("APPEARANCE_PATENT", null),
|
||||
"记录缺模块标识不归属");
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullExpectedModuleTypeNeverOwnsAnything() {
|
||||
assertFalse(TaskFinalizeSupport.belongsToModule(null, "APPEARANCE_PATENT"),
|
||||
"期望标识为 null 不能判成归属——否则守卫静默失效");
|
||||
}
|
||||
}
|
||||
+4
-1
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.task.service;
|
||||
|
||||
import com.nanri.aiimage.config.AppearancePatentProperties;
|
||||
import com.nanri.aiimage.config.SimilarAsinProperties;
|
||||
import com.nanri.aiimage.modules.appearancepatent.service.AppearancePatentTaskCacheService;
|
||||
import com.nanri.aiimage.modules.appearancepatent.service.AppearancePatentTaskHeartbeatSpi;
|
||||
@@ -46,7 +47,9 @@ class TaskModuleHeartbeatSpiCoverageTest {
|
||||
|
||||
private static Map<String, TaskModuleHeartbeatSpi> implementationsByModuleType() {
|
||||
Map<String, TaskModuleHeartbeatSpi> impls = new LinkedHashMap<>();
|
||||
register(impls, new AppearancePatentTaskHeartbeatSpi(mock(AppearancePatentTaskCacheService.class)));
|
||||
register(impls, new AppearancePatentTaskHeartbeatSpi(
|
||||
mock(AppearancePatentTaskCacheService.class), mock(TaskFileJobService.class),
|
||||
mock(AppearancePatentProperties.class)));
|
||||
register(impls, new CollectDataTaskHeartbeatSpi(mock(CollectDataService.class)));
|
||||
register(impls, new DeleteBrandTaskHeartbeatSpi(mock(DeleteBrandTaskCacheService.class)));
|
||||
register(impls, new PatrolDeleteTaskHeartbeatSpi(mock(PatrolDeleteTaskCacheService.class)));
|
||||
|
||||
+472
@@ -0,0 +1,472 @@
|
||||
package com.nanri.aiimage.modules.task.service.pipeline;
|
||||
|
||||
import com.baomidou.mybatisplus.core.MybatisConfiguration;
|
||||
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
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.model.entity.FileResultEntity;
|
||||
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
|
||||
import com.nanri.aiimage.modules.task.service.AbstractModuleTaskCacheService;
|
||||
import com.nanri.aiimage.modules.task.service.TaskDistributedLockService;
|
||||
import com.nanri.aiimage.modules.task.service.TaskFileJobService;
|
||||
import org.apache.ibatis.builder.MapperBuilderAssistant;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
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.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* 任务管线底座的行为契约(Phase 2 新增公共件,AGENTS.md §3 阶段 3 第 2 条要求覆盖正常/边界/异常)。
|
||||
*
|
||||
* <p>这些用例锁的不是「基类能跑」,而是<b>Phase 3 迁移时七支必须换得上的那截形状</b>:
|
||||
* 每条断言旁边注着它抄自哪支现网代码的哪一行。任何一条改了,就是在替现网做决定。
|
||||
*/
|
||||
class AbstractFileTaskPipelineTest {
|
||||
|
||||
private static final String MODULE_TYPE = "PIPE_TEST";
|
||||
|
||||
private FileTaskMapper fileTaskMapper;
|
||||
private FileResultMapper fileResultMapper;
|
||||
private TaskDistributedLockService lockService;
|
||||
private TaskFileJobService jobService;
|
||||
private OssStorageService ossStorageService;
|
||||
private TestPipeline pipeline;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
// LambdaQueryWrapper 的列名解析吃 lambda 缓存,未预置会在 getTargetSql() 处炸(仓内 136 支同此套路)
|
||||
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""),
|
||||
FileResultEntity.class);
|
||||
fileTaskMapper = mock(FileTaskMapper.class);
|
||||
fileResultMapper = mock(FileResultMapper.class);
|
||||
lockService = mock(TaskDistributedLockService.class);
|
||||
jobService = mock(TaskFileJobService.class);
|
||||
ossStorageService = mock(OssStorageService.class);
|
||||
pipeline = new TestPipeline(fileTaskMapper, fileResultMapper, lockService, jobService, ossStorageService);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// 段 1:解析建单
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void taskHeaderCarriesTheSevenModuleCommonFieldsVerbatim() {
|
||||
FileTaskEntity task = pipeline.newTaskHeader("RUNNING", "PYTHON_QUEUE", 42L, " dev-1 ", 3);
|
||||
|
||||
assertTrue(task.getTaskNo().startsWith(MODULE_TYPE + "-"), "taskNo 必须是 <moduleType>-<雪花>");
|
||||
assertEquals(MODULE_TYPE, task.getModuleType());
|
||||
assertEquals("PYTHON_QUEUE", task.getTaskMode());
|
||||
assertEquals("RUNNING", task.getStatus());
|
||||
assertEquals(3, task.getSourceFileCount());
|
||||
assertEquals("user:42", task.getCreatedBy());
|
||||
assertEquals(42L, task.getUserId());
|
||||
assertEquals("dev-1", task.getDeviceId(), "deviceId 走 trim(AdminAuthSupport.normalizeDeviceId)");
|
||||
assertNotNull(task.getCreatedAt());
|
||||
assertSame(task.getCreatedAt(), task.getUpdatedAt());
|
||||
}
|
||||
|
||||
@Test
|
||||
void blankDeviceIdStaysUnrecordedRatherThanEmptyString() {
|
||||
assertNull(pipeline.newTaskHeader("PENDING", "IMMEDIATE", 1L, " ", 0).getDeviceId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void taskHeaderDoesNotInventDefaultsForModuleDecidedColumns() {
|
||||
FileTaskEntity task = pipeline.newTaskHeader("SCHEDULED", "PYTHON_QUEUE", 7L, "dev", 1);
|
||||
// ShopMatch 的 scheduledAt、Publish 的 finishedAt/errorMessage、各支 requestJson/resultJson
|
||||
// 都由调用方自己 set:底座一设默认值,迁移时就会把「没写」变成「写了个错的」。
|
||||
assertNull(task.getScheduledAt());
|
||||
assertNull(task.getFinishedAt());
|
||||
assertNull(task.getErrorMessage());
|
||||
assertNull(task.getRequestJson());
|
||||
assertNull(task.getResultJson());
|
||||
// 两个计数列同理:DeleteBrand 建单时留 NULL、循环后才回填(:146-157 → :268-278),
|
||||
// Publish 写的是真实失败数(:1061)——底座一-default 0 就把「还没统计」偷换成「零成功零失败」。
|
||||
assertNull(task.getSuccessFileCount());
|
||||
assertNull(task.getFailedFileCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void illegalUserIdIsRejectedBeforeAnyRowIsBuilt() {
|
||||
for (Long bad : new Long[]{null, 0L, -1L}) {
|
||||
BusinessException ex = assertThrows(BusinessException.class,
|
||||
() -> pipeline.newTaskHeader("RUNNING", "PYTHON_QUEUE", bad, "dev", 1));
|
||||
assertEquals("user_id 不合法", ex.getMessage(), "七支文案逐字相同,不许改");
|
||||
}
|
||||
verifyNoInteractions(fileTaskMapper, fileResultMapper);
|
||||
}
|
||||
|
||||
@Test
|
||||
void insertTaskWritesOnceAndReturnsTheSameEntityForIdBackfill() {
|
||||
FileTaskEntity task = pipeline.newTaskHeader("RUNNING", "PYTHON_QUEUE", 9L, "dev", 1);
|
||||
assertSame(task, pipeline.insertTask(task));
|
||||
verify(fileTaskMapper, times(1)).insert(task);
|
||||
}
|
||||
|
||||
@Test
|
||||
void explicitCreatedAtIsStampedVerbatimOnBothColumns() {
|
||||
// ShopMatch:462→:484-485 用的是 now()=LocalDateTime.now(Asia/Shanghai),
|
||||
// 底座默认那套是 JVM 时区——首迁实测出来的缺件,时刻只能由被迁支交进来。
|
||||
java.time.LocalDateTime businessNow = java.time.LocalDateTime.of(2026, 10, 18, 9, 5, 3);
|
||||
FileTaskEntity task = pipeline.newTaskHeader("SCHEDULED", "PYTHON_QUEUE", 7L, "dev", 2, businessNow);
|
||||
|
||||
assertEquals(businessNow, task.getCreatedAt());
|
||||
assertEquals(businessNow, task.getUpdatedAt(), "两列同一个时刻(现网就复用同一枚 now)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void fiveArgHeaderStillFallsBackToTheWallClock() {
|
||||
java.time.LocalDateTime before = java.time.LocalDateTime.now();
|
||||
FileTaskEntity task = pipeline.newTaskHeader("RUNNING", "PYTHON_QUEUE", 7L, "dev", 1);
|
||||
assertTrue(!task.getCreatedAt().isBefore(before), "五参版仍是默认时区的 now()(PriceTrack:512-513 那一派)");
|
||||
assertTrue(!task.getCreatedAt().isAfter(before.plusMinutes(1)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void scopeRowsShareOneInstantWhenTheBranchPassesIt() {
|
||||
java.time.LocalDateTime businessNow = java.time.LocalDateTime.of(2026, 10, 18, 9, 5, 3);
|
||||
FileResultEntity first = pipeline.newScopeRow(1L, 9L, "a", "ua", null, 0, businessNow);
|
||||
FileResultEntity second = pipeline.newScopeRow(1L, 9L, "b", "ub", null, 0, businessNow);
|
||||
|
||||
assertEquals(businessNow, first.getCreatedAt());
|
||||
assertEquals(first.getCreatedAt(), second.getCreatedAt(),
|
||||
"ShopMatch:503 把建单那一枚 now 复用给每一行,逐行各取一次就不是同一件事");
|
||||
}
|
||||
|
||||
@Test
|
||||
void scopeRowKeepsNullableColumnsUntouched() {
|
||||
// ShopDataCrawl/ShopMatch 建单时不写 rowCount,AppearancePatent 不写 success:
|
||||
// 底座一归一,结果行的「未开始」就被读成「0 行且失败」。
|
||||
FileResultEntity row = pipeline.newScopeRow(100L, 9L, "shop-a", "shop-id-1", null, null);
|
||||
assertNull(row.getRowCount());
|
||||
assertNull(row.getSuccess());
|
||||
assertEquals(100L, row.getTaskId());
|
||||
assertEquals(MODULE_TYPE, row.getModuleType());
|
||||
assertEquals("shop-a", row.getSourceFilename(), "sourceFilename 是回传侧的作用域匹配键");
|
||||
assertEquals("shop-id-1", row.getSourceFileUrl());
|
||||
assertEquals(9L, row.getUserId());
|
||||
assertNotNull(row.getCreatedAt());
|
||||
|
||||
assertEquals(-1, pipeline.newScopeRow(1L, 1L, "s", "u", null, -1).getSuccess(),
|
||||
"ShopDataCrawl 的 RESULT_PENDING=-1 必须原样传下去");
|
||||
}
|
||||
|
||||
@Test
|
||||
void scopeRowsAreInsertedOneByOneNotBatched() {
|
||||
List<FileResultEntity> rows = List.of(
|
||||
pipeline.newScopeRow(1L, 1L, "a", "ua", 10, 0),
|
||||
pipeline.newScopeRow(1L, 1L, "b", "ub", 20, 0));
|
||||
|
||||
List<FileResultEntity> saved = pipeline.insertScopeRows(rows);
|
||||
|
||||
assertEquals(2, saved.size());
|
||||
assertSame(rows.get(0), saved.get(0));
|
||||
assertSame(rows.get(1), saved.get(1));
|
||||
verify(fileResultMapper, times(2)).insert(any(FileResultEntity.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptyScopeRowListInsertsNothing() {
|
||||
assertTrue(pipeline.insertScopeRows(List.of()).isEmpty());
|
||||
verify(fileResultMapper, never()).insert(any(FileResultEntity.class));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// 段 3:回传准入
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void illegalTaskIdRejectedWithoutTouchingAnyCollaborator() {
|
||||
for (Long bad : new Long[]{null, 0L, -5L}) {
|
||||
assertEquals("taskId 不合法",
|
||||
assertThrows(BusinessException.class, () -> pipeline.requireTaskId(bad)).getMessage());
|
||||
}
|
||||
verifyNoInteractions(fileTaskMapper, fileResultMapper, lockService, jobService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingTaskOrForeignModuleTypeIsBothReportedAsAbsent() {
|
||||
pipeline.loadedTask = null;
|
||||
assertAdmissionFails("任务不存在");
|
||||
|
||||
FileTaskEntity foreign = new FileTaskEntity();
|
||||
foreign.setModuleType("SOMETHING_ELSE");
|
||||
foreign.setStatus("RUNNING");
|
||||
pipeline.loadedTask = foreign;
|
||||
assertAdmissionFails("任务不存在");
|
||||
}
|
||||
|
||||
@Test
|
||||
void terminalTaskRejectionKeepsTheTwoWireProtocolShapes() {
|
||||
for (String terminal : List.of("SUCCESS", "FAILED")) {
|
||||
pipeline.loadedTask = taskWithStatus(terminal);
|
||||
|
||||
BusinessException idempotent = assertThrows(BusinessException.class,
|
||||
() -> pipeline.admitSubmission(1L, AbstractFileTaskPipeline.TerminalRejection.IDEMPOTENT, null));
|
||||
assertEquals(40901, idempotent.getCode(),
|
||||
"40901 → HTTP 200 + success=true,Python 停止重试(BusinessCodes 已拆码,不可含糊)");
|
||||
assertEquals("任务已结束,拒绝重复提交", idempotent.getMessage());
|
||||
|
||||
BusinessException error = assertThrows(BusinessException.class,
|
||||
() -> pipeline.admitSubmission(1L, AbstractFileTaskPipeline.TerminalRejection.ERROR, null));
|
||||
assertNull(error.getCode(), "无 code 的拒绝会让 success=false,与 IDEMPOTENT 是两件事");
|
||||
assertEquals("任务已结束,拒绝重复提交", error.getMessage());
|
||||
assertEquals(terminal, pipeline.loadedTask.getStatus());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void runningTaskIsAdmittedAndHeartbeatOnlyWhenTheModuleHasACacheService() {
|
||||
pipeline.loadedTask = taskWithStatus("RUNNING");
|
||||
|
||||
pipeline.admitSubmission(1L, AbstractFileTaskPipeline.TerminalRejection.IDEMPOTENT, null);
|
||||
assertNull(pipeline.ownershipOperation, "ownershipOperation 传 null 即不校验归属(四支现网如此)");
|
||||
assertTrue(pipeline.cacheRequested, "准入必须真的问一次缓存服务,否则这个钩子是死代码");
|
||||
verifyNoInteractions(ossStorageService, jobService);
|
||||
|
||||
pipeline.cacheServiceHolder = mock(AbstractModuleTaskCacheService.class);
|
||||
pipeline.admitSubmission(1L, AbstractFileTaskPipeline.TerminalRejection.IDEMPOTENT, null);
|
||||
verify(pipeline.cacheServiceHolder, times(1)).touchTaskHeartbeat(1L);
|
||||
|
||||
pipeline.cacheServiceHolder = mock(AbstractModuleTaskCacheService.class);
|
||||
pipeline.admitSubmission(2L, AbstractFileTaskPipeline.TerminalRejection.ERROR, "submit shop data crawl result");
|
||||
assertEquals("submit shop data crawl result", pipeline.ownershipOperation,
|
||||
"AP/Publish/SDC 三支要归属校验,钩子必须真被走到");
|
||||
}
|
||||
|
||||
@Test
|
||||
void lockContentionRejectsSubmissionWithTaskBusyCode() {
|
||||
when(lockService.acquire(anyString(), anyLong())).thenReturn(null);
|
||||
BusinessException ex = assertThrows(BusinessException.class,
|
||||
() -> pipeline.acquireSubmissionLockOrThrow(1L, "shop-match"));
|
||||
assertEquals(40902, ex.getCode(), "锁竞争必须 success=false 让调用方重试,不能静默降级");
|
||||
assertEquals("任务正在处理中,请稍后再试", ex.getMessage());
|
||||
|
||||
when(lockService.acquire(anyString(), anyLong(), anyLong())).thenReturn(null);
|
||||
assertEquals(40902, assertThrows(BusinessException.class,
|
||||
() -> pipeline.acquireSubmissionLockOrThrow(1L, "shop-match", 5_000L)).getCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void lockHandleIsHandedBackWhenAcquired() {
|
||||
TaskDistributedLockService.LockHandle handle = mock(TaskDistributedLockService.LockHandle.class);
|
||||
when(lockService.acquire(MODULE_TYPE, 1L)).thenReturn(handle);
|
||||
assertSame(handle, pipeline.acquireSubmissionLockOrThrow(1L, "shop-match"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void scopeRowsAreListedForThisTaskAndModuleOrderedById() {
|
||||
List<FileResultEntity> rows = List.of(new FileResultEntity(), new FileResultEntity());
|
||||
when(fileResultMapper.selectList(any())).thenReturn(rows);
|
||||
|
||||
assertSame(rows, pipeline.listScopeRows(77L));
|
||||
|
||||
// 光看返回值抓不到「读了别的任务/别的模块的行」——mock 的 selectList 是无条件回桩的,
|
||||
// 所以必须把 wrapper 抓出来钉住条件列与值(仓内既有惯例)。
|
||||
ArgumentCaptor<com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<FileResultEntity>> captor =
|
||||
ArgumentCaptor.forClass(
|
||||
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper.class);
|
||||
verify(fileResultMapper).selectList(captor.capture());
|
||||
captor.getValue().getSqlSegment(); // MP 惯例:先求值一次才铺出参数
|
||||
String sql = captor.getValue().getSqlSegment();
|
||||
assertTrue(sql.contains("task_id") && sql.contains("module_type"),
|
||||
"条件必须双卡 taskId+moduleType,少了后者就会把别的模块的结果行读进来:" + sql);
|
||||
assertTrue(captor.getValue().getParamNameValuePairs().containsValue(77L));
|
||||
assertTrue(captor.getValue().getParamNameValuePairs().containsValue(MODULE_TYPE));
|
||||
assertTrue(sql.toLowerCase().contains("order by"),
|
||||
"回传收尾判定依赖行序,丢了顺序就是行为变更:" + sql);
|
||||
}
|
||||
|
||||
@Test
|
||||
void resultAssemblyJobIsEnqueuedUnderTheModuleType() {
|
||||
pipeline.enqueueResultAssembly(5L, 6L, "task:5:owner:i-1");
|
||||
verify(jobService).enqueueAssembleResult(5L, MODULE_TYPE, 6L, "task:5:owner:i-1");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// 段 4:出结果
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void publishResultFileUploadsThenWritesTheSixColumns(@TempDir java.nio.file.Path dir) throws IOException {
|
||||
File xlsx = write(dir, "a.xlsx", "hello");
|
||||
FileResultEntity row = resultRowWithFailure("上一轮有部分行没跑完");
|
||||
when(ossStorageService.uploadResultFile(xlsx, MODULE_TYPE)).thenReturn("object/key/a");
|
||||
|
||||
pipeline.publishResultFile(row, xlsx, "店铺A.xlsx", "application/vnd.ms-excel", 12, false);
|
||||
|
||||
verify(ossStorageService).uploadResultFile(xlsx, MODULE_TYPE);
|
||||
assertEquals("店铺A.xlsx", row.getResultFilename());
|
||||
assertEquals("object/key/a", row.getResultFileUrl());
|
||||
assertEquals(xlsx.length(), row.getResultFileSize(), "文件大小取真实上传件字节数");
|
||||
assertEquals("application/vnd.ms-excel", row.getResultContentType());
|
||||
assertEquals(12, row.getRowCount());
|
||||
assertEquals(1, row.getSuccess());
|
||||
assertNull(row.getErrorMessage(), "非 preserveFailure 必须清掉旧失败原因(六支现网无条件 success=1)");
|
||||
verify(fileResultMapper).updateById(row);
|
||||
}
|
||||
|
||||
@Test
|
||||
void preserveFailureKeepsTheRowVisiblyFailedWhileStillAttachingTheFile(@TempDir java.nio.file.Path dir)
|
||||
throws IOException {
|
||||
File xlsx = write(dir, "b.xlsx", "data");
|
||||
FileResultEntity row = resultRowWithFailure("店铺处理失败");
|
||||
row.setSuccess(0);
|
||||
|
||||
pipeline.publishResultFile(row, xlsx, "店铺B.xlsx", "application/vnd.ms-excel", 3, true);
|
||||
|
||||
assertEquals(0, row.getSuccess(), "失败店铺的部分结果被组装后仍是失败态,否则用户看不到「其实没跑完」");
|
||||
assertEquals("店铺处理失败", row.getErrorMessage());
|
||||
assertEquals("店铺B.xlsx", row.getResultFilename(), "文件照挂,用户仍能下载已跑出来的行");
|
||||
verify(fileResultMapper).updateById(row);
|
||||
}
|
||||
|
||||
@Test
|
||||
void uploadFailureLeavesTheRowUntouched(@TempDir java.nio.file.Path dir) throws IOException {
|
||||
File xlsx = write(dir, "c.xlsx", "data");
|
||||
FileResultEntity row = resultRowWithFailure(null);
|
||||
when(ossStorageService.uploadResultFile(any(), anyString())).thenThrow(new IllegalStateException("对象存储不可达"));
|
||||
|
||||
assertThrows(IllegalStateException.class,
|
||||
() -> pipeline.publishResultFile(row, xlsx, "店铺C.xlsx", "x", 1, false));
|
||||
|
||||
verify(fileResultMapper, never()).updateById(any(FileResultEntity.class));
|
||||
assertNull(row.getResultFileUrl(), "上传没成就不能把 URL 写进去,否则下载即 404");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// 夹具
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
private void assertAdmissionFails(String expectedMessage) {
|
||||
BusinessException ex = assertThrows(BusinessException.class,
|
||||
() -> pipeline.admitSubmission(1L, AbstractFileTaskPipeline.TerminalRejection.IDEMPOTENT, null));
|
||||
assertEquals(expectedMessage, ex.getMessage());
|
||||
}
|
||||
|
||||
private static FileTaskEntity taskWithStatus(String status) {
|
||||
FileTaskEntity task = new FileTaskEntity();
|
||||
task.setId(1L);
|
||||
task.setModuleType(MODULE_TYPE);
|
||||
task.setStatus(status);
|
||||
return task;
|
||||
}
|
||||
|
||||
private static FileResultEntity resultRowWithFailure(String errorMessage) {
|
||||
FileResultEntity row = new FileResultEntity();
|
||||
row.setId(500L);
|
||||
row.setTaskId(1L);
|
||||
row.setModuleType(MODULE_TYPE);
|
||||
row.setSuccess(0);
|
||||
row.setErrorMessage(errorMessage);
|
||||
return row;
|
||||
}
|
||||
|
||||
private static File write(java.nio.file.Path dir, String name, String content) throws IOException {
|
||||
return Files.write(dir.resolve(name), content.getBytes(StandardCharsets.UTF_8)).toFile();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// 序列化公共件(随 Phase 3 首迁落下那一件)
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void writeJsonHandsBackExactlyWhatTheMapperProduced() throws Exception {
|
||||
com.fasterxml.jackson.databind.ObjectMapper mapper =
|
||||
mock(com.fasterxml.jackson.databind.ObjectMapper.class);
|
||||
when(mapper.writeValueAsString(any())).thenReturn("{\"k\":1}");
|
||||
|
||||
assertEquals("{\"k\":1}", pipeline.writeJson(mapper, java.util.Map.of("k", 1), "序列化任务数据失败"));
|
||||
verify(mapper, times(1)).writeValueAsString(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void writeJsonReplacesFailureWithTheBranchOwnMessageAndKeepsNoCause() throws Exception {
|
||||
com.fasterxml.jackson.databind.ObjectMapper mapper =
|
||||
mock(com.fasterxml.jackson.databind.ObjectMapper.class);
|
||||
when(mapper.writeValueAsString(any())).thenThrow(new IllegalStateException("serializer blew up"));
|
||||
|
||||
BusinessException ex = assertThrows(BusinessException.class,
|
||||
() -> pipeline.writeJson(mapper, new Object(), "task 不存在"));
|
||||
|
||||
assertEquals("task 不存在", ex.getMessage(), "文案逐字取被迁支现网那句(Python 按它决定要不要重试)");
|
||||
assertNull(ex.getCause(), "七支的形状都是「不带 cause」——带上就等于悄悄改日志体积");
|
||||
}
|
||||
|
||||
@Test
|
||||
void writeJsonCatchesSerializerRuntimeExceptionsNotOnlyJsonOnes() throws Exception {
|
||||
// 被迁支原样是宽捕获(catch (Exception));收窄成 JsonProcessingException 会让
|
||||
// 序列化器自己抛的 RuntimeException 从「拒单」变成「冒出去」,那是行为变更,不归本件。
|
||||
com.fasterxml.jackson.databind.ObjectMapper mapper =
|
||||
mock(com.fasterxml.jackson.databind.ObjectMapper.class);
|
||||
when(mapper.writeValueAsString(any())).thenThrow(new NullPointerException("getter threw"));
|
||||
|
||||
assertThrows(BusinessException.class, () -> pipeline.writeJson(mapper, new Object(), "序列化任务数据失败"));
|
||||
}
|
||||
|
||||
/** 被测底座的具体子类:只补三个钩子,公共件一律不重写(重写就等于没沉)。 */
|
||||
private static class TestPipeline extends AbstractFileTaskPipeline<Map<String, Object>> {
|
||||
|
||||
FileTaskEntity loadedTask;
|
||||
String ownershipOperation;
|
||||
boolean cacheRequested;
|
||||
AbstractModuleTaskCacheService<Map<String, Object>> cacheServiceHolder;
|
||||
|
||||
TestPipeline(FileTaskMapper fileTaskMapper,
|
||||
FileResultMapper fileResultMapper,
|
||||
TaskDistributedLockService lockService,
|
||||
TaskFileJobService jobService,
|
||||
OssStorageService ossStorageService) {
|
||||
super(fileTaskMapper, fileResultMapper, lockService, jobService, ossStorageService);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String moduleType() {
|
||||
return MODULE_TYPE;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected FileTaskEntity loadTaskForSubmission(Long taskId) {
|
||||
return loadedTask;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected AbstractModuleTaskCacheService<Map<String, Object>> taskCacheService() {
|
||||
cacheRequested = true;
|
||||
return cacheServiceHolder;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void ensureTaskOwnedByCurrentInstance(FileTaskEntity task, String operation) {
|
||||
this.ownershipOperation = operation;
|
||||
}
|
||||
}
|
||||
}
|
||||
+368
@@ -0,0 +1,368 @@
|
||||
package com.nanri.aiimage.modules.task.service.pipeline;
|
||||
|
||||
import com.baomidou.mybatisplus.core.MybatisConfiguration;
|
||||
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
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.model.entity.FileResultEntity;
|
||||
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
|
||||
import com.nanri.aiimage.modules.task.service.TaskDistributedLockService;
|
||||
import com.nanri.aiimage.modules.task.service.TaskFileJobService;
|
||||
import org.apache.ibatis.builder.MapperBuilderAssistant;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.function.Function;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* 「店铺维度合并载荷」家族骨架的行为契约。
|
||||
*
|
||||
* <p>逐条对撞的是 ShopMatch{@code submitResult:630-710} 与 PriceTrack{@code submitResult:591-663}
|
||||
* 这两支行级孪生件的共同形状:命中与否由 {@code row.sourceFilename} 对上归一化店铺名决定,
|
||||
* 一个都没命中就<b>不重读也不重算状态</b>,任何退出路径都必须把任务锁还回去。
|
||||
*/
|
||||
class AbstractShopPayloadTaskPipelineTest {
|
||||
|
||||
private static final String MODULE_TYPE = "SHOP_PAYLOAD_TEST";
|
||||
|
||||
private FileResultMapper fileResultMapper;
|
||||
private TaskDistributedLockService lockService;
|
||||
private TaskDistributedLockService.LockHandle lockHandle;
|
||||
private ShopPipeline pipeline;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""),
|
||||
FileResultEntity.class);
|
||||
fileResultMapper = mock(FileResultMapper.class);
|
||||
lockService = mock(TaskDistributedLockService.class);
|
||||
lockHandle = mock(TaskDistributedLockService.LockHandle.class);
|
||||
when(lockService.acquire(anyString(), any())).thenReturn(lockHandle);
|
||||
pipeline = new ShopPipeline(mock(FileTaskMapper.class), fileResultMapper, lockService,
|
||||
mock(TaskFileJobService.class), mock(OssStorageService.class));
|
||||
pipeline.loadedTask = runningTask();
|
||||
}
|
||||
|
||||
@Test
|
||||
void matchedShopRowsAreHandledOnceAndStatusIsRecomputedFromFreshRows() {
|
||||
FileResultEntity shopA = row("shop-a");
|
||||
FileResultEntity shopB = row("shop-b");
|
||||
List<FileResultEntity> firstRead = List.of(shopA, shopB);
|
||||
List<FileResultEntity> secondRead = List.of(row("shop-a"));
|
||||
// 第一次读=本轮待处理行,第二次读=changed 闸门后重算状态用的最新行(两支现网都是重读,不复用旧行)
|
||||
when(fileResultMapper.selectList(any())).thenReturn(firstRead, secondRead);
|
||||
|
||||
pipeline.submitShopScopedResults(1L, List.of("Shop-A"), String::valueOf,
|
||||
AbstractFileTaskPipeline.TerminalRejection.IDEMPOTENT, null);
|
||||
|
||||
assertEquals(1, pipeline.handled.size(), "只处理对上的那一行,对不上的行不许被顺手改写");
|
||||
assertEquals("shop-a", pipeline.handled.get(0).shopKey);
|
||||
assertSame(shopA, pipeline.handled.get(0).row);
|
||||
assertEquals("Shop-A", pipeline.handled.get(0).incoming, "钩子收的是原始入参,合并时机留给各支自己定");
|
||||
assertSame(pipeline.loadedTask, pipeline.handled.get(0).task);
|
||||
assertEquals(1, pipeline.recomputed.size());
|
||||
assertSame(secondRead, pipeline.recomputed.get(0), "收尾必须拿重读后的最新行,不能吃本轮的旧快照");
|
||||
verify(lockHandle, times(1)).close();
|
||||
}
|
||||
|
||||
@Test
|
||||
void noMatchedRowLeavesStatusUntouchedButStillReleasesTheLock() {
|
||||
when(fileResultMapper.selectList(any())).thenReturn(List.of(row("shop-x")));
|
||||
|
||||
pipeline.submitShopScopedResults(1L, List.of("Shop-Z"), String::valueOf,
|
||||
AbstractFileTaskPipeline.TerminalRejection.IDEMPOTENT, null);
|
||||
|
||||
assertTrue(pipeline.handled.isEmpty());
|
||||
assertTrue(pipeline.recomputed.isEmpty(), "changed 闸门是两支共有的:没改动就不许重算任务状态");
|
||||
verify(lockHandle, times(1)).close();
|
||||
}
|
||||
|
||||
@Test
|
||||
void rowWithoutScopeKeyIsSkippedInsteadOfCrashingTheLoop() {
|
||||
when(fileResultMapper.selectList(any())).thenReturn(List.of(row(null)));
|
||||
|
||||
pipeline.submitShopScopedResults(1L, List.of("Shop-A"), String::valueOf,
|
||||
AbstractFileTaskPipeline.TerminalRejection.IDEMPOTENT, null);
|
||||
|
||||
assertTrue(pipeline.handled.isEmpty());
|
||||
assertTrue(pipeline.recomputed.isEmpty());
|
||||
verify(lockHandle, times(1)).close();
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptyShopListIsRejectedBeforeTakingTheLock() {
|
||||
BusinessException empty = assertThrows(BusinessException.class,
|
||||
() -> pipeline.submitShopScopedResults(1L, List.of(), String::valueOf,
|
||||
AbstractFileTaskPipeline.TerminalRejection.IDEMPOTENT, null));
|
||||
assertEquals("shops 不能为空", empty.getMessage());
|
||||
|
||||
BusinessException nullList = assertThrows(BusinessException.class,
|
||||
() -> pipeline.submitShopScopedResults(1L, null, String::valueOf,
|
||||
AbstractFileTaskPipeline.TerminalRejection.IDEMPOTENT, null));
|
||||
assertEquals("shops 不能为空", nullList.getMessage());
|
||||
|
||||
verifyNoInteractions(lockService, fileResultMapper);
|
||||
}
|
||||
|
||||
@Test
|
||||
void illegalTaskIdKeepsItsOwnMessageAndDoesNotReachTheShopValidation() {
|
||||
BusinessException ex = assertThrows(BusinessException.class,
|
||||
() -> pipeline.submitShopScopedResults(0L, List.of("Shop-A"), String::valueOf,
|
||||
AbstractFileTaskPipeline.TerminalRejection.IDEMPOTENT, null));
|
||||
assertEquals("taskId 不合法", ex.getMessage());
|
||||
verifyNoInteractions(lockService, fileResultMapper);
|
||||
}
|
||||
|
||||
@Test
|
||||
void terminalTaskRejectionStillReleasesTheLock() {
|
||||
pipeline.loadedTask.setStatus("SUCCESS");
|
||||
|
||||
BusinessException ex = assertThrows(BusinessException.class,
|
||||
() -> pipeline.submitShopScopedResults(1L, List.of("Shop-A"), String::valueOf,
|
||||
AbstractFileTaskPipeline.TerminalRejection.IDEMPOTENT, null));
|
||||
|
||||
assertEquals(40901, ex.getCode(), "终态重复提交必须回 40901,让 Python 侧幂等忽略");
|
||||
verify(lockHandle, times(1)).close();
|
||||
verify(fileResultMapper, never()).selectList(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void hookFailurePropagatesAndTheLockIsNotLeaked() {
|
||||
when(fileResultMapper.selectList(any())).thenReturn(List.of(row("shop-a")));
|
||||
pipeline.failOnHandle = new IllegalStateException("合并载荷时对象存储不可达");
|
||||
|
||||
assertThrows(IllegalStateException.class,
|
||||
() -> pipeline.submitShopScopedResults(1L, List.of("Shop-A"), String::valueOf,
|
||||
AbstractFileTaskPipeline.TerminalRejection.IDEMPOTENT, null));
|
||||
|
||||
verify(lockHandle, times(1)).close();
|
||||
assertTrue(pipeline.recomputed.isEmpty(), "单行炸了就不许带着半截状态去重算任务");
|
||||
}
|
||||
|
||||
@Test
|
||||
void incomingIndexSkipsNullAndUnnormalizableShopNamesKeepingRequestOrder() {
|
||||
// 每项尾缀一个序号,好让「同名后者覆盖」这件事看得见(List.of 不收 null,这里用 Arrays.asList)
|
||||
List<String> incoming = java.util.Arrays.asList("Shop-B#1", null, " ", "Shop-A#1", "Shop-B#2");
|
||||
Function<String, String> shopNameOf = item -> item.split("#")[0];
|
||||
|
||||
var indexed = pipeline.indexByShopKey(incoming, shopNameOf);
|
||||
|
||||
assertEquals(List.of("shop-b", "shop-a"), List.copyOf(indexed.keySet()),
|
||||
"空名与归一化后为空的项不进索引;请求顺序保留(两支都用 LinkedHashMap)");
|
||||
assertEquals("Shop-B#2", indexed.get("shop-b"), "同名后到的覆盖先到的——两支现网 put 同形,不许改成合并");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shopKeyNormalizerIsUsedForBothIndexingAndMatching() {
|
||||
// 行上的 sourceFilename 是建单时按同一规则写进去的归一化名(ShopMatch:601/PriceTrack:528-543)
|
||||
when(fileResultMapper.selectList(any())).thenReturn(List.of(row("shop-a")));
|
||||
|
||||
pipeline.submitShopScopedResults(1L, List.of("Shop-A"), String::valueOf,
|
||||
AbstractFileTaskPipeline.TerminalRejection.IDEMPOTENT, null);
|
||||
|
||||
assertEquals(List.of("Shop-A"), pipeline.normalized, "索引侧必须调归一化钩子,两侧同规则才对得上");
|
||||
assertEquals(1, pipeline.handled.size());
|
||||
assertEquals("shop-a", pipeline.handled.get(0).shopKey);
|
||||
}
|
||||
|
||||
@Test
|
||||
void lockLogTagDefaultsToModuleTypeSoSubclassesMustOverrideIt() {
|
||||
assertEquals(MODULE_TYPE, pipeline.submissionLockLogTag(),
|
||||
"默认给个不缺的标签;现网各支是小写短名(shop-match/price-track),迁移时必须覆写回历史值");
|
||||
|
||||
ShopPipeline tagged = new ShopPipeline(mock(FileTaskMapper.class), mock(FileResultMapper.class),
|
||||
mock(TaskDistributedLockService.class), mock(TaskFileJobService.class),
|
||||
mock(OssStorageService.class)) {
|
||||
@Override
|
||||
protected String submissionLockLogTag() {
|
||||
return "shop-match";
|
||||
}
|
||||
};
|
||||
assertEquals("shop-match", tagged.submissionLockLogTag());
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// 载荷观察点(首迁实测缺件:PriceTrack:617 那句 received 日志的位置)
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void payloadIsObservedOnceAfterAdmissionAndBeforeTheRowLoop() {
|
||||
when(fileResultMapper.selectList(any())).thenReturn(List.of(row("shop-a"), row("shop-b")));
|
||||
|
||||
pipeline.submitShopScopedResults(1L, List.of("Shop-A"), String::valueOf,
|
||||
AbstractFileTaskPipeline.TerminalRejection.IDEMPOTENT, null);
|
||||
|
||||
assertEquals(List.of("observed", "handle:shop-a", "recomputed"), pipeline.order,
|
||||
"观察点必须卡在「准入已过、索引已建、行还没开始处理」——早一秒晚一秒都拿不到 PriceTrack 那句日志的语义");
|
||||
assertEquals(1, pipeline.observedTasks.size(), "每次回传恰好观察一次,不是每行一次");
|
||||
assertSame(pipeline.loadedTask, pipeline.observedTasks.get(0), "拿到的是准入后的那一枚任务实体");
|
||||
assertEquals(List.of("shop-a"), List.copyOf(pipeline.observedIndexes.get(0).keySet()),
|
||||
"拿到的是归一化之后的索引(payloadKeys 就是它)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void observationIsSkippedOnEveryRejectionPath() {
|
||||
FileTaskEntity finished = runningTask();
|
||||
finished.setStatus("SUCCESS");
|
||||
pipeline.loadedTask = finished;
|
||||
assertThrows(BusinessException.class, () -> pipeline.submitShopScopedResults(1L, List.of("Shop-A"),
|
||||
String::valueOf, AbstractFileTaskPipeline.TerminalRejection.IDEMPOTENT, null));
|
||||
|
||||
pipeline.loadedTask = runningTask();
|
||||
assertThrows(BusinessException.class, () -> pipeline.submitShopScopedResults(1L, List.of(),
|
||||
String::valueOf, AbstractFileTaskPipeline.TerminalRejection.IDEMPOTENT, null));
|
||||
assertThrows(BusinessException.class, () -> pipeline.submitShopScopedResults(0L, List.of("Shop-A"),
|
||||
String::valueOf, AbstractFileTaskPipeline.TerminalRejection.IDEMPOTENT, null));
|
||||
|
||||
assertTrue(pipeline.order.isEmpty(), "被拒的回传一条都不该被观察到,否则 received 日志会在拒绝路径上冒出来");
|
||||
}
|
||||
|
||||
@Test
|
||||
void branchesThatDoNotOverrideTheObserverStillRunUnchanged() {
|
||||
// ShopMatch 一个字都不改就走这条路径 ⇒ 默认实现必须是真空着:既不吞调用,也不替别人打日志。
|
||||
// 这里刻意造一支**没有覆写观察点**的子类:它只需要能跑完,跑不完就是默认实现写坏了。
|
||||
List<String> handled = new ArrayList<>();
|
||||
AbstractShopPayloadTaskPipeline<String> untouched =
|
||||
new AbstractShopPayloadTaskPipeline<String>(mock(FileTaskMapper.class), fileResultMapper,
|
||||
lockService, mock(TaskFileJobService.class), mock(OssStorageService.class)) {
|
||||
@Override
|
||||
protected String moduleType() {
|
||||
return MODULE_TYPE;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected FileTaskEntity loadTaskForSubmission(Long taskId) {
|
||||
return runningTask();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String normalizeShopKey(String rawShopName) {
|
||||
return rawShopName == null ? null : rawShopName.trim().toLowerCase();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void applyShopResultRow(Long taskId, FileTaskEntity task, FileResultEntity row,
|
||||
String shopKey, String incoming) {
|
||||
handled.add(shopKey);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onShopRowsRecomputed(FileTaskEntity task, List<FileResultEntity> latestRows) {
|
||||
handled.add("recomputed:" + latestRows.size());
|
||||
}
|
||||
};
|
||||
when(fileResultMapper.selectList(any())).thenReturn(List.of(row("shop-a")));
|
||||
|
||||
untouched.submitShopScopedResults(1L, List.of("Shop-A"), String::valueOf,
|
||||
AbstractFileTaskPipeline.TerminalRejection.IDEMPOTENT, null);
|
||||
|
||||
assertEquals(List.of("shop-a", "recomputed:1"), handled,
|
||||
"没覆写观察点的子类,段 3 骨架的产出与覆写前逐字相同(默认实现不改变任何形状)");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// 夹具
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
private static FileTaskEntity runningTask() {
|
||||
FileTaskEntity task = new FileTaskEntity();
|
||||
task.setId(1L);
|
||||
task.setModuleType(MODULE_TYPE);
|
||||
task.setStatus("RUNNING");
|
||||
return task;
|
||||
}
|
||||
|
||||
private static FileResultEntity row(String shopKey) {
|
||||
FileResultEntity row = new FileResultEntity();
|
||||
row.setTaskId(1L);
|
||||
row.setModuleType(MODULE_TYPE);
|
||||
row.setSourceFilename(shopKey);
|
||||
row.setSuccess(0);
|
||||
return row;
|
||||
}
|
||||
|
||||
/** 家族层的具体子类:三个钩子只做记录,不引入任何模块语义。 */
|
||||
private static class ShopPipeline extends AbstractShopPayloadTaskPipeline<String> {
|
||||
|
||||
FileTaskEntity loadedTask;
|
||||
final List<Handled> handled = new ArrayList<>();
|
||||
final List<List<FileResultEntity>> recomputed = new ArrayList<>();
|
||||
final List<String> normalized = new ArrayList<>();
|
||||
// 观察点契约用:副作用的**先后**才是这一格的內容,光数次数证明不了它卡在准入之后、行循环之前
|
||||
final List<String> order = new ArrayList<>();
|
||||
final List<FileTaskEntity> observedTasks = new ArrayList<>();
|
||||
final List<java.util.Map<String, String>> observedIndexes = new ArrayList<>();
|
||||
RuntimeException failOnHandle;
|
||||
|
||||
ShopPipeline(FileTaskMapper fileTaskMapper,
|
||||
FileResultMapper fileResultMapper,
|
||||
TaskDistributedLockService lockService,
|
||||
TaskFileJobService jobService,
|
||||
OssStorageService ossStorageService) {
|
||||
super(fileTaskMapper, fileResultMapper, lockService, jobService, ossStorageService);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String moduleType() {
|
||||
return MODULE_TYPE;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected FileTaskEntity loadTaskForSubmission(Long taskId) {
|
||||
return loadedTask;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String normalizeShopKey(String rawShopName) {
|
||||
normalized.add(rawShopName);
|
||||
return rawShopName == null ? null : rawShopName.trim().toLowerCase();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onPayloadIndexed(FileTaskEntity task, java.util.Map<String, String> payloadByShopKey) {
|
||||
observedTasks.add(task);
|
||||
observedIndexes.add(new java.util.LinkedHashMap<>(payloadByShopKey));
|
||||
order.add("observed");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void applyShopResultRow(Long taskId,
|
||||
FileTaskEntity task,
|
||||
FileResultEntity row,
|
||||
String shopKey,
|
||||
String incoming) {
|
||||
order.add("handle:" + shopKey);
|
||||
if (failOnHandle != null) {
|
||||
throw failOnHandle;
|
||||
}
|
||||
handled.add(new Handled(taskId, task, row, shopKey, incoming));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onShopRowsRecomputed(FileTaskEntity task, List<FileResultEntity> latestRows) {
|
||||
order.add("recomputed");
|
||||
recomputed.add(latestRows);
|
||||
}
|
||||
}
|
||||
|
||||
private record Handled(Long taskId, FileTaskEntity task, FileResultEntity row, String shopKey, String incoming) {
|
||||
}
|
||||
}
|
||||
@@ -487,4 +487,139 @@ class SourceScanTest {
|
||||
.hasMessageContaining("遍历")
|
||||
.hasMessageContaining(vanished.getFileName().toString());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- N8 只吃 .java
|
||||
|
||||
@Test
|
||||
void exclude_java只计java扩展() {
|
||||
assertThat(SourceScan.moduleSources("modules/appearancepatent"))
|
||||
.as("面内每一支都必须以小写 {@code .java} 结尾——大小写策略见 exclude_大写JAVA后缀被计入")
|
||||
.allMatch(p -> p.getFileName().toString().endsWith(".java"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void exclude_同目录md文件不进面() throws IOException {
|
||||
Path module = Files.createDirectories(tmp.resolve("N8混放/src/main/java/modules/mixed"));
|
||||
Files.writeString(module.resolve("Keep.java"), "class Keep {}", StandardCharsets.UTF_8);
|
||||
Files.writeString(module.resolve("MIGRATION.md"), "# 拆分说明", StandardCharsets.UTF_8);
|
||||
Files.writeString(module.resolve("mapper.xml"), "<x/>", StandardCharsets.UTF_8);
|
||||
Files.writeString(module.resolve("notes.txt"), "x", StandardCharsets.UTF_8);
|
||||
|
||||
assertThat(SourceScan.moduleSources(tmp.resolve("N8混放/src/main/java"), "modules/mixed"))
|
||||
.as("真集成同款场景:SourceScan.java:35-39 记过同类事故——注释类文本会把「被禁写法」喂成假绿。"
|
||||
+ "正反双向一起断言:留 1 支 .java,同时排除 3 支非 java")
|
||||
.extracting(p -> p.getFileName().toString())
|
||||
.containsExactly("Keep.java");
|
||||
}
|
||||
|
||||
@Test
|
||||
void exclude_大写JAVA后缀被计入() throws IOException {
|
||||
Path module = Files.createDirectories(tmp.resolve("N8大小写/src/main/java/modules/case"));
|
||||
Files.writeString(module.resolve("Lower.java"), "class Lower {}", StandardCharsets.UTF_8);
|
||||
Files.writeString(module.resolve("UPPER.JAVA"), "class UPPER {}", StandardCharsets.UTF_8);
|
||||
|
||||
// 本 task 定口径:**大写 .JAVA 不计**(与仓内现状一致)。正反两条同时钉:
|
||||
// 谁把它改成大小写不敏感匹配,下面那条「不含 UPPER.JAVA」立刻红——这格因此不是恒绿格。
|
||||
List<String> names = SourceScan.moduleSources(tmp.resolve("N8大小写/src/main/java"), "modules/case")
|
||||
.stream().map(p -> p.getFileName().toString()).toList();
|
||||
|
||||
assertThat(names).contains("Lower.java");
|
||||
assertThat(names)
|
||||
.as("口径选择:只认小写 .java。仓内 973 支主源码件实测全是小写后缀,"
|
||||
+ "把 .JAVA 也收进来等于给「同一份代码换个大小写再放一遍」开绿灯")
|
||||
.doesNotContain("UPPER.JAVA");
|
||||
}
|
||||
|
||||
@Test
|
||||
void exclude_以java结尾的目录名不误判() throws IOException {
|
||||
Path module = Files.createDirectories(tmp.resolve("N8怪目录/src/main/java/modules/weird"));
|
||||
Path fakeDir = Files.createDirectories(module.resolve("foo.java"));
|
||||
Files.writeString(fakeDir.resolve("Bar.java"), "class Bar {}", StandardCharsets.UTF_8);
|
||||
|
||||
List<Path> files = SourceScan.moduleSources(tmp.resolve("N8怪目录/src/main/java"), "modules/weird");
|
||||
|
||||
assertThat(Files.isDirectory(fakeDir))
|
||||
.as("正对照:这个目录确实叫 foo.java,否则下面那条断言是空的")
|
||||
.isTrue();
|
||||
assertThat(files)
|
||||
.as("目录不是源文件:后缀判定必须先过 isRegularFile(walkFileTree 的 visitFile 天然只给文件,"
|
||||
+ "但这条换实现就容易踩,所以钉住)")
|
||||
.extracting(p -> p.getFileName().toString())
|
||||
.containsExactly("Bar.java");
|
||||
}
|
||||
|
||||
@Test
|
||||
// plan 原文这格叫「exclude_隐藏文件.java不计入」——含点号做 Java 方法名不合法,改名并在此留痕
|
||||
void exclude_隐藏文件不计入() throws IOException {
|
||||
Path module = Files.createDirectories(tmp.resolve("N8隐藏件/src/main/java/modules/dot"));
|
||||
Files.writeString(module.resolve("Real.java"), "class Real {}", StandardCharsets.UTF_8);
|
||||
Files.writeString(module.resolve(".Shadow.java"), "class Shadow {}", StandardCharsets.UTF_8);
|
||||
|
||||
assertThat(SourceScan.moduleSources(tmp.resolve("N8隐藏件/src/main/java"), "modules/dot"))
|
||||
.as("以点开头的 .java 是编辑器备份(.Foo.java、Foo.java.orig 一族),进面就会把计数喂大。"
|
||||
+ "正反双向:真件在、影子件不在")
|
||||
.extracting(p -> p.getFileName().toString())
|
||||
.containsExactly("Real.java");
|
||||
}
|
||||
|
||||
@Test
|
||||
void exclude_空文件被计入但读为空串() throws IOException {
|
||||
Path module = Files.createDirectories(tmp.resolve("N8空件/src/main/java/modules/zero"));
|
||||
Path empty = Files.createFile(module.resolve("Empty.java"));
|
||||
Files.writeString(module.resolve("Kept.java"), "class Kept {}", StandardCharsets.UTF_8);
|
||||
|
||||
List<Path> files = SourceScan.moduleSources(tmp.resolve("N8空件/src/main/java"), "modules/zero");
|
||||
|
||||
assertThat(Files.size(empty))
|
||||
.as("正对照:这支确实是 0 字节")
|
||||
.isZero();
|
||||
assertThat(files)
|
||||
.as("有文件但内容为空 ≠ 零文件——这条与 N11「目录里 0 支 .java 才抛」必须分得开,"
|
||||
+ "否则 N11 会把「全是空件」的模块误判成「没有文件」")
|
||||
.extracting(p -> p.getFileName().toString())
|
||||
.containsExactlyInAnyOrder("Empty.java", "Kept.java");
|
||||
}
|
||||
|
||||
@Test
|
||||
void exclude_不可读文件抛不静默跳过() throws IOException, InterruptedException {
|
||||
Path root = tmp.resolve("N8不可读/src/main/java");
|
||||
Path module = Files.createDirectories(root.resolve("modules/locked"));
|
||||
Path noList = Files.createDirectories(module.resolve("nolist"));
|
||||
Files.writeString(noList.resolve("Hidden.java"), "class Hidden {}", StandardCharsets.UTF_8);
|
||||
|
||||
Process icacls = new ProcessBuilder("icacls", noList.toString(), "/deny", "*S-1-1-0:(OI)(CI)RX")
|
||||
.redirectErrorStream(true).start();
|
||||
String out;
|
||||
try (var in = icacls.getInputStream()) {
|
||||
out = new String(in.readAllBytes(), StandardCharsets.UTF_8);
|
||||
}
|
||||
int code = icacls.waitFor();
|
||||
try {
|
||||
assertThat(code)
|
||||
.as("icacls 造不出「不可列举目录」⇒ 环境缺口,判红而不是跳过(跳过会新增 Skipped,违反 N99)。"
|
||||
+ "输出:%s", out)
|
||||
.isZero();
|
||||
assertThat(Files.isReadable(noList))
|
||||
.as("反证前提:拒绝授权必须真的生效,否则后面那条断言是恒绿的")
|
||||
.isFalse();
|
||||
|
||||
assertThatThrownBy(() -> SourceScan.moduleSources(root, "modules/locked"))
|
||||
.as("列举失败的目录必须把异常冒出来(visitFileFailed ⇒ IllegalStateException),"
|
||||
+ "静默跳过 = 那个子树里的被禁写法永远不会被读到")
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessageContaining("遍历");
|
||||
} finally {
|
||||
// 撤销拒绝授权,否则 JUnit 清 @TempDir 会因无删除权限卡住,把一次性件留在机器上
|
||||
new ProcessBuilder("icacls", noList.toString(), "/remove:d", "*S-1-1-0")
|
||||
.redirectErrorStream(true).start().waitFor();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void exclude_面内全部元素isRegularFile为真() {
|
||||
assertThat(SourceScan.moduleSources("modules/shopdatacrawl"))
|
||||
.as("真实集成:51 支的模块里逐支都必须是regular file,形状契约")
|
||||
.isNotEmpty()
|
||||
.allMatch(Files::isRegularFile);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
== case=keywordSheet
|
||||
vo: taskId=1001 sourceFilename=keyword.xlsx sourceFileCount=1 totalRows=3 acceptedRows=2 droppedRows=1 pageSize=50
|
||||
task.insert: id=1001 moduleType=COLLECT_DATA taskMode=PYTHON_QUEUE status=PENDING sourceFileCount=1 deviceId=dev-1 requestJsonTaskTypeDefault=true requestJsonTaskTypeExplicit=false resultJsonHasFinalRowCount=true
|
||||
item: id=3001 taskId=1001 rowIndex=1 sourceFileKey=fk-keyword sourceFilename=keyword.xlsx keyword=wirel less 耳机 statusValue=在售 extraJson={"asin":"B011","国家":"US","价格":"19.90"}
|
||||
item: id=3002 taskId=1001 rowIndex=2 sourceFileKey=fk-keyword sourceFilename=keyword.xlsx keyword=mouse statusValue=缺少报价 extraJson={"asin":"","国家":"DE","价格":""}
|
||||
result.insert: id=2001 taskId=1001 moduleType=COLLECT_DATA sourceFilename=keyword.xlsx sourceFileUrl=fk-keyword rowCount=2
|
||||
== case=explicitTaskType
|
||||
vo: taskId=1001 sourceFilename=keyword.xlsx sourceFileCount=1 totalRows=3 acceptedRows=2 droppedRows=1 pageSize=50
|
||||
task.insert: id=1001 moduleType=COLLECT_DATA taskMode=PYTHON_QUEUE status=PENDING sourceFileCount=1 deviceId=dev-1 requestJsonTaskTypeDefault=false requestJsonTaskTypeExplicit=true resultJsonHasFinalRowCount=true
|
||||
item: id=3001 taskId=1001 rowIndex=1 sourceFileKey=fk-keyword sourceFilename=keyword.xlsx keyword=wirel less 耳机 statusValue=在售 extraJson={"asin":"B011","国家":"US","价格":"19.90"}
|
||||
item: id=3002 taskId=1001 rowIndex=2 sourceFileKey=fk-keyword sourceFilename=keyword.xlsx keyword=mouse statusValue=缺少报价 extraJson={"asin":"","国家":"DE","价格":""}
|
||||
result.insert: id=2001 taskId=1001 moduleType=COLLECT_DATA sourceFilename=keyword.xlsx sourceFileUrl=fk-keyword rowCount=2
|
||||
== case=noKeywordHeader
|
||||
vo: taskId=1001 sourceFilename=no-keyword.xlsx sourceFileCount=1 totalRows=2 acceptedRows=2 droppedRows=0 pageSize=50
|
||||
task.insert: id=1001 moduleType=COLLECT_DATA taskMode=PYTHON_QUEUE status=PENDING sourceFileCount=1 deviceId=dev-1 requestJsonTaskTypeDefault=true requestJsonTaskTypeExplicit=false resultJsonHasFinalRowCount=true
|
||||
item: id=3001 taskId=1001 rowIndex=1 sourceFileKey=fk-no-keyword sourceFilename=no-keyword.xlsx keyword=- statusValue=- extraJson={"asin":"B021","国家":"UK","价格":"5.00"}
|
||||
item: id=3002 taskId=1001 rowIndex=2 sourceFileKey=fk-no-keyword sourceFilename=no-keyword.xlsx keyword=- statusValue=- extraJson={"asin":"B022","国家":"UK","价格":""}
|
||||
result.insert: id=2001 taskId=1001 moduleType=COLLECT_DATA sourceFilename=no-keyword.xlsx sourceFileUrl=fk-no-keyword rowCount=2
|
||||
== case=twoFiles
|
||||
vo: taskId=1001 sourceFilename=keyword.xlsx 等 2 个文件 sourceFileCount=2 totalRows=5 acceptedRows=4 droppedRows=1 pageSize=50
|
||||
task.insert: id=1001 moduleType=COLLECT_DATA taskMode=PYTHON_QUEUE status=PENDING sourceFileCount=2 deviceId=dev-1 requestJsonTaskTypeDefault=true requestJsonTaskTypeExplicit=false resultJsonHasFinalRowCount=true
|
||||
item: id=3001 taskId=1001 rowIndex=1 sourceFileKey=fk-keyword sourceFilename=keyword.xlsx keyword=wirel less 耳机 statusValue=在售 extraJson={"asin":"B011","国家":"US","价格":"19.90"}
|
||||
item: id=3002 taskId=1001 rowIndex=2 sourceFileKey=fk-keyword sourceFilename=keyword.xlsx keyword=mouse statusValue=缺少报价 extraJson={"asin":"","国家":"DE","价格":""}
|
||||
item: id=3003 taskId=1001 rowIndex=3 sourceFileKey=fk-no-keyword sourceFilename=no-keyword.xlsx keyword=- statusValue=- extraJson={"asin":"B021","国家":"UK","价格":"5.00"}
|
||||
item: id=3004 taskId=1001 rowIndex=4 sourceFileKey=fk-no-keyword sourceFilename=no-keyword.xlsx keyword=- statusValue=- extraJson={"asin":"B022","国家":"UK","价格":""}
|
||||
result.insert: id=2001 taskId=1001 moduleType=COLLECT_DATA sourceFilename=keyword.xlsx 等 2 个文件 sourceFileUrl=fk-keyword|fk-no-keyword rowCount=4
|
||||
== case=blankHeader
|
||||
thrown: BusinessException message=Excel 表头为空
|
||||
== case=allRowsDropped
|
||||
thrown: BusinessException message=未解析到有效数据行
|
||||
== case=notExcel
|
||||
thrown: BusinessException message=解析 Excel 失败
|
||||
== case=missingSourceFile
|
||||
thrown: BusinessException message=源文件不存在
|
||||
== case=blankFileKeyFiltered
|
||||
thrown: BusinessException message=请先上传 Excel 文件
|
||||
== case=emptyFiles
|
||||
thrown: BusinessException message=请先上传 Excel 文件
|
||||
@@ -0,0 +1,74 @@
|
||||
== case=main files=1
|
||||
task.insert: id=1001 moduleType=DELETE_BRAND status=RUNNING taskMode=IMMEDIATE userId=7 createdBy=user:7 deviceId=dev-1 sourceFileCount=1
|
||||
task.update: id=1001 status=RUNNING sourceFileCount=1 successFileCount=1 failedFileCount=0 errorMessage=-
|
||||
result.insert: id=2001 taskId=1001 moduleType=DELETE_BRAND sourceFileUrl=uploads/魏振峰.xlsx rowCount=4 success=0 resultFilename=- errorMessage=-
|
||||
vo: total=1 successCount=1 failedCount=0
|
||||
item: resultId=2001 fileKey=uploads/魏振峰.xlsx shopName=魏振峰 matched=true matchStatus=MATCHED countryCount=2 totalRows=4 truncated=false success=true error=- taskStatus=RUNNING
|
||||
parsed country=美国 asinCount=2
|
||||
parsed asin: row=3 value=b011 1 status=在售
|
||||
parsed asin: row=5 value=B012 status=-
|
||||
parsed country=德国 asinCount=2
|
||||
parsed asin: row=3 value=B021 status=-
|
||||
parsed asin: row=5 value=B022 status=在售
|
||||
preview: row=3 country=美国 asin=b011 1 status=在售
|
||||
preview: row=5 country=美国 asin=B012 status=-
|
||||
preview: row=3 country=德国 asin=B021 status=-
|
||||
preview: row=5 country=德国 asin=B022 status=在售
|
||||
payload.files=1
|
||||
payload: fileKey=uploads/魏振峰.xlsx shopId=shop-魏振峰 companyName=公司-魏振峰 platform=amazon totalRows=4
|
||||
country=美国 asinCount=2
|
||||
asin: row=3 value=b011 1 status=在售
|
||||
asin: row=5 value=B012 status=-
|
||||
country=德国 asinCount=2
|
||||
asin: row=3 value=B021 status=-
|
||||
asin: row=5 value=B022 status=在售
|
||||
== case=unmatched files=1
|
||||
task.insert: id=1001 moduleType=DELETE_BRAND status=FAILED taskMode=IMMEDIATE userId=7 createdBy=user:7 deviceId=dev-1 sourceFileCount=0
|
||||
task.update: id=1001 status=FAILED sourceFileCount=0 successFileCount=0 failedFileCount=1 errorMessage=全部文件解析或匹配失败
|
||||
result.insert: id=2001 taskId=1001 moduleType=DELETE_BRAND sourceFileUrl=uploads/魏振峰.xlsx rowCount=4 success=0 resultFilename=- errorMessage=-
|
||||
vo: total=1 successCount=0 failedCount=1
|
||||
item: resultId=2001 fileKey=uploads/魏振峰.xlsx shopName=魏振峰 matched=false matchStatus=NOT_FOUND countryCount=2 totalRows=4 truncated=false success=true error=- taskStatus=RUNNING
|
||||
parsed country=美国 asinCount=2
|
||||
parsed asin: row=3 value=b011 1 status=在售
|
||||
parsed asin: row=5 value=B012 status=-
|
||||
parsed country=德国 asinCount=2
|
||||
parsed asin: row=3 value=B021 status=-
|
||||
parsed asin: row=5 value=B022 status=在售
|
||||
preview: row=3 country=美国 asin=b011 1 status=在售
|
||||
preview: row=5 country=美国 asin=B012 status=-
|
||||
preview: row=3 country=德国 asin=B021 status=-
|
||||
preview: row=5 country=德国 asin=B022 status=在售
|
||||
payload.files=0
|
||||
== case=headerOnly files=1
|
||||
task.insert: id=1001 moduleType=DELETE_BRAND status=FAILED taskMode=IMMEDIATE userId=7 createdBy=user:7 deviceId=dev-1 sourceFileCount=0
|
||||
task.update: id=1001 status=FAILED sourceFileCount=0 successFileCount=0 failedFileCount=1 errorMessage=全部文件解析或匹配失败
|
||||
result.insert: id=2001 taskId=1001 moduleType=DELETE_BRAND sourceFileUrl=uploads/缺字段行.xlsx rowCount=- success=0 resultFilename=- errorMessage=Excel 表头不完整
|
||||
vo: total=1 successCount=0 failedCount=1
|
||||
item: resultId=2001 fileKey=uploads/缺字段行.xlsx shopName=缺字段行 matched=false matchStatus=- countryCount=- totalRows=- truncated=false success=false error=Excel 表头不完整 taskStatus=RUNNING
|
||||
payload.files=0
|
||||
== case=shopNameColumnSkipped files=1
|
||||
task.insert: id=1001 moduleType=DELETE_BRAND status=RUNNING taskMode=IMMEDIATE userId=7 createdBy=user:7 deviceId=dev-1 sourceFileCount=1
|
||||
task.update: id=1001 status=RUNNING sourceFileCount=1 successFileCount=1 failedFileCount=0 errorMessage=-
|
||||
result.insert: id=2001 taskId=1001 moduleType=DELETE_BRAND sourceFileUrl=uploads/英国.xlsx rowCount=3 success=0 resultFilename=- errorMessage=-
|
||||
vo: total=1 successCount=1 failedCount=0
|
||||
item: resultId=2001 fileKey=uploads/英国.xlsx shopName=英国 matched=true matchStatus=MATCHED countryCount=1 totalRows=3 truncated=false success=true error=- taskStatus=RUNNING
|
||||
parsed country=英国 asinCount=3
|
||||
parsed asin: row=2 value=ASIN status=状态
|
||||
parsed asin: row=3 value=B031 status=在售
|
||||
parsed asin: row=4 value=B032 status=缺少报价
|
||||
preview: row=2 country=英国 asin=ASIN status=状态
|
||||
preview: row=3 country=英国 asin=B031 status=在售
|
||||
preview: row=4 country=英国 asin=B032 status=缺少报价
|
||||
payload.files=1
|
||||
payload: fileKey=uploads/英国.xlsx shopId=shop-英国 companyName=公司-英国 platform=amazon totalRows=3
|
||||
country=英国 asinCount=3
|
||||
asin: row=2 value=ASIN status=状态
|
||||
asin: row=3 value=B031 status=在售
|
||||
asin: row=4 value=B032 status=缺少报价
|
||||
== case=notExcel files=1
|
||||
task.insert: id=1001 moduleType=DELETE_BRAND status=FAILED taskMode=IMMEDIATE userId=7 createdBy=user:7 deviceId=dev-1 sourceFileCount=0
|
||||
task.update: id=1001 status=FAILED sourceFileCount=0 successFileCount=0 failedFileCount=1 errorMessage=全部文件解析或匹配失败
|
||||
result.insert: id=2001 taskId=1001 moduleType=DELETE_BRAND sourceFileUrl=uploads/伪装.csv.xlsx rowCount=- success=0 resultFilename=- errorMessage=读取删除品牌 Excel 失败
|
||||
vo: total=1 successCount=0 failedCount=1
|
||||
item: resultId=2001 fileKey=uploads/伪装.csv.xlsx shopName=伪装.csv matched=false matchStatus=- countryCount=- totalRows=- truncated=false success=false error=读取删除品牌 Excel 失败 taskStatus=RUNNING
|
||||
payload.files=0
|
||||
@@ -0,0 +1,99 @@
|
||||
== case=asinModeTwoSheets
|
||||
vo: taskId=1001 items=2
|
||||
item: resultId=2001 shopName=店铺A matched=true taskStatus=RUNNING success=false
|
||||
item: resultId=2002 shopName=店铺B matched=true taskStatus=RUNNING success=false
|
||||
vo: asinRowsByCountry=0 skipAsinsByCountry=0 minimumPriceByCountry=0
|
||||
task.insert: id=1001 moduleType=PRICE_TRACK taskMode=PYTHON_QUEUE status=RUNNING sourceFileCount=2
|
||||
task.update: id=1001 status=RUNNING requestJsonHasAsinFiles=true requestJsonHasListingStatuses=true resultJsonItems=2
|
||||
result.insert: id=2001 moduleType=PRICE_TRACK sourceFilename=店铺A sourceFileUrl=shop-店铺A success=0
|
||||
result.insert: id=2002 moduleType=PRICE_TRACK sourceFilename=店铺B sourceFileUrl=shop-店铺B success=0
|
||||
payloadSaves=1
|
||||
payload country=UK rows=2
|
||||
row: asin=B011 price=19.90 minimumPrice=18.00
|
||||
row: asin=b012 price=20.00 minimumPrice=-
|
||||
payload country=DE rows=1
|
||||
row: asin=B021 price=5.00
|
||||
heartbeatTouches=1
|
||||
== case=singleSheetFallback
|
||||
vo: taskId=1001 items=1
|
||||
item: resultId=2001 shopName=店铺A matched=true taskStatus=RUNNING success=false
|
||||
vo: asinRowsByCountry=0 skipAsinsByCountry=0 minimumPriceByCountry=0
|
||||
task.insert: id=1001 moduleType=PRICE_TRACK taskMode=PYTHON_QUEUE status=RUNNING sourceFileCount=1
|
||||
task.update: id=1001 status=RUNNING requestJsonHasAsinFiles=true requestJsonHasListingStatuses=true resultJsonItems=1
|
||||
result.insert: id=2001 moduleType=PRICE_TRACK sourceFilename=店铺A sourceFileUrl=shop-店铺A success=0
|
||||
payloadSaves=1
|
||||
payload country=FR rows=1
|
||||
row: asin=B099 price=1.00
|
||||
heartbeatTouches=1
|
||||
== case=unknownSheetWithoutFallback
|
||||
vo: taskId=1001 items=1
|
||||
item: resultId=2001 shopName=店铺A matched=true taskStatus=RUNNING success=false
|
||||
vo: asinRowsByCountry=0 skipAsinsByCountry=0 minimumPriceByCountry=0
|
||||
task.insert: id=1001 moduleType=PRICE_TRACK taskMode=PYTHON_QUEUE status=RUNNING sourceFileCount=1
|
||||
task.update: id=1001 status=RUNNING requestJsonHasAsinFiles=true requestJsonHasListingStatuses=true resultJsonItems=1
|
||||
result.insert: id=2001 moduleType=PRICE_TRACK sourceFilename=店铺A sourceFileUrl=shop-店铺A success=0
|
||||
payloadSaves=1
|
||||
heartbeatTouches=1
|
||||
== case=multipleFilesSameCountryMerged
|
||||
vo: taskId=1001 items=1
|
||||
item: resultId=2001 shopName=店铺A matched=true taskStatus=RUNNING success=false
|
||||
vo: asinRowsByCountry=0 skipAsinsByCountry=0 minimumPriceByCountry=0
|
||||
task.insert: id=1001 moduleType=PRICE_TRACK taskMode=PYTHON_QUEUE status=RUNNING sourceFileCount=1
|
||||
task.update: id=1001 status=RUNNING requestJsonHasAsinFiles=true requestJsonHasListingStatuses=true resultJsonItems=1
|
||||
result.insert: id=2001 moduleType=PRICE_TRACK sourceFilename=店铺A sourceFileUrl=shop-店铺A success=0
|
||||
payloadSaves=1
|
||||
payload country=UK rows=2
|
||||
row: asin=B011 price=19.90 minimumPrice=18.00
|
||||
row: asin=b012 price=20.00 minimumPrice=-
|
||||
payload country=DE rows=1
|
||||
row: asin=B021 price=5.00
|
||||
payload country=FR rows=1
|
||||
row: asin=B099 price=1.00
|
||||
heartbeatTouches=1
|
||||
== case=fileOutsideTempRootRejected
|
||||
thrown: BusinessException message=ASIN 文件不存在或不可读: <outside>\outside.xlsx
|
||||
payloadSaves=0
|
||||
heartbeatTouches=0
|
||||
== case=missingFile
|
||||
thrown: BusinessException message=ASIN 文件不存在或不可读: 不存在的.xlsx
|
||||
payloadSaves=0
|
||||
heartbeatTouches=0
|
||||
== case=blankPathSkipped
|
||||
vo: taskId=1001 items=1
|
||||
item: resultId=2001 shopName=店铺A matched=true taskStatus=RUNNING success=false
|
||||
vo: asinRowsByCountry=0 skipAsinsByCountry=0 minimumPriceByCountry=0
|
||||
task.insert: id=1001 moduleType=PRICE_TRACK taskMode=PYTHON_QUEUE status=RUNNING sourceFileCount=1
|
||||
task.update: id=1001 status=RUNNING requestJsonHasAsinFiles=true requestJsonHasListingStatuses=true resultJsonItems=1
|
||||
result.insert: id=2001 moduleType=PRICE_TRACK sourceFilename=店铺A sourceFileUrl=shop-店铺A success=0
|
||||
payloadSaves=1
|
||||
payload country=UK rows=2
|
||||
row: asin=B011 price=19.90 minimumPrice=18.00
|
||||
row: asin=b012 price=20.00 minimumPrice=-
|
||||
payload country=DE rows=1
|
||||
row: asin=B021 price=5.00
|
||||
heartbeatTouches=1
|
||||
== case=statusMode
|
||||
vo: taskId=1001 items=1
|
||||
item: resultId=2001 shopName=店铺A matched=true taskStatus=RUNNING success=false
|
||||
vo: asinRowsByCountry=0 skipAsinsByCountry=0 minimumPriceByCountry=0
|
||||
task.insert: id=1001 moduleType=PRICE_TRACK taskMode=PYTHON_QUEUE status=RUNNING sourceFileCount=1
|
||||
task.update: id=1001 status=RUNNING requestJsonHasAsinFiles=false requestJsonHasListingStatuses=true resultJsonItems=1
|
||||
result.insert: id=2001 moduleType=PRICE_TRACK sourceFilename=店铺A sourceFileUrl=shop-店铺A success=0
|
||||
payloadSaves=0
|
||||
heartbeatTouches=1
|
||||
== case=bothModes
|
||||
thrown: BusinessException message=跟价模式必须二选一
|
||||
payloadSaves=0
|
||||
heartbeatTouches=0
|
||||
== case=neitherMode
|
||||
thrown: BusinessException message=跟价模式必须二选一
|
||||
payloadSaves=0
|
||||
heartbeatTouches=0
|
||||
== case=asinModeWithoutFiles
|
||||
thrown: BusinessException message=自定义 ASIN 模式必须上传 ASIN 文件
|
||||
payloadSaves=0
|
||||
heartbeatTouches=0
|
||||
== case=unmatchedShop
|
||||
thrown: BusinessException message=存在未匹配店铺,无法创建任务: 店铺C
|
||||
payloadSaves=0
|
||||
heartbeatTouches=0
|
||||
@@ -0,0 +1,101 @@
|
||||
== case=happyShop
|
||||
mergedSave: taskId=1001 shopKey=店铺A shopName=店铺A error=- success=true countries=1
|
||||
row: country=UK asin=B001 price=19.90 changeStatus=改价成功 modifyCount=- rows=1
|
||||
payloadSave: taskId=1001 moduleType=PRICE_TRACK scopeKey=店铺A shopName=店铺A error=- success=true countries=1
|
||||
row: country=UK asin=B001 price=19.90 changeStatus=改价成功 modifyCount=1 rows=1
|
||||
result.update: id=2001 success=1 error=- filename=店铺A.xlsx urlPresent=false size=0 contentType=application/vnd.openxmlformats-officedocument.spreadsheetml.sheet rowCount=1
|
||||
enqueue: taskId=1001 moduleType=PRICE_TRACK resultId=2001 scopeKey=店铺A
|
||||
mergedRemove: taskId=1001 shopKey=店铺A
|
||||
task.update: id=1001 status=RUNNING ok=0 fail=0 sourceFileCount=2 error=- resultJsonItems=2 finishedPresent=false
|
||||
events=6 heartbeatTouches=1 lockCloses=1
|
||||
== case=unknownShopWritesNothing
|
||||
events=0 heartbeatTouches=1 lockCloses=1
|
||||
== case=successFalseWithRowsProducesPartial
|
||||
mergedSave: taskId=1001 shopKey=店铺A shopName=店铺A error=- success=false countries=1
|
||||
row: country=UK asin=B001 price=19.90 changeStatus=- modifyCount=- rows=1
|
||||
result.update: id=2001 success=0 error=shop processing failed filename=- urlPresent=false size=0 contentType=- rowCount=0
|
||||
payloadSave: taskId=1001 moduleType=PRICE_TRACK scopeKey=店铺A shopName=店铺A error=- success=false countries=1
|
||||
row: country=UK asin=B001 price=19.90 changeStatus=- modifyCount=0 rows=1
|
||||
result.update: id=2001 success=0 error=shop processing failed filename=店铺A.xlsx urlPresent=false size=0 contentType=application/vnd.openxmlformats-officedocument.spreadsheetml.sheet rowCount=1
|
||||
enqueue: taskId=1001 moduleType=PRICE_TRACK resultId=2001 scopeKey=店铺A
|
||||
mergedRemove: taskId=1001 shopKey=店铺A
|
||||
task.update: id=1001 status=RUNNING ok=0 fail=0 sourceFileCount=2 error=- resultJsonItems=2 finishedPresent=false
|
||||
events=7 heartbeatTouches=1 lockCloses=1
|
||||
== case=errorWithRows
|
||||
mergedSave: taskId=1001 shopKey=店铺A shopName=店铺A error=店铺登录失败 success=true countries=1
|
||||
row: country=UK asin=B001 price=19.90 changeStatus=- modifyCount=- rows=1
|
||||
result.update: id=2001 success=0 error=店铺登录失败 filename=- urlPresent=false size=0 contentType=- rowCount=0
|
||||
payloadSave: taskId=1001 moduleType=PRICE_TRACK scopeKey=店铺A shopName=店铺A error=店铺登录失败 success=true countries=1
|
||||
row: country=UK asin=B001 price=19.90 changeStatus=- modifyCount=0 rows=1
|
||||
result.update: id=2001 success=0 error=店铺登录失败 filename=店铺A.xlsx urlPresent=false size=0 contentType=application/vnd.openxmlformats-officedocument.spreadsheetml.sheet rowCount=1
|
||||
enqueue: taskId=1001 moduleType=PRICE_TRACK resultId=2001 scopeKey=店铺A
|
||||
mergedRemove: taskId=1001 shopKey=店铺A
|
||||
task.update: id=1001 status=RUNNING ok=0 fail=0 sourceFileCount=2 error=- resultJsonItems=2 finishedPresent=false
|
||||
events=7 heartbeatTouches=1 lockCloses=1
|
||||
== case=errorWithoutRows
|
||||
mergedSave: taskId=1001 shopKey=店铺A shopName=店铺A error=店铺登录失败 success=true countries=0 rows=0
|
||||
result.update: id=2001 success=0 error=店铺登录失败 filename=- urlPresent=false size=0 contentType=- rowCount=0
|
||||
mergedRemove: taskId=1001 shopKey=店铺A
|
||||
task.update: id=1001 status=RUNNING ok=0 fail=1 sourceFileCount=2 error=- resultJsonItems=2 finishedPresent=false
|
||||
events=4 heartbeatTouches=1 lockCloses=1
|
||||
== case=completedWithoutUsableRows
|
||||
mergedSave: taskId=1001 shopKey=店铺A shopName=店铺A error=- success=true countries=1
|
||||
row: country=DE asin=- price=1.00 changeStatus=- modifyCount=- rows=1
|
||||
result.update: id=2001 success=0 error=未收到有效跟价数据,未生成结果文件 filename=- urlPresent=false size=0 contentType=- rowCount=0
|
||||
mergedRemove: taskId=1001 shopKey=店铺A
|
||||
task.update: id=1001 status=RUNNING ok=0 fail=1 sourceFileCount=2 error=- resultJsonItems=2 finishedPresent=false
|
||||
events=4 heartbeatTouches=1 lockCloses=1
|
||||
== case=blankErrorFallsBackToNoUsableRowsMessage
|
||||
mergedSave: taskId=1001 shopKey=店铺A shopName=店铺A error=- success=true countries=1
|
||||
row: country=DE asin=- price=1.00 changeStatus=- modifyCount=- rows=1
|
||||
result.update: id=2001 success=0 error=未收到有效跟价数据,未生成结果文件 filename=- urlPresent=false size=0 contentType=- rowCount=0
|
||||
mergedRemove: taskId=1001 shopKey=店铺A
|
||||
task.update: id=1001 status=RUNNING ok=0 fail=1 sourceFileCount=2 error=- resultJsonItems=2 finishedPresent=false
|
||||
events=4 heartbeatTouches=1 lockCloses=1
|
||||
== case=chunkWithoutSuccessWaits
|
||||
mergedSave: taskId=1001 shopKey=店铺A shopName=店铺A error=- success=- countries=1
|
||||
row: country=UK asin=B001 price=19.90 changeStatus=- modifyCount=- rows=1
|
||||
task.update: id=1001 status=RUNNING ok=0 fail=0 sourceFileCount=2 error=- resultJsonItems=2 finishedPresent=false
|
||||
events=2 heartbeatTouches=1 lockCloses=1
|
||||
== case=chunkedMergeAcrossTwoSubmissions
|
||||
mergedSave: taskId=1001 shopKey=店铺A shopName=店铺A error=- success=true countries=1
|
||||
row: country=UK asin=B001 price=19.90 changeStatus=UPDATED modifyCount=- rows=1
|
||||
payloadSave: taskId=1001 moduleType=PRICE_TRACK scopeKey=店铺A shopName=店铺A error=- success=true countries=1
|
||||
row: country=UK asin=B001 price=19.90 changeStatus=UPDATED modifyCount=1 rows=1
|
||||
result.update: id=2001 success=1 error=- filename=店铺A.xlsx urlPresent=false size=0 contentType=application/vnd.openxmlformats-officedocument.spreadsheetml.sheet rowCount=1
|
||||
enqueue: taskId=1001 moduleType=PRICE_TRACK resultId=2001 scopeKey=店铺A
|
||||
mergedRemove: taskId=1001 shopKey=店铺A
|
||||
task.update: id=1001 status=RUNNING ok=0 fail=0 sourceFileCount=2 error=- resultJsonItems=2 finishedPresent=false
|
||||
events=6 heartbeatTouches=2 lockCloses=2
|
||||
== case=skipAsinDeleteSignalChangesNothing
|
||||
mergedSave: taskId=1001 shopKey=店铺A shopName=店铺A error=- success=true countries=1
|
||||
row: country=UK asin=B002 price=8.00 changeStatus=- modifyCount=- rows=1
|
||||
payloadSave: taskId=1001 moduleType=PRICE_TRACK scopeKey=店铺A shopName=店铺A error=- success=true countries=1
|
||||
row: country=UK asin=B002 price=8.00 changeStatus=- modifyCount=0 rows=1
|
||||
result.update: id=2001 success=1 error=- filename=店铺A.xlsx urlPresent=false size=0 contentType=application/vnd.openxmlformats-officedocument.spreadsheetml.sheet rowCount=1
|
||||
enqueue: taskId=1001 moduleType=PRICE_TRACK resultId=2001 scopeKey=店铺A
|
||||
mergedRemove: taskId=1001 shopKey=店铺A
|
||||
task.update: id=1001 status=RUNNING ok=0 fail=0 sourceFileCount=2 error=- resultJsonItems=2 finishedPresent=false
|
||||
events=6 heartbeatTouches=1 lockCloses=1
|
||||
== case=allShopsFailedFinalizesTask
|
||||
mergedSave: taskId=1001 shopKey=店铺A shopName=店铺A error=- success=false countries=0 rows=0
|
||||
result.update: id=2001 success=0 error=shop processing failed filename=- urlPresent=false size=0 contentType=- rowCount=0
|
||||
mergedRemove: taskId=1001 shopKey=店铺A
|
||||
mergedSave: taskId=1001 shopKey=店铺B shopName=店铺B error=- success=false countries=0 rows=0
|
||||
result.update: id=2002 success=0 error=shop processing failed filename=- urlPresent=false size=0 contentType=- rowCount=0
|
||||
mergedRemove: taskId=1001 shopKey=店铺B
|
||||
task.update: id=1001 status=FAILED ok=0 fail=2 sourceFileCount=2 error=店铺A: shop processing failed; 店铺B: shop processing failed resultJsonItems=2 finishedPresent=true
|
||||
taskCacheDelete: taskId=1001
|
||||
loopRunSync: taskId=1001
|
||||
events=9 heartbeatTouches=1 lockCloses=1
|
||||
== case=terminalTaskRejectedWith40901
|
||||
thrown: BusinessException code=40901 message=任务已结束,拒绝重复提交
|
||||
== case=wrongModuleTaskNotFound
|
||||
thrown: BusinessException code=- message=任务不存在
|
||||
== case=invalidTaskIdRejectedBeforeLock
|
||||
thrown: BusinessException code=- message=taskId 不合法
|
||||
events=0 heartbeatTouches=0 lockCloses=0
|
||||
== case=emptyShops
|
||||
thrown: BusinessException code=- message=shops 不能为空
|
||||
== case=nullRequest
|
||||
thrown: BusinessException code=- message=shops 不能为空
|
||||
@@ -0,0 +1,45 @@
|
||||
== case=immediate
|
||||
vo: taskId=1001 items=2
|
||||
item: resultId=2001 shopName=店铺A shopId=shop-店铺A matched=true matchStatus=MATCHED taskStatus=RUNNING success=false scheduledAtPresent=false
|
||||
item: resultId=2002 shopName=店铺B shopId=shop-店铺B matched=true matchStatus=MATCHED taskStatus=RUNNING success=false scheduledAtPresent=false
|
||||
task.insert: id=1001 moduleType=SHOP_MATCH taskMode=PYTHON_QUEUE status=RUNNING sourceFileCount=2 deviceId=dev-1 scheduledAtPresent=false
|
||||
task.update: id=1001 status=RUNNING requestJsonStageIndexZero=false requestJsonStageIndexNull=true resultJsonResultIds=2
|
||||
result.insert: id=2001 taskId=1001 moduleType=SHOP_MATCH sourceFilename=店铺A sourceFileUrl=shop-店铺A success=0
|
||||
result.insert: id=2002 taskId=1001 moduleType=SHOP_MATCH sourceFilename=店铺B sourceFileUrl=shop-店铺B success=0
|
||||
heartbeatTouches=1
|
||||
== case=usNotSupportedCountry
|
||||
thrown: BusinessException message=非法国家代码: US
|
||||
heartbeatTouches=0
|
||||
== case=dedupedByNormalizedName
|
||||
vo: taskId=1001 items=2
|
||||
item: resultId=2001 shopName=店铺A shopId=shop-店铺A matched=true matchStatus=MATCHED taskStatus=RUNNING success=false scheduledAtPresent=false
|
||||
item: resultId=2002 shopName=店铺B shopId=shop-店铺B matched=true matchStatus=MATCHED taskStatus=RUNNING success=false scheduledAtPresent=false
|
||||
task.insert: id=1001 moduleType=SHOP_MATCH taskMode=PYTHON_QUEUE status=RUNNING sourceFileCount=2 deviceId=dev-1 scheduledAtPresent=false
|
||||
task.update: id=1001 status=RUNNING requestJsonStageIndexZero=false requestJsonStageIndexNull=true resultJsonResultIds=2
|
||||
result.insert: id=2001 taskId=1001 moduleType=SHOP_MATCH sourceFilename=店铺A sourceFileUrl=shop-店铺A success=0
|
||||
result.insert: id=2002 taskId=1001 moduleType=SHOP_MATCH sourceFilename=店铺B sourceFileUrl=shop-店铺B success=0
|
||||
heartbeatTouches=1
|
||||
== case=scheduled
|
||||
vo: taskId=1001 items=2
|
||||
item: resultId=2001 shopName=店铺A shopId=shop-店铺A matched=true matchStatus=MATCHED taskStatus=SCHEDULED success=false scheduledAtPresent=false
|
||||
item: resultId=2002 shopName=店铺B shopId=shop-店铺B matched=true matchStatus=MATCHED taskStatus=SCHEDULED success=false scheduledAtPresent=false
|
||||
task.insert: id=1001 moduleType=SHOP_MATCH taskMode=PYTHON_QUEUE status=SCHEDULED sourceFileCount=2 deviceId=dev-1 scheduledAtPresent=true
|
||||
task.update: id=1001 status=SCHEDULED requestJsonStageIndexZero=true requestJsonStageIndexNull=false resultJsonResultIds=2
|
||||
result.insert: id=2001 taskId=1001 moduleType=SHOP_MATCH sourceFilename=店铺A sourceFileUrl=shop-店铺A success=0
|
||||
result.insert: id=2002 taskId=1001 moduleType=SHOP_MATCH sourceFilename=店铺B sourceFileUrl=shop-店铺B success=0
|
||||
heartbeatTouches=0
|
||||
== case=unmatchedShop
|
||||
thrown: BusinessException message=存在未匹配店铺,无法创建任务
|
||||
heartbeatTouches=0
|
||||
== case=badCountryCode
|
||||
thrown: BusinessException message=非法国家代码: CN
|
||||
heartbeatTouches=0
|
||||
== case=emptyCountryCodes
|
||||
thrown: BusinessException message=country_codes 不能为空
|
||||
heartbeatTouches=0
|
||||
== case=scheduleInPast
|
||||
thrown: BusinessException message=schedule_times 必须晚于当前时间
|
||||
heartbeatTouches=0
|
||||
== case=scheduleNotIncreasing
|
||||
thrown: BusinessException message=schedule_times 必须按时间递增
|
||||
heartbeatTouches=0
|
||||
@@ -0,0 +1,76 @@
|
||||
== case=happyTwoShops
|
||||
mergedSave: taskId=1001 shopKey=店铺A shopName=店铺A error=- countries=1 rows=1 skipDetailCountries=0
|
||||
payloadSave: taskId=1001 moduleType=SHOP_MATCH scopeKey=店铺A shopName=店铺A error=- countries=1 rows=1 skipDetailCountries=0
|
||||
result.update: id=2001 success=1 error=- filename=店铺A.xlsx urlPresent=false size=0 contentType=application/vnd.openxmlformats-officedocument.spreadsheetml.sheet rowCount=1
|
||||
enqueue: taskId=1001 moduleType=SHOP_MATCH resultId=2001 scopeKey=店铺A
|
||||
mergedRemove: taskId=1001 shopKey=店铺A
|
||||
mergedSave: taskId=1001 shopKey=店铺B shopName=店铺B error=- countries=1 rows=1 skipDetailCountries=0
|
||||
payloadSave: taskId=1001 moduleType=SHOP_MATCH scopeKey=店铺B shopName=店铺B error=- countries=1 rows=1 skipDetailCountries=0
|
||||
result.update: id=2002 success=1 error=- filename=店铺B.xlsx urlPresent=false size=0 contentType=application/vnd.openxmlformats-officedocument.spreadsheetml.sheet rowCount=1
|
||||
enqueue: taskId=1001 moduleType=SHOP_MATCH resultId=2002 scopeKey=店铺B
|
||||
mergedRemove: taskId=1001 shopKey=店铺B
|
||||
task.update: id=1001 status=RUNNING ok=0 fail=0 sourceFileCount=null error=- resultJsonItems=2 finishedPresent=false
|
||||
taskCacheSave: id=1001
|
||||
events=12 heartbeatTouches=1 lockCloses=1
|
||||
== case=unknownShopWritesNothing
|
||||
events=0 heartbeatTouches=1 lockCloses=1
|
||||
== case=nullAndBlankShopSkipped
|
||||
events=0 heartbeatTouches=1 lockCloses=1
|
||||
== case=failedShopWithPartialRows
|
||||
mergedSave: taskId=1001 shopKey=店铺A shopName=店铺A error=会话掉线 countries=1 rows=1 skipDetailCountries=0
|
||||
result.update: id=2001 success=0 error=会话掉线 filename=- urlPresent=false size=0 contentType=- rowCount=0
|
||||
payloadSave: taskId=1001 moduleType=SHOP_MATCH scopeKey=店铺A shopName=店铺A error=会话掉线 countries=1 rows=1 skipDetailCountries=0
|
||||
result.update: id=2001 success=0 error=会话掉线 filename=店铺A.xlsx urlPresent=false size=0 contentType=application/vnd.openxmlformats-officedocument.spreadsheetml.sheet rowCount=1
|
||||
enqueue: taskId=1001 moduleType=SHOP_MATCH resultId=2001 scopeKey=店铺A
|
||||
mergedRemove: taskId=1001 shopKey=店铺A
|
||||
task.update: id=1001 status=RUNNING ok=0 fail=0 sourceFileCount=null error=- resultJsonItems=2 finishedPresent=false
|
||||
taskCacheSave: id=1001
|
||||
events=8 heartbeatTouches=1 lockCloses=1
|
||||
== case=failedShopWithoutRows
|
||||
mergedSave: taskId=1001 shopKey=店铺A shopName=店铺A error=店铺打不开 countries=0 rows=0 skipDetailCountries=0
|
||||
result.update: id=2001 success=0 error=店铺打不开 filename=- urlPresent=false size=0 contentType=- rowCount=0
|
||||
mergedRemove: taskId=1001 shopKey=店铺A
|
||||
task.update: id=1001 status=RUNNING ok=0 fail=1 sourceFileCount=null error=- resultJsonItems=2 finishedPresent=false
|
||||
taskCacheSave: id=1001
|
||||
events=5 heartbeatTouches=1 lockCloses=1
|
||||
== case=allShopsFailedFinalizesTask
|
||||
mergedSave: taskId=1001 shopKey=店铺A shopName=店铺A error=店铺打不开 countries=0 rows=0 skipDetailCountries=0
|
||||
result.update: id=2001 success=0 error=店铺打不开 filename=- urlPresent=false size=0 contentType=- rowCount=0
|
||||
mergedRemove: taskId=1001 shopKey=店铺A
|
||||
mergedSave: taskId=1001 shopKey=店铺B shopName=店铺B error=国家页超时 countries=0 rows=0 skipDetailCountries=0
|
||||
result.update: id=2002 success=0 error=国家页超时 filename=- urlPresent=false size=0 contentType=- rowCount=0
|
||||
mergedRemove: taskId=1001 shopKey=店铺B
|
||||
task.update: id=1001 status=FAILED ok=0 fail=2 sourceFileCount=null error=店铺A: 店铺打不开;店铺B: 国家页超时 resultJsonItems=2 finishedPresent=true
|
||||
taskCacheSave: id=1001
|
||||
taskCacheDelete: taskId=1001
|
||||
events=9 heartbeatTouches=1 lockCloses=1
|
||||
== case=blankAsinWithDoneFlagStillWaits
|
||||
mergedSave: taskId=1001 shopKey=店铺A shopName=店铺A error=- countries=1 rows=1 skipDetailCountries=0
|
||||
task.update: id=1001 status=RUNNING ok=0 fail=0 sourceFileCount=null error=- resultJsonItems=2 finishedPresent=false
|
||||
taskCacheSave: id=1001
|
||||
events=3 heartbeatTouches=1 lockCloses=1
|
||||
== case=partialChunkWaitsForMore
|
||||
mergedSave: taskId=1001 shopKey=店铺A shopName=店铺A error=- countries=1 rows=1 skipDetailCountries=0
|
||||
task.update: id=1001 status=RUNNING ok=0 fail=0 sourceFileCount=null error=- resultJsonItems=2 finishedPresent=false
|
||||
taskCacheSave: id=1001
|
||||
events=3 heartbeatTouches=1 lockCloses=1
|
||||
== case=chunkedMergeAcrossTwoSubmissions
|
||||
mergedSave: taskId=1001 shopKey=店铺A shopName=店铺A error=- countries=1 rows=1 skipDetailCountries=0
|
||||
payloadSave: taskId=1001 moduleType=SHOP_MATCH scopeKey=店铺A shopName=店铺A error=- countries=1 rows=1 skipDetailCountries=0
|
||||
result.update: id=2001 success=1 error=- filename=店铺A.xlsx urlPresent=false size=0 contentType=application/vnd.openxmlformats-officedocument.spreadsheetml.sheet rowCount=1
|
||||
enqueue: taskId=1001 moduleType=SHOP_MATCH resultId=2001 scopeKey=店铺A
|
||||
mergedRemove: taskId=1001 shopKey=店铺A
|
||||
task.update: id=1001 status=RUNNING ok=0 fail=0 sourceFileCount=null error=- resultJsonItems=2 finishedPresent=false
|
||||
taskCacheSave: id=1001
|
||||
events=7 heartbeatTouches=2 lockCloses=2
|
||||
== case=terminalTaskRejectedWith40901
|
||||
thrown: BusinessException code=40901 message=任务已结束,拒绝重复提交
|
||||
== case=wrongModuleTaskNotFound
|
||||
thrown: BusinessException code=- message=任务不存在
|
||||
== case=invalidTaskIdRejectedBeforeLock
|
||||
thrown: BusinessException code=- message=taskId 不合法
|
||||
events=0 heartbeatTouches=0 lockCloses=0
|
||||
== case=emptyShops
|
||||
thrown: BusinessException code=- message=shops 不能为空
|
||||
== case=nullRequest
|
||||
thrown: BusinessException code=- message=shops 不能为空
|
||||
@@ -172,6 +172,7 @@ import {
|
||||
import { getPollingProgressBatch } from '@/shared/api/task-progress-polling.ts'
|
||||
import { formatDateTime } from '@/shared/utils/datetime'
|
||||
import { taskStatusClass, taskStatusText } from '@/shared/utils/task-status-text'
|
||||
import { terminalKeywordShortfall } from '@/shared/utils/task-progress-readout'
|
||||
import { runBatchDelete } from '@/shared/utils/batch-delete'
|
||||
import { confirmTaskDeletion } from '@/shared/task-delete-confirm'
|
||||
|
||||
@@ -678,6 +679,7 @@ function toCollectTaskView(item: CollectDataHistoryItem): TaskItemView {
|
||||
const isActive = isCollectTaskActive(item)
|
||||
const keywordProgress = taskKeywordProgress(item)
|
||||
const stageProgress = taskStageProgress(item)
|
||||
const shortfall = terminalKeywordShortfall(item)
|
||||
const percent = taskProgressPercent(item)
|
||||
const finishedAt = item.finishedAt ? formatDateTime(item.finishedAt) : isActive ? '进行中' : '-'
|
||||
const extraLines: string[] = isActive
|
||||
@@ -693,6 +695,9 @@ function toCollectTaskView(item: CollectDataHistoryItem): TaskItemView {
|
||||
`不符合 ASIN 过滤:${item.invalidFilteredCount ?? 0}`,
|
||||
...(item.resultFilename ? [item.resultFilename] : []),
|
||||
...(taskFilterSummary(item) ? [`筛选统计:${taskFilterSummary(item)}`] : []),
|
||||
// 终态却没跑完全部关键词:把缺口写在卡片上。此前只有那根 25% 的进度条在说话,
|
||||
// 而卡片同时写着「已完成」,读起来像是进度条坏了,实际是它在报任务提前结束。
|
||||
...(shortfall ? [shortfall] : []),
|
||||
...(item.error ? [`错误:${userNotice(item.error)}`] : []),
|
||||
]
|
||||
return {
|
||||
|
||||
@@ -99,11 +99,7 @@
|
||||
<el-pagination v-if="candidateTotal > candidatePageSize" class="candidate-pagination"
|
||||
layout="total, prev, pager, next" :total="candidateTotal" :page-size="candidatePageSize"
|
||||
v-model:current-page="candidatePage" />
|
||||
<div v-if="candidateSelectionNotice || rememberedCandidates.length" class="hint">
|
||||
<span v-if="candidateSelectionNotice">{{ candidateSelectionNotice }}</span>
|
||||
<button v-if="rememberedCandidates.length" type="button" class="link-danger"
|
||||
@click="clearCandidateSelectionMemory">清除勾选记忆(共 {{ rememberedCandidates.length }} 家)</button>
|
||||
</div>
|
||||
<div v-if="candidateSelectionNotice" class="hint">{{ candidateSelectionNotice }}</div>
|
||||
</div>
|
||||
|
||||
<template v-if="!asinModeEnabled">
|
||||
@@ -833,13 +829,6 @@ async function restoreCandidateSelection() {
|
||||
candidateSelectionNotice.value = selectionNotice(rows.length)
|
||||
}
|
||||
|
||||
function clearCandidateSelectionMemory() {
|
||||
rememberedCandidates.value = []
|
||||
candidateSelectionNotice.value = ''
|
||||
saveSelectionMemory()
|
||||
candidateTableRef.value?.clearSelection()
|
||||
}
|
||||
|
||||
function onSelectionChange(rows: PriceTrackCandidateVo[]) {
|
||||
selectedCandidates.value = rows || []
|
||||
if (restoringSelection) return
|
||||
|
||||
@@ -68,17 +68,7 @@
|
||||
:page-size="candidatePageSize"
|
||||
v-model:current-page="candidatePage"
|
||||
/>
|
||||
<div v-if="candidateSelectionNotice || rememberedCandidates.length" class="loading-msg">
|
||||
<span v-if="candidateSelectionNotice">{{ candidateSelectionNotice }}</span>
|
||||
<button
|
||||
v-if="rememberedCandidates.length"
|
||||
type="button"
|
||||
class="link-danger"
|
||||
@click="clearCandidateSelectionMemory"
|
||||
>
|
||||
清除勾选记忆(共 {{ rememberedCandidates.length }} 家)
|
||||
</button>
|
||||
</div>
|
||||
<div v-if="candidateSelectionNotice" class="loading-msg">{{ candidateSelectionNotice }}</div>
|
||||
|
||||
|
||||
<div class="run-row">
|
||||
@@ -852,13 +842,6 @@ async function restoreCandidateSelection() {
|
||||
candidateSelectionNotice.value = selectionNotice(rows.length);
|
||||
}
|
||||
|
||||
function clearCandidateSelectionMemory() {
|
||||
rememberedCandidates.value = [];
|
||||
candidateSelectionNotice.value = "";
|
||||
saveSelectionMemory();
|
||||
candidateTableRef.value?.clearSelection();
|
||||
}
|
||||
|
||||
function onSelectionChange(rows: QueryAsinCandidateVo[]) {
|
||||
selectedCandidates.value = rows;
|
||||
if (restoringSelection) return;
|
||||
|
||||
@@ -146,7 +146,7 @@ import {
|
||||
} from '@/shared/dispatch-guard'
|
||||
import { passGuard } from '@/shared/dispatch-guard-ui'
|
||||
import { formatDateTime } from '@/shared/utils/datetime'
|
||||
import { resultBuildFailed, taskStatusClass, taskStatusText } from '@/shared/utils/task-status-text'
|
||||
import { isCompletedTask, resultBuildFailed, taskStatusClass, taskStatusText } from '@/shared/utils/task-status-text'
|
||||
import { getStoredApiSecret } from '@/shared/utils/api-secret-store'
|
||||
|
||||
// ---- 文件选择 / 上传(公共组合式函数)----
|
||||
@@ -305,19 +305,20 @@ function toAsinTaskView(item: SimilarAsinHistoryItem): TaskItemView {
|
||||
|
||||
function statusText(item: SimilarAsinHistoryItem) {
|
||||
const status = normalizeTaskStatus(item)
|
||||
if (status === 'FAILED') return taskStatusText('FAILED')
|
||||
if (status === 'RUNNING') return taskStatusText(status)
|
||||
if (status === 'PENDING') return taskStatusText(status, { text: { PENDING: '已解析待启动' } })
|
||||
if (isResultPreparing(item)) return '结果生成中'
|
||||
if (isResultBuildFailed(item)) return '结果生成失败'
|
||||
if (status === 'SUCCESS' || item.success) return taskStatusText('SUCCESS')
|
||||
return status === 'FAILED' ? taskStatusText('FAILED') : '等待中'
|
||||
if (isCompletedTask(status)) return taskStatusText('SUCCESS')
|
||||
return '等待中'
|
||||
}
|
||||
|
||||
function statusClass(item: SimilarAsinHistoryItem) {
|
||||
const status = normalizeTaskStatus(item)
|
||||
if (status === 'FAILED' || isResultBuildFailed(item)) return taskStatusClass('FAILED')
|
||||
if (status === 'RUNNING' || isResultPreparing(item)) return taskStatusClass('RUNNING')
|
||||
if (isResultBuildFailed(item) || status === 'FAILED') return taskStatusClass('FAILED')
|
||||
if (status === 'SUCCESS' || item.success) return taskStatusClass('SUCCESS')
|
||||
if (isCompletedTask(status)) return taskStatusClass('SUCCESS')
|
||||
return 'pending'
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* 终态任务卡片的进度读数。
|
||||
*
|
||||
* 为什么单独放一个文件:这条判据只能从 .vue 里挂出来测(本套件没有 @vue/test-utils,
|
||||
* 见 tests/task-terminal-completed-behavior.test.ts 的说明),而它恰好是线上事故
|
||||
* (task 31253:已完成 + 总进度 25% + 下载空白)里唯一说真话的那一格。
|
||||
*
|
||||
* 铁律:**不许**因为状态是 SUCCESS 就把没跑完的关键词抹成 100%。
|
||||
* processedRows < totalRows 是「任务提前结束」的表征,把它显示出来是这条读数的用途,
|
||||
* 不是它的 bug。
|
||||
*/
|
||||
|
||||
import { isTerminalTaskStatus } from './task-terminal.ts'
|
||||
|
||||
export interface TerminalProgressItem {
|
||||
taskStatus?: string | null
|
||||
success?: boolean | null
|
||||
processedRows?: number | null
|
||||
totalRows?: number | null
|
||||
}
|
||||
|
||||
function isTerminal(item: TerminalProgressItem): boolean {
|
||||
return item.success === true || isTerminalTaskStatus(item.taskStatus || undefined)
|
||||
}
|
||||
|
||||
/**
|
||||
* 终态且关键词没跑完时返回一句缺口说明,否则返回空串。
|
||||
* 行数缺失(totalRows 非正数)时不猜,返回空串——没有分母就没有缺口可言。
|
||||
*/
|
||||
export function terminalKeywordShortfall(item: TerminalProgressItem): string {
|
||||
if (!isTerminal(item)) return ''
|
||||
const total = Number(item.totalRows)
|
||||
const processed = Number(item.processedRows ?? 0)
|
||||
if (!Number.isFinite(total) || total <= 0) return ''
|
||||
if (!Number.isFinite(processed) || processed >= total) return ''
|
||||
const status = (item.taskStatus || '').toUpperCase()
|
||||
const label = status === 'FAILED' ? '任务失败于' : '任务提前结束于'
|
||||
return `关键词缺口:${label} ${processed}/${total},还有 ${total - processed} 个关键词未采集`
|
||||
}
|
||||
@@ -124,3 +124,15 @@ export function resultBuildFailed(fileStatus?: string | null, downloadable = fal
|
||||
if (downloadable) return false;
|
||||
return (fileStatus || '').toUpperCase() === 'FAILED';
|
||||
}
|
||||
|
||||
/**
|
||||
* 任务行终态是否算「已完成」——结果行的 success 位不参与判定。
|
||||
*
|
||||
* `biz_file_result.success` 是 `NOT NULL DEFAULT 1` 的列:解析建行那一刻就是 1,只有走正常收尾才回写。
|
||||
* 而通用兜底判死只 UPDATE `biz_file_task`,不碰这一列,于是被心跳超时判死的任务它仍是 1。
|
||||
* 2026-10-16 任务 31060(客户端只回传 51/510 分片、结果文件从未生成)就是这样显示成「已完成」的。
|
||||
*/
|
||||
export function isCompletedTask(taskStatus?: string | null): boolean {
|
||||
const key = normalizeStatusKey(taskStatus);
|
||||
return key === 'SUCCESS' || key === 'COMPLETED';
|
||||
}
|
||||
|
||||
@@ -81,10 +81,9 @@ for (const { file, tab, nameField } of PAGES) {
|
||||
assert.match(load, /parseRememberedNames\(/, '读回来的没经脏数据收口')
|
||||
})
|
||||
|
||||
test(`${file} 有清除入口,且清的是记忆本身`, () => {
|
||||
const clear = functionBody(source, 'function clearCandidateSelectionMemory(')
|
||||
assert.match(clear, /rememberedCandidates\.value = \[\]/, '没清内存里的名单')
|
||||
assert.ok(clear.includes('saveSelectionMemory()'), '没写回 localStorage,下次启动又恢复')
|
||||
assert.match(source, /@click="clearCandidateSelectionMemory/, '界面上没有清除勾选记忆入口')
|
||||
test(`${file} 勾选区不留红字清除入口`, () => {
|
||||
// 记忆的唯一出口是取消勾选本身:onSelectionChange 按本窗口重算并写回(上一条用例钉的就是这条)
|
||||
assert.ok(!source.includes('clearCandidateSelectionMemory'), '勾选区又长出了清除勾选记忆入口')
|
||||
assert.ok(!source.includes('清除勾选记忆'), '勾选区又出现了红字提示文案')
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { resolve, dirname } from 'node:path'
|
||||
import { isCompletedTask } from '../src/shared/utils/task-status-text.ts'
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
|
||||
function tabSource(name: string): string {
|
||||
return readFileSync(resolve(here, `../src/pages/brand/components/${name}.vue`), 'utf-8')
|
||||
}
|
||||
|
||||
function bodyOf(source: string, name: string): string {
|
||||
const match = source.match(new RegExp(`function ${name}\\([\\s\\S]*?\\n\\}`))
|
||||
assert.ok(match, `找不到函数 ${name}`)
|
||||
return match[0]
|
||||
}
|
||||
|
||||
// 2026-10-16 任务 31060:biz_file_task 已被通用兜底判死(status=FAILED,「任务心跳超时,已自动失败」),
|
||||
// 客户端只回传了 51/510 个分片,结果文件从未生成。历史列表却显示「已完成」——
|
||||
// 因为 biz_file_result.success 是 `NOT NULL DEFAULT 1` 的列,解析建行那一刻就是 1,
|
||||
// 只有走正常收尾才会回写;兜底判死只 UPDATE biz_file_task,不碰这一列。
|
||||
// 前端 `if (status === 'SUCCESS' || item.success)` 于是被这一位单独点亮。
|
||||
test('已完成只认任务行终态,结果行的 success 位不参与判定', () => {
|
||||
assert.equal(isCompletedTask('SUCCESS'), true)
|
||||
assert.equal(isCompletedTask('COMPLETED'), true)
|
||||
assert.equal(isCompletedTask('success'), true, '大小写不敏感')
|
||||
assert.equal(isCompletedTask('FAILED'), false, '任务已判死时不得算完成')
|
||||
assert.equal(isCompletedTask('RUNNING'), false)
|
||||
assert.equal(isCompletedTask('PENDING'), false)
|
||||
assert.equal(isCompletedTask(null), false, '任务行缺失时不得凭结果行默认位算完成')
|
||||
assert.equal(isCompletedTask(undefined), false)
|
||||
assert.equal(isCompletedTask(''), false)
|
||||
})
|
||||
|
||||
// 外观专利页的同型缺陷已由 appearance-patent-failed-status.test.ts 用「FAILED 分支排在最前」钉住,
|
||||
// 本次只动货源查询页,不去改另一页的历史口径。
|
||||
const source = tabSource('BrandSimilarAsinTab')
|
||||
|
||||
test('BrandSimilarAsinTab 的 statusText 必须先判 FAILED,再谈已完成', () => {
|
||||
const body = bodyOf(source, 'statusText')
|
||||
const failedIdx = body.indexOf("status === 'FAILED'")
|
||||
const completedIdx = body.indexOf('isCompletedTask(status)')
|
||||
assert.ok(failedIdx >= 0, 'statusText 缺少 FAILED 分支')
|
||||
assert.ok(completedIdx >= 0, 'statusText 必须走 isCompletedTask 判定已完成')
|
||||
assert.ok(failedIdx < completedIdx, 'FAILED 排在已完成之后时,判死任务会被别的结果位翻案')
|
||||
})
|
||||
|
||||
test('BrandSimilarAsinTab 不得再用结果行的 success 位单独点亮已完成', () => {
|
||||
for (const fn of ['statusText', 'statusClass']) {
|
||||
const body = bodyOf(source, fn)
|
||||
assert.ok(!/\|\|\s*item\.success/.test(body),
|
||||
`${fn} 里 || item.success 就是 31060 假绿灯的短路:biz_file_result.success 默认 1,判死任务不回写`)
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,47 @@
|
||||
// 终态进度读数的钉子(task 31253:已完成 + 总进度 25% + 下载空白)。
|
||||
//
|
||||
// 这条读数唯一不许被改坏的性质:**状态是 SUCCESS 不等于跑完了全部关键词**。
|
||||
// 当时卡片上只有 25% 那根条在说真话,却被当成显示 bug 报上来——所以这里钉的是
|
||||
// 「缺口必须出声」,而不是「成功就画满」。
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
|
||||
import { terminalKeywordShortfall } from '../src/shared/utils/task-progress-readout.ts'
|
||||
|
||||
test('成功态但关键词没跑完:缺口必须写在卡片上', () => {
|
||||
// 31253 的真实形状:8 个关键词只处理了 2 个,服务端却标了 SUCCESS。
|
||||
const line = terminalKeywordShortfall({ taskStatus: 'SUCCESS', processedRows: 2, totalRows: 8 })
|
||||
assert.match(line, /2\/8/, '要给出已处理/总数,用户才知道差多少')
|
||||
assert.match(line, /6 个关键词未采集/, '要给出缺口条数')
|
||||
assert.match(line, /提前结束/, '成功态下的提前结束要说清是提前结束,不是正常收尾')
|
||||
})
|
||||
|
||||
test('跑满的终态:不产生缺口说明', () => {
|
||||
assert.equal(terminalKeywordShortfall({ taskStatus: 'SUCCESS', processedRows: 8, totalRows: 8 }), '')
|
||||
assert.equal(terminalKeywordShortfall({ taskStatus: 'SUCCESS', processedRows: 9, totalRows: 8 }), '')
|
||||
})
|
||||
|
||||
test('失败态的缺口说「失败于」而不是「提前结束于」', () => {
|
||||
const line = terminalKeywordShortfall({ taskStatus: 'FAILED', processedRows: 1, totalRows: 4 })
|
||||
assert.match(line, /失败于 1\/4/)
|
||||
})
|
||||
|
||||
test('在跑的任务不归这条管:运行期缺口由关键词进度行负责', () => {
|
||||
assert.equal(terminalKeywordShortfall({ taskStatus: 'RUNNING', processedRows: 2, totalRows: 8 }), '')
|
||||
assert.equal(terminalKeywordShortfall({ taskStatus: 'PENDING', processedRows: 0, totalRows: 8 }), '')
|
||||
})
|
||||
|
||||
test('没有分母就不猜', () => {
|
||||
for (const totalRows of [null, undefined, 0, -1, Number.NaN]) {
|
||||
assert.equal(
|
||||
terminalKeywordShortfall({ taskStatus: 'SUCCESS', processedRows: 2, totalRows }),
|
||||
'',
|
||||
`totalRows=${String(totalRows)} 时不该编出一条缺口文案`,
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
test('success 布尔位也算终态(老响应体没有 taskStatus)', () => {
|
||||
const line = terminalKeywordShortfall({ success: true, processedRows: 3, totalRows: 8 })
|
||||
assert.match(line, /3\/8/)
|
||||
})
|
||||
Reference in New Issue
Block a user