Compare commits

...

4 Commits

Author SHA1 Message Date
huangzd1997 e0303f9cba feat(上架): 店铺互斥改为按(设备,店铺),同店可在不同客户端并行跑不同国家
背景:紫鸟浏览器会话是每台客户端一份,同一家店可以在两台机器上并行;
国家是会话内的可切换状态(SwitchingCountries,断线重连还会再切),
所以真正必须串行的只有"同一台设备上的同一家店"。原来的全局按店铺互斥
把跨机器的合法并行也挡了(2026-09-18 任务 28624 被 28616 误挡)。

- V130:biz_publish_file 增加 device_id 列
- AdminAuthSupport.currentDeviceId():只读 JWT 签名的 deviceId claim,
  不信任客户端可控的 X-Device-Id 请求头
- activateFile 互斥键改为 (device_id, shop_name);device 为空(旧客户端
  token 无该 claim / 内部令牌调用)时退回全局店铺互斥,保守不放宽;
  存量 RUNNING 行的 NULL device 视为"来源不明",同样保守拦到跑完为止
- 前端与客户端无需改动:页面 axios 对 /newApi 已带 Authorization Bearer
2026-09-18 16:08:08 +08:00
huangzd1997 9d39705c77 fix(采集数据): 品牌检测移出任务锁 + 失败任务仍产出可下载的部分结果
taskId 28599 事故根因:分片回传在任务锁内同步做品牌检测,上游 16890 卡死时
单次持锁 103.5 秒(costMs=103556),期间该任务的心跳与客户端重试全部撞
40902「任务正在处理」,客户端 5 次重试预算耗尽后中止了整个采集。

- submitResult:行归一化 / 去重过滤 / 品牌检测移到任务锁外,锁内只保留落库与终态
- BrandCheckClient:整批加 90 秒总耗时上限(超时按查询失败降级,首轮始终执行),
  单次回传时延从「无上界」收敛到约 90 秒 + 一次读超时
- 失败且已收到分片时照常组装部分结果;任务已 FAILED 则保留失败态与真实失败原因,
  只补结果文件(乐观写结果行 + 条件更新不匹配再补偿写回,避免崩溃时留下「成功但无下载」)
- productrisk / shopmatch 按 pricetrack 的 preserveFailure 样板补齐,含组装落地时
  不再把失败行「洗成成功」
- 前端:采集 / 跟价 / 产品风险 / 店铺匹配的下载按钮放宽到失败任务
2026-09-18 15:53:15 +08:00
huangzd1997 986df86e89 fix(任务恢复): 停止意图优先于自动续跑 + 未覆盖模块的中断可见
自查上一提交时发现两处遗漏:

- 用户点了「停止循环」而子任务恰好因客户端中断失败时,续派逻辑跑在停止检查之前,
  会把循环从停止意图里拉回 RUNNING 自己转起来。改为停止请求优先:直接 STOPPED。
- 模块不支持自动续跑的中断任务此前完全无痕迹(用户只看到失败)。
  这类模块(上架/改价/审批/商品管理采集/跟价非循环任务)的续跑载荷需要用户在页面上
  选的执行参数(ziniao_version 等),而这份选择只存在于派发那一刻的浏览器里、没落到
  request_json —— 自动重排队会用错参数,所以它们**不纳入**续跑(白名单的设计原则就是
  「执行参数全在服务端」)。现补一条计数查询把这类中断数量带进 stale-check summary
  的 resume(u=N),运维据此人工重跑;将来把参数回写落库后即可纳入白名单。

测试:PriceTrackLoopRunServiceTest 新增「已请求停止时中断失败不续派而是停止」,
TaskResumeServiceTest 新增「统计不支持续跑的中断任务数」。
2026-09-18 15:48:33 +08:00
huangzd1997 bd359411a9 feat(任务恢复): 客户端中断的任务自动续跑(保留失败记录 + 重新排队)
2026-09-18 任务 28587(跟价,uid 977 店铺「张美莺」)在客户端 09:51/09:57 被更新脚本
重启后中断,任务一直挂 RUNNING 到 stale 兜底;跟价循环还有第二重问题——子任务失败
即整个循环判 FAILED,一次客户端更新就让无限循环彻底停下。

契约:中断任务**保留失败记录**(用户看得到「因客户端重启中断」),同时由服务端自动
重新排队续跑,长任务不再因为一次更新整个白跑。

- V129:biz_file_task 加 resume_of_task_id / resume_attempt,
  biz_price_track_loop_run 加 resume_attempt(代数封顶用);
- 新增 TaskResumeService:扫描最近 30 分钟内因客户端中断而失败、未续跑过、代数未超限的
  任务,复制请求参数重新排队成 PENDING,交给已有兜底拉取通道(客户端每分钟 pull-pending)
  领走执行——不新造第二套派发机制。只对注册了 ClientTaskPullSpi 的模块生效
  (相似ASIN/采集/外观专利),上架/改价等写操作模块刻意排除,避免盲目重跑;
- 幂等:按 resume_of_task_id 反查,同一原任务不会重复排队;
- 挂在 stale-check 巡检线(每 2 分钟、有分布式锁),并用隔离壳包住异常:
  续跑失败绝不拖垮判死主流程(判死优先级更高);
- PriceTrackLoopRunService:子任务因「客户端异常中断」失败时不终止循环,
  清 active_task_id 后保持 RUNNING,客户端下次 dispatchNext 拿到同一店铺/同一轮,
  即原地续跑(页内已处理 ASIN 由服务端 skip_asins 去重,不会重复改价);
  连续重派超过 3 次才真正判失败,避免会话持续不可用时无限重开浏览器
  (28587 就是这样白烧了 5 小时)。子任务成功一轮后计数归零;
- application.yml:aiimage.task-resume.enabled 默认跟随 client-task-pull 开关
  (兜底拉取关着时续跑任务无人领取,只会积压被告死)。

测试:TaskResumeServiceTest 6 例(排队/幂等/开关/无实现/插入失败/无归属用户)、
PriceTrackLoopRunServiceTest 新增 4 例(中断续跑/达上限/非中断仍终止/成功归零),
连带更新 DeleteBrandStaleTaskServiceTest 与 TaskModuleCoverageTest 的构造参数。
2026-09-18 15:42:07 +08:00
29 changed files with 1219 additions and 94 deletions
@@ -9,6 +9,7 @@ import io.jsonwebtoken.Claims;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
@@ -19,6 +20,7 @@ import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
@Slf4j
@Component
@RequiredArgsConstructor
public class AdminAuthSupport {
@@ -62,8 +64,30 @@ public class AdminAuthSupport {
return user;
}
/** 当前用户必须是管理员或超级管理员,否则抛 403。 */
public AdminUserEntity requireAdmin(HttpServletRequest request) {
/**
* 解析当前请求 JWT 中**签名的**设备标识(deviceId claim);识别不出时返回空串。
*
* <p>无 token、token 过期/非法、内部令牌通道调用一律返回空串——调用方必须把空串
* 当作"来源不明"做保守判定,绝不据此放宽任何限制。只认签名 claim,不接受
* X-Device-Id 请求头(头由客户端可控,见 {@link DeviceSessionPolicy} 类注释)。</p>
*
* <p>本方法只做识别、不做鉴权,因此解析失败不抛异常,仅记日志后返回空串,
* 避免把匿名/内部调用直接升级成 401。</p>
*/
public String currentDeviceId(HttpServletRequest request) {
String token = resolveToken(request);
if (token == null || token.isBlank()) {
return "";
}
try {
return DeviceSessionPolicy.claimDeviceId(jwtService.parse(token));
} catch (Exception ex) {
log.warn("[auth] 解析 token 取设备标识失败,按来源不明处理: {}", ex.getMessage());
return "";
}
}
/** 当前用户必须是管理员或超级管理员,否则抛 403。 */ public AdminUserEntity requireAdmin(HttpServletRequest request) {
AdminUserEntity user = requireUser(request);
String role = currentRole(user);
if (role == null) {
@@ -23,6 +23,14 @@ public class BrandCheckProperties {
* 10 次尝试合计约 45s,既能覆盖限流窗口又不会让单个品牌长时间占住查询线程。
*/
private int retryMaxIntervalMillis = 10000;
/**
* 一次批量检查的总耗时上限(毫秒):整批用尽后不再重试,剩余品牌按「查询失败」收尾。
* 上限的意义不是省时间,而是给「分片回传」这类同步调用方一个时延上界——上游卡死时
* 单品牌 10 次重试曾把一次回传拖到 103.5 秒(taskId 28599),客户端重试预算耗尽后
* 中止了整个采集。首轮请求始终执行,故上游只是略慢时不会误降级。
* 设为 0 或负数表示不限制。
*/
private int totalTimeoutMillis = 90000;
private int connectTimeoutMillis = 10000;
private int readTimeoutMillis = 60000;
}
@@ -95,10 +95,14 @@ public class BrandCheckClient {
public BrandCheckBatchResult checkAll(List<String> brands, String strategy) {
List<String> distinctBrands = distinctNonBlank(brands);
// 整批共用一个耗时预算:上游 16890 卡死时,单品牌 10 次重试曾把一次分片回传拖到
// 103.5 秒(taskId 28599),客户端重试预算耗尽后中止了整个采集。预算用尽即停止重试。
long budgetMillis = properties.getTotalTimeoutMillis();
long deadlineNanos = budgetMillis > 0L ? System.nanoTime() + budgetMillis * 1_000_000L : Long.MAX_VALUE;
List<CompletableFuture<BrandCheckOutcome>> futures = new ArrayList<>(distinctBrands.size());
for (String brand : distinctBrands) {
futures.add(CompletableFuture.supplyAsync(
() -> checkOneBrand(brand, strategy), checkExecutor));
() -> checkOneBrand(brand, strategy, deadlineNanos), checkExecutor));
}
List<Object> failedData = new ArrayList<>();
List<Object> queryFailedData = new ArrayList<>();
@@ -110,11 +114,19 @@ public class BrandCheckClient {
return new BrandCheckBatchResult(distinctBrands, failedData, queryFailedData);
}
private BrandCheckOutcome checkOneBrand(String brand, String strategy) {
private BrandCheckOutcome checkOneBrand(String brand, String strategy, long deadlineNanos) {
int attempts = Math.max(1, properties.getRetryTimes());
BrandCheckResponse response = null;
Exception lastFailure = null;
for (int attempt = 1; attempt <= attempts; attempt++) {
// 预算用尽就不再重试,按查询失败收尾。只掐「重试」不打断已发出的请求,
// 故最坏耗时 ≈ 预算 + 一次请求的读超时;首轮始终执行,避免上游只是慢一点时被误降级。
if (attempt > 1 && System.nanoTime() >= deadlineNanos) {
log.warn("[brand-check] 整批耗时预算用尽,停止重试 brand={} attempt={}/{} lastErr={}",
brand, attempt, attempts,
lastFailure == null ? "query_faild_data 持续非空" : lastFailure.getMessage());
break;
}
try {
response = check(brand, strategy);
} catch (Exception ex) {
@@ -782,6 +782,39 @@ public class CollectDataService {
throw new BusinessException("request is empty");
}
ensureRustfsPayloadStorageEnabled();
// 锁外预检:任务不存在/已结束时立即失败,不为终态任务白跑去重查询与品牌检测。
// 只做快速失败,并发正确性仍由锁内的重读复核保证。
FileTaskEntity probe = fileTaskMapper.selectById(taskId);
if (probe == null || !MODULE_TYPE.equals(probe.getModuleType())) {
throw new BusinessException("任务不存在");
}
if (STATUS_SUCCESS.equals(probe.getStatus()) || STATUS_FAILED.equals(probe.getStatus())) {
log.warn("[collect-data] 任务已结束,拒绝重复提交 taskId={} status={}", taskId, probe.getStatus());
throw new BusinessException(40901, "任务已结束,拒绝重复提交");
}
// 归一化 / 去重过滤 / 品牌检测放在锁外:品牌检测是同步远程调用,上游 16890 抖动时
// 单品牌 10 次重试合计上百秒(taskId 28599 实测:chunk 回传在锁内等品牌检测 103.5 秒,
// 期间心跳与客户端重试全部撞 40902 拿不到锁,客户端 5 次重试预算耗尽后中止整个采集)。
// 这几步只依赖本批入参、不写任务状态,放锁外不改变 chunk 落库的串行语义。
List<CollectDataResultRowVo> rows = normalizeSubmitRows(request.getItems());
buildParseLimits().validateChunkRowCount(rows.size());
// 「结果文件」sheet 需要 Python 回传的全量数据(不经任何后端过滤),
// 因此 chunk payload 写入未筛除空 ASIN 的全量 rows;
// 仅当 ASIN 非空时才进入去重 / 无效品牌 / 品牌检测链路并落 biz_task_result_item。
List<CollectDataResultRowVo> rowsForFiltering = new ArrayList<>(rows.size());
for (CollectDataResultRowVo row : rows) {
if (row.getAsin() != null && !row.getAsin().isBlank()) {
rowsForFiltering.add(row);
}
}
long prepareStartAt = System.currentTimeMillis();
CollectDataBatchQuery.FilterResult filtered = collectDataBatchQuery.filter(rowsForFiltering);
CollectDataBrandBatchFilter.BrandBatchOutcome brandOutcome = brandBatchFilter.filter(filtered.kept());
log.info("[collect-data] 锁外预处理完成 taskId={} rows={} 去重后={} 品牌检测耗时={}ms",
taskId, rows.size(), filtered.kept().size(), System.currentTimeMillis() - prepareStartAt);
try (TaskDistributedLockService.LockHandle ignored = acquireTaskLockOrThrow(taskId)) {
FileTaskEntity task = fileTaskMapper.selectById(taskId);
if (task == null || !MODULE_TYPE.equals(task.getModuleType())) {
@@ -819,25 +852,23 @@ public class CollectDataService {
return buildSubmitVo(task, result, chunkIndex, chunkTotal, request, 0);
}
List<CollectDataResultRowVo> rows = normalizeSubmitRows(request.getItems());
buildParseLimits().validateChunkRowCount(rows.size());
CollectDataStats stats = loadStats(task);
stats.receivedRows += rows.size();
stats.currentChunkRows = rows.size();
// 「结果文件」sheet 需要 Python 回传的全量数据(不经任何后端过滤),
// 因此 chunk payload 写入未筛除空 ASIN 的全量 rows;
// 仅当 ASIN 非空时才进入去重 / 无效品牌 / 品牌检测链路并落 biz_task_result_item。
List<CollectDataResultRowVo> rowsForFiltering = new ArrayList<>(rows.size());
for (CollectDataResultRowVo row : rows) {
if (row.getAsin() != null && !row.getAsin().isBlank()) {
rowsForFiltering.add(row);
}
}
CollectDataBatchQuery.FilterResult filtered = collectDataBatchQuery.filter(rowsForFiltering);
stats.dedupeFilteredCount += filtered.dedupeFilteredCount();
stats.invalidFilteredCount += filtered.invalidFilteredCount();
List<CollectDataResultRowVo> accepted = filterByBrandCheck(filtered.kept(), stats);
stats.brandRejectedCount += brandOutcome.rejected().size();
stats.brandQueryFailedCount += brandOutcome.queryFailed().size();
// 只有被服务端判定为无效品牌(rejected)的行才写入无效品牌表;
// queryFailed 是品牌检测服务端到端失败(如缺 X-Token 422/超时/限流),
// 一并写入会把故障期间被误伤的品牌永久拉黑,后续同品牌商品全部被
// invalidFiltered 过滤(task-27265 实测:通过 Python 过滤的 21 行中
// 8 行查询失败被写表后误杀,最终结果 Excel 0 行)。rejected 为空时
// 不触发任何写入,避免空批次无意义调用。
if (!brandOutcome.rejected().isEmpty()) {
invalidAsinBatchWriter.writeBatch(brandOutcome.rejected());
}
List<CollectDataResultRowVo> accepted = brandOutcome.accepted();
// 结果明细改为 chunk 级存储:整个 chunk 的 accepted 行共享一个
// RustFS 对象(deterministic key,同 chunk 重提覆盖同一对象),
// biz_task_result_item.payload_json 只存 {chunk, offset, payload} 引用。
@@ -872,6 +903,14 @@ public class CollectDataService {
if (request.getError() != null && !request.getError().isBlank()) {
markTaskFailed(task, result, request.getError(), stats);
// 失败但已收到分片:照常组装结果文件,让用户能下载已采集的数据。
// 此前失败分支只标失败不组装,已落库的数据也没有任何结果文件可下载
// (taskId 28599:55 个分片全部收到、187 行明细已落库,用户却拿不到文件)。
if (hasReceivedChunks(taskId)) {
enqueueFinalWorkbook(task, result, stats);
log.warn("[collect-data] 任务失败仍组装部分结果 taskId={} error={} finalRows={}",
taskId, request.getError(), stats.finalRowCount);
}
} else if (Boolean.TRUE.equals(request.getDone())) {
enqueueFinalWorkbook(task, result, stats);
} else {
@@ -933,22 +972,6 @@ public class CollectDataService {
return rows;
}
private List<CollectDataResultRowVo> filterByBrandCheck(List<CollectDataResultRowVo> rows, CollectDataStats stats) {
CollectDataBrandBatchFilter.BrandBatchOutcome outcome = brandBatchFilter.filter(rows);
stats.brandRejectedCount += outcome.rejected().size();
stats.brandQueryFailedCount += outcome.queryFailed().size();
// 只有被服务端判定为无效品牌(rejected)的行才写入无效品牌表;
// queryFailed 是品牌检测服务端到端失败(如缺 X-Token 422/超时/限流),
// 一并写入会把故障期间被误伤的品牌永久拉黑,后续同品牌商品全部被
// invalidFiltered 过滤(task-27265 实测:通过 Python 过滤的 21 行中
// 8 行查询失败被写表后误杀,最终结果 Excel 0 行)。rejected 为空时
// 不触发任何写入,避免空批次无意义调用。
if (!outcome.rejected().isEmpty()) {
invalidAsinBatchWriter.writeBatch(outcome.rejected());
}
return outcome.accepted();
}
private void persistChunk(Long taskId,
String scopeKey,
String scopeHash,
@@ -1011,7 +1034,8 @@ public class CollectDataService {
result.setResultFileSize(0L);
result.setResultContentType(CONTENT_TYPE_XLSX);
result.setRowCount(stats.finalRowCount);
result.setErrorMessage(null);
// 不清 errorMessage:失败任务的部分结果组装也走这里,清掉会让用户看不到真实失败原因
// (成功路径的 errorMessage 本来就为 null,无需清理)。
fileResultMapper.updateById(result);
task.setUpdatedAt(LocalDateTime.now());
fileTaskMapper.updateById(task);
@@ -1060,6 +1084,22 @@ public class CollectDataService {
stats.summaries,
batch -> streamRawRows(task.getId(), batch));
String objectKey = ossStorageService.uploadResultFile(xlsx, MODULE_TYPE);
// 复用同一份 stats 更新 finalRowCount 后再持久化,避免重复 loadStats 丢失 summaries。
stats.finalRowCount = (int) finalRowCount;
persistStats(task, stats);
// 失败原因先留存:下面的乐观写入会清空 result.errorMessage,任务已被判失败时要用它恢复。
String failureReason = result.getErrorMessage();
if (failureReason == null || failureReason.isBlank()) {
failureReason = task.getErrorMessage();
}
if (failureReason == null || failureReason.isBlank()) {
failureReason = "任务失败,结果文件为已采集的部分数据";
}
// 结果行先按成功乐观写入:保持「结果文件先于任务成功落库」的时序,
// 万一进程在这两步之间退出,任务仍是 RUNNING,会被陈旧巡检重新组装(可自愈)。
result.setResultFilename(filename);
result.setResultFileUrl(objectKey);
result.setResultFileSize(xlsx.length());
@@ -1069,10 +1109,7 @@ public class CollectDataService {
result.setErrorMessage(null);
fileResultMapper.updateById(result);
// 复用同一份 stats 更新 finalRowCount 后再持久化,避免重复 loadStats 丢失 summaries。
stats.finalRowCount = (int) finalRowCount;
persistStats(task, stats);
// 条件更新:任务可能已被 /fail 标为 FAILED(客户端报错与结果文件组装并发)——
// 条件更新:任务可能已被判失败(客户端上报失败 / 陈旧判死与结果文件组装并发)——
// 无条件 updateById 会把 FAILED 覆盖成 SUCCESS(错误信息被清、用户看到「假成功」)。
// 结果文件已生成,故失败态下仍保留文件,只是不覆盖状态。
int updated = fileTaskMapper.update(null, new LambdaUpdateWrapper<FileTaskEntity>()
@@ -1085,7 +1122,13 @@ public class CollectDataService {
.set(FileTaskEntity::getUpdatedAt, LocalDateTime.now())
.set(FileTaskEntity::getFinishedAt, LocalDateTime.now()));
if (updated == 0) {
log.warn("[collect-data] 结果文件已生成但任务已是 FAILED,保留失败态不覆盖 taskId={}", task.getId());
// 任务已是 FAILED:结果记录改回失败语义并保留真实原因,但文件 URL 照常保留,
// 用户看到「失败 + 原因」的同时仍能下载已采集的部分结果。
result.setSuccess(0);
result.setErrorMessage(failureReason);
fileResultMapper.updateById(result);
log.warn("[collect-data] 结果文件已生成但任务已是 FAILED,保留失败态与原因 taskId={} rows={} reason={}",
task.getId(), finalRowCount, failureReason);
}
} finally {
FileUtil.del(xlsx);
@@ -27,6 +27,7 @@ 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.TaskHeartbeatPositionService;
import com.nanri.aiimage.modules.task.service.TaskResumeService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
@@ -92,6 +93,8 @@ public class DeleteBrandStaleTaskService {
private final ShopDataCrawlTaskService shopDataCrawlTaskService;
private final TaskScopeStateMapper taskScopeStateMapper;
private final TaskHeartbeatPositionService taskHeartbeatPositionService;
/** 客户端中断任务的自动续跑(保留失败记录 + 重排队续跑任务,V129)。 */
private final TaskResumeService taskResumeService;
@Value("${aiimage.temp-dir.retention-hours:24}")
private long tempDirRetentionHours;
@@ -114,13 +117,16 @@ public class DeleteBrandStaleTaskService {
ShopMatchStaleCheckStats queryAsinStats = failStaleQueryAsinTasks();
ShopMatchStaleCheckStats withdrawStats = failStaleWithdrawTasks();
NoResultUploadStaleCheckStats noUploadStats = failNoResultUploadTasks();
// 客户端重启中断的任务:除了标失败(客户端上报,用户能看到原因),还要重新排队
// 一条 PENDING 续跑任务交给客户端兜底拉取执行,否则长任务一遇客户端更新就整个白跑
TaskResumeService.ResumeStats resumeStats = resumeInterruptedSafely();
for (Map.Entry<String, Runnable> delegated : delegatedStaleChecks().entrySet()) {
runModuleStaleCheck(delegated.getKey(), delegated.getValue());
}
// 周期每 2 分钟一轮,各模块 summary 合并为单行,避免定期刷屏
// 注意:每段占位符数量必须与实参一致——此前每段 5 个占位符只传 4 个参数,
// 导致 withdraw 之后的取值整体错位、末尾 elapsedMs/thread 打成字面量
log.info("[stale-check] summary product-risk(s={} f={} x={} p={}) price-track(s={} f={} x={} p={}) shop-match(s={} f={} x={} p={}) patrol-delete(s={} f={} x={} p={}) query-asin(s={} f={} x={} p={}) withdraw(s={} f={} x={} p={}) no-upload(c={} f={} x={}) elapsedMs={} thread={}",
log.info("[stale-check] summary product-risk(s={} f={} x={} p={}) price-track(s={} f={} x={} p={}) shop-match(s={} f={} x={} p={}) patrol-delete(s={} f={} x={} p={}) query-asin(s={} f={} x={} p={}) withdraw(s={} f={} x={} p={}) no-upload(c={} f={} x={}) resume(s={} r={} k={} u={}) elapsedMs={} thread={}",
stats.scannedTaskCount, stats.finalizedTaskCount, stats.failedTaskCount, stats.skippedTaskCount,
priceTrackStats.scannedTaskCount, priceTrackStats.finalizedTaskCount, priceTrackStats.failedTaskCount, priceTrackStats.skippedTaskCount,
shopMatchStats.scannedTaskCount, shopMatchStats.finalizedTaskCount, shopMatchStats.failedTaskCount, shopMatchStats.skippedTaskCount,
@@ -128,11 +134,27 @@ public class DeleteBrandStaleTaskService {
queryAsinStats.scannedTaskCount, queryAsinStats.finalizedTaskCount, queryAsinStats.failedTaskCount, queryAsinStats.skippedTaskCount,
withdrawStats.scannedTaskCount, withdrawStats.finalizedTaskCount, withdrawStats.failedTaskCount, withdrawStats.skippedTaskCount,
noUploadStats.scannedTaskCount, noUploadStats.failedTaskCount, noUploadStats.skippedTaskCount,
resumeStats.scannedTaskCount, resumeStats.resumedTaskCount, resumeStats.skippedTaskCount,
resumeStats.unsupportedTaskCount,
System.currentTimeMillis() - startedAt,
Thread.currentThread().getName());
}
}
/**
* 自动续跑巡检的隔离壳:续跑失败绝不能拖垮判死主流程。
* 判死是任务状态的兜底(不做会留下永远 RUNNING 的孤儿),优先级高于续跑;
* 这里失败只记日志并返回空统计,2 分钟后的下一轮自然重试。
*/
private TaskResumeService.ResumeStats resumeInterruptedSafely() {
try {
return taskResumeService.resumeInterruptedTasks();
} catch (Exception ex) {
log.warn("[task-resume] 自动续跑巡检失败(不影响本轮判死): {}", ex.getMessage(), ex);
return new TaskResumeService.ResumeStats();
}
}
/**
* 委派式陈旧判死:moduleType → 处理动作。
* {@code TaskModuleRegistry} 中 delegatedStaleCheck=true 的模块都必须在这里登记,
@@ -29,6 +29,8 @@ public class PriceTrackLoopRunEntity {
@TableField(value = "active_task_id", updateStrategy = FieldStrategy.ALWAYS)
private Long activeTaskId;
private Boolean stopRequested;
/** 因客户端中断自动重派当前轮的次数:封顶用,避免会话持续不可用时无限重派(V129)。 */
private Integer resumeAttempt;
private String errorMessage;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
@@ -39,6 +39,14 @@ public class PriceTrackLoopRunService {
private static final String STATUS_STOPPED = "STOPPED";
private static final String EXECUTION_MODE_FINITE = "FINITE";
private static final String EXECUTION_MODE_INFINITE = "INFINITE";
/** 客户端异常中断的任务 errorMessage 前缀(TaskHeartbeatService.markInterrupted 写入)。 */
private static final String CLIENT_INTERRUPT_ERROR_PREFIX = "客户端异常中断";
/**
* 中断后自动重派当前轮的次数上限。
* 会话持续不可用(账号被风控、紫鸟未就绪)时,不封顶会无限重派、无限重开浏览器——
* 2026-09-18 任务 28587 就是这样白烧了 5 小时。
*/
private static final int MAX_AUTO_RESUME_ATTEMPT = 3;
private final PriceTrackLoopRunMapper loopRunMapper;
private final FileTaskMapper fileTaskMapper;
@@ -259,6 +267,33 @@ public class PriceTrackLoopRunService {
entity.setActiveTaskId(null);
entity.setUpdatedAt(LocalDateTime.now());
if (STATUS_FAILED.equals(task.getStatus())) {
// 用户已请求停止时绝不续派:停止意图优先于自动恢复(否则点完停止循环还会自己转起来)
if (Boolean.TRUE.equals(entity.getStopRequested())) {
markStopped(entity, null);
return;
}
// 客户端重启中断(markInterrupted 写入的前缀)不终止循环:清空 active_task_id 后保持
// RUNNING,客户端下次 dispatchNext 会拿到**同一店铺、同一轮次**的 childTaskRequest,
// 等于原地续跑——页内已处理的 ASIN 由服务端 skip_asins 去重,不会重复改价。
if (isClientInterrupt(task) && currentResumeAttempt(entity) < MAX_AUTO_RESUME_ATTEMPT) {
int attempt = currentResumeAttempt(entity) + 1;
entity.setStatus(STATUS_RUNNING);
entity.setErrorMessage(null);
entity.setFinishedAt(null);
entity.setResumeAttempt(attempt);
loopRunMapper.updateById(entity);
log.warn("[price-track-loop] 子任务因客户端中断失败,自动重派当前轮 loopRunId={} childTaskId={} "
+ "round={} shopIndex={} resumeAttempt={}/{} error={}",
entity.getId(), childTaskId, entity.getCurrentRound(), entity.getCurrentShopIndex(),
attempt, MAX_AUTO_RESUME_ATTEMPT, task.getErrorMessage());
return;
}
if (isClientInterrupt(task)) {
log.warn("[price-track-loop] 客户端中断续跑已达上限 {} 次,终止循环 loopRunId={} childTaskId={} "
+ "round={} shopIndex={}",
MAX_AUTO_RESUME_ATTEMPT, entity.getId(), childTaskId,
entity.getCurrentRound(), entity.getCurrentShopIndex());
}
entity.setStatus(STATUS_FAILED);
entity.setErrorMessage(task.getErrorMessage() == null || task.getErrorMessage().isBlank()
? "子任务执行失败"
@@ -269,6 +304,8 @@ public class PriceTrackLoopRunService {
entity.getId(), childTaskId, entity.getCurrentRound(), entity.getCurrentShopIndex(), entity.getErrorMessage());
return;
}
// 子任务成功 → 中断续跑计数归零(否则历史上的中断会一直占用封顶额度)
entity.setResumeAttempt(0);
List<PriceTrackMatchShopsVo.PriceTrackShopQueueItem> items = parseShops(entity);
if (items.isEmpty()) {
entity.setStatus(STATUS_FAILED);
@@ -300,6 +337,16 @@ public class PriceTrackLoopRunService {
entity.getId(), childTaskId, entity.getStatus(), entity.getCurrentRound(), entity.getCurrentShopIndex(), entity.getActiveTaskId());
}
/** 子任务失败原因是否为「客户端异常中断」(客户端重启上报,可自动重派续跑)。 */
private static boolean isClientInterrupt(FileTaskEntity task) {
String message = task == null ? null : task.getErrorMessage();
return message != null && message.startsWith(CLIENT_INTERRUPT_ERROR_PREFIX);
}
private static int currentResumeAttempt(PriceTrackLoopRunEntity entity) {
return entity.getResumeAttempt() == null ? 0 : entity.getResumeAttempt();
}
private void reconcileWithTerminalChild(PriceTrackLoopRunEntity entity) {
if (entity == null || entity.getActiveTaskId() == null || isTerminal(entity.getStatus())) {
return;
@@ -652,9 +652,8 @@ public class ProductRiskTaskService {
}
matchedShopCount++;
if (payload.getError() != null && !payload.getError().isBlank()) {
markResultFailed(fr, payload.getError());
batchErrors.add(shopKey + ": " + payload.getError());
productRiskTaskCacheService.removeShopMergedPayload(taskId, shopKey);
finalizeFailedShop(fr, shopKey, mergeShopPayload(taskId, shopKey, payload),
payload.getError(), batchErrors);
continue;
}
@@ -759,9 +758,8 @@ public class ProductRiskTaskService {
}
if (cachedPayload.getError() != null && !cachedPayload.getError().isBlank()) {
markResultFailed(fr, cachedPayload.getError());
batchErrors.add(shopKey + ": " + cachedPayload.getError());
productRiskTaskCacheService.removeShopMergedPayload(taskId, shopKey);
// 陈旧收尾同样保留已跑出来的行:失败原因照常回显,文件顺手组装
finalizeFailedShop(fr, shopKey, cachedPayload, cachedPayload.getError(), batchErrors);
changed = true;
continue;
}
@@ -852,6 +850,9 @@ public class ProductRiskTaskService {
String stem = safeFileStem(displayName);
File xlsx = FileUtil.file(workRoot, stem + ".xlsx");
File zip = FileUtil.file(workRoot, stem + ".zip");
// 失败店铺的部分结果(errorMessage 已写明原因):组装完成时保留失败态,只挂文件。
// 否则组装一落地就把行"洗成成功",用户再也看不到「这个店铺其实没跑完」。
boolean partialFailure = fr.getErrorMessage() != null && !fr.getErrorMessage().isBlank();
try {
excelAssemblyService.writeWorkbook(xlsx, displayName, countries);
ZipUtil.zip(zip, false, xlsx);
@@ -861,8 +862,12 @@ public class ProductRiskTaskService {
fr.setResultFileSize(zip.length());
fr.setResultContentType(CONTENT_TYPE_ZIP);
fr.setRowCount(excelAssemblyService.countRows(countries));
fr.setSuccess(1);
fr.setErrorMessage(null);
if (partialFailure) {
fr.setSuccess(0);
} else {
fr.setSuccess(1);
fr.setErrorMessage(null);
}
fileResultMapper.updateById(fr);
} finally {
FileUtil.del(xlsx);
@@ -899,13 +904,56 @@ public class ProductRiskTaskService {
}
private void enqueueResultFileAssembly(FileResultEntity result, String shopKey, ProductRiskShopPayloadDto payload) {
enqueueResultFileAssembly(result, shopKey, payload, false);
}
/**
* @param preserveFailure 失败店铺的部分结果:保留 success=0 + 失败原因,只把文件挂上去,
* 任务状态不变(仍 FAILED),用户仍能下载已跑出来的行
*/
private void enqueueResultFileAssembly(FileResultEntity result, String shopKey,
ProductRiskShopPayloadDto payload, boolean preserveFailure) {
taskResultPayloadService.saveLatest(result.getTaskId(), MODULE_TYPE, shopKey, payload);
taskResultItemService.replaceResultSnapshot(result.getTaskId(), MODULE_TYPE, result.getId(), shopKey, payload);
markResultFilePending(result, shopKey, payload);
markResultFilePending(result, shopKey, payload, preserveFailure);
taskFileJobService.enqueueAssembleResult(result.getTaskId(), MODULE_TYPE, result.getId(), shopKey);
}
private void markResultFilePending(FileResultEntity result, String shopKey, ProductRiskShopPayloadDto payload) {
/**
* 失败店铺的收尾:任务照旧标 FAILED(原因回显给用户),但已经把跑出来的行组装成
* 部分结果文件随任务交付——否则用户只看到「失败」,却拿不到「哪些 ASIN 实际已被处理」
* 的记录(会话掉线这类"跑了几个国家才断"的场景尤其需要)。一行可用数据都没有时才退化成纯失败。
*/
private void finalizeFailedShop(FileResultEntity fr, String shopKey,
ProductRiskShopPayloadDto mergedPayload, String errorMessage,
List<String> batchErrors) {
int rows = mergedPayload == null ? 0 : countPayloadRows(mergedPayload);
String message = errorMessage;
if (rows > 0) {
markResultFailed(fr, errorMessage);
try {
enqueueResultFileAssembly(fr, shopKey, mergedPayload, true);
batchErrors.add(shopKey + ": " + errorMessage);
productRiskTaskCacheService.removeShopMergedPayload(fr.getTaskId(), shopKey);
log.info("[product-risk] 失败店铺仍产出部分结果 taskId={} shop={} rows={} error={}",
fr.getTaskId(), shopKey, rows, errorMessage);
return;
} catch (Exception ex) {
message = errorMessage + "(部分结果组装排队失败:" + (ex.getMessage() == null ? "未知错误" : ex.getMessage()) + ")";
log.warn("[product-risk] 失败店铺部分结果排队失败,仅标记失败 taskId={} shop={} msg={}",
fr.getTaskId(), shopKey, ex.getMessage(), ex);
}
} else {
log.info("[product-risk] 失败店铺无可用行,不产出结果文件 taskId={} shop={} error={}",
fr.getTaskId(), shopKey, errorMessage);
}
markResultFailed(fr, message);
batchErrors.add(shopKey + ": " + message);
productRiskTaskCacheService.removeShopMergedPayload(fr.getTaskId(), shopKey);
}
private void markResultFilePending(FileResultEntity result, String shopKey,
ProductRiskShopPayloadDto payload, boolean preserveFailure) {
Map<String, List<ProductRiskRowDto>> countries = excelAssemblyService.normalizeCountriesMap(payload.getCountries());
String displayName = payload.getShopName() != null && !payload.getShopName().isBlank()
? payload.getShopName().trim()
@@ -916,8 +964,16 @@ public class ProductRiskTaskService {
result.setResultFileSize(0L);
result.setResultContentType(CONTENT_TYPE_ZIP);
result.setRowCount(excelAssemblyService.countRows(countries));
result.setSuccess(1);
result.setErrorMessage(null);
if (preserveFailure) {
// 失败店铺的部分结果:成功态与失败原因都不能动,只标「文件名已定、文件待组装」
result.setSuccess(0);
if (result.getErrorMessage() == null || result.getErrorMessage().isBlank()) {
result.setErrorMessage("店铺未跑完,仅产出部分结果");
}
} else {
result.setSuccess(1);
result.setErrorMessage(null);
}
fileResultMapper.updateById(result);
}
@@ -1,6 +1,7 @@
package com.nanri.aiimage.modules.publish.controller;
import com.nanri.aiimage.common.api.ApiResponse;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.modules.publish.model.dto.PublishParseRequest;
import com.nanri.aiimage.modules.publish.model.dto.PublishSubmitResultRequest;
import com.nanri.aiimage.modules.publish.model.dto.PublishTaskBatchRequest;
@@ -14,6 +15,7 @@ import com.nanri.aiimage.modules.publish.service.PublishTaskService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.DeleteMapping;
@@ -34,6 +36,7 @@ import com.nanri.aiimage.modules.task.model.vo.TaskProgressLightBatchVo;
public class PublishController {
private final PublishTaskService publishTaskService;
private final AdminAuthSupport adminAuthSupport;
@PostMapping("/parse")
@Operation(
@@ -57,15 +60,18 @@ public class PublishController {
@PostMapping("/tasks/{taskId}/files/{fileId}/activate")
@Operation(
summary = "激活任务中的单个文件",
description = "前端派发 Python 队列前调用。taskId 和 fileId 用于定位文件,user_id 可省略;如传入则校验任务归属。同一任务同一时间只允许一个 RUNNING 文件;重复激活当前 RUNNING 文件为幂等操作。")
description = "前端派发 Python 队列前调用。taskId 和 fileId 用于定位文件,user_id 可省略;如传入则校验任务归属。同一任务同一时间只允许一个 RUNNING 文件;重复激活当前 RUNNING 文件为幂等操作。"
+ "店铺互斥按 (发起方设备, 店铺) 判定:同一台机器上同一店铺只允许一个任务在跑(该机器上该店铺只有一个紫鸟浏览器会话,并发会互相切换国家);不同设备各自持有独立会话,允许同一店铺并行跑不同国家。"
+ "设备号取自 JWT 签名的 deviceId claim,缺失时退回按店铺全局互斥。")
public ApiResponse<Void> activateFile(
@Parameter(description = "上架任务 ID", required = true, example = "9001")
@PathVariable Long taskId,
@Parameter(description = "任务内文件 ID", required = true, example = "9101")
@PathVariable Long fileId,
@Parameter(description = "可选的任务所属用户 ID;省略时由 taskId 反查", required = false, example = "1")
@RequestParam(value = "user_id", required = false) Long userId) {
publishTaskService.activateFile(taskId, fileId, userId);
@RequestParam(value = "user_id", required = false) Long userId,
HttpServletRequest request) {
publishTaskService.activateFile(taskId, fileId, userId, adminAuthSupport.currentDeviceId(request));
return ApiResponse.success(null);
}
@@ -20,6 +20,8 @@ public class PublishFileEntity {
private Integer matched;
private String shopId;
private Long matchedUserId;
/** 激活该文件时客户端所在设备(JWT 签名的 deviceId);空表示来源不明,按全局店铺互斥保守处理。 */
private String deviceId;
private String platform;
private String companyName;
private String matchStatus;
@@ -174,7 +174,14 @@ public class PublishTaskService {
}
}
public void activateFile(Long taskId, Long fileId, Long userId) {
/**
* 激活任务中的单个文件。
*
* @param deviceId 发起方设备标识(JWT 签名的 deviceId claim);空串/空白表示来源不明
* (旧客户端 token 无该 claim、内部令牌调用),此时退回全局店铺互斥
*/
public void activateFile(Long taskId, Long fileId, Long userId, String deviceId) {
String device = deviceId == null ? "" : deviceId.trim();
try (TaskDistributedLockService.LockHandle lock =
taskDistributedLockService.acquire(MODULE_TYPE, taskId)) {
if (lock == null) {
@@ -198,23 +205,45 @@ public class PublishTaskService {
if (runningFile != null) {
throw new BusinessException("同一任务已有文件正在执行: " + runningFile.getSourceFilename());
}
// 店铺级互斥:同一店铺同一时刻只允许一个上架任务在跑。
// 2026-09-17 事故(28519/28520/28521 相继提交同一店铺「林洪武」):同一店铺被多个
// 任务并发打开,客户端 startBrowser 全部返回 -10000,三个任务一起失败。激活是任务
// 真正开跑的唯一入口,在这里挡掉并带出占用中的任务号,用户才知道要等谁。
// 店铺级互斥:同一台设备上同一店铺同一时刻只允许一个上架任务在跑。
// 2026-09-17 事故(28519/28520/28521 相继提交同一店铺「林洪武」):同一台机器上同一
// 店铺被多个任务并发打开,客户端 startBrowser 全部返回 -10000,三个任务一起失败。
// 激活是任务真正开跑的唯一入口,在这里挡掉并带出占用中的任务号,用户才知道要等谁。
//
// 互斥键是 (设备, 店铺) 而不是店铺:紫鸟浏览器会话是**每台机器一份**,不同客户端
// 各自持有独立会话,同一家店可以在两台机器上并行跑不同国家(2026-09-18 任务 28624
// 在另一台机器上被 28616 误挡)。真正必须串行的是同一台设备——那里只有一个会话,
// 两个任务会互相切换国家(add_product.py 的 SwitchingCountries 是会话级状态,任务
// 中途断线重连还会再切一次),轻则失败,重则把 A 国家的商品提交进 B 国家的店铺。
// 设备号取自 JWT 签名的 deviceId claim;为空(旧客户端 token 无该 claim / 内部令牌
// 调用)时退回改动前的全局店铺互斥,保守不放宽。
//
// 注意:本校验与随后的状态更新之间仍有极小竞态窗口(两个请求恰好同时通过校验);
// 真正的串行由客户端店铺锁保证,这一层的目的是尽早给出明确提示,避免白传文件与重复执行。
String shopName = file.getShopName();
if (shopName != null && !shopName.isBlank()) {
PublishFileEntity shopRunning = publishFileMapper.selectOne(
new LambdaQueryWrapper<PublishFileEntity>()
.eq(PublishFileEntity::getShopName, shopName)
.eq(PublishFileEntity::getStatus, STATUS_RUNNING)
.ne(PublishFileEntity::getTaskId, taskId)
.orderByAsc(PublishFileEntity::getId)
.last("limit 1"));
LambdaQueryWrapper<PublishFileEntity> shopRunningQuery = new LambdaQueryWrapper<PublishFileEntity>()
.eq(PublishFileEntity::getShopName, shopName)
.eq(PublishFileEntity::getStatus, STATUS_RUNNING)
.ne(PublishFileEntity::getTaskId, taskId)
.orderByAsc(PublishFileEntity::getId)
.last("limit 1");
if (device.isEmpty()) {
log.info("[publish] 激活无设备标识,按全局店铺互斥判定 taskId={} fileId={} shop={}",
taskId, fileId, shopName);
} else {
// 本设备的 RUNNING 行,以及设备未知的存量行(旧客户端/内部调用,NULL 或空串)
// ——后者无法判断落在哪台机器上,一律保守视为可能同机。
shopRunningQuery.and(wrapper -> wrapper
.eq(PublishFileEntity::getDeviceId, device)
.or().isNull(PublishFileEntity::getDeviceId)
.or().eq(PublishFileEntity::getDeviceId, ""));
}
PublishFileEntity shopRunning = publishFileMapper.selectOne(shopRunningQuery);
if (shopRunning != null) {
log.warn("[publish] 店铺互斥拦截 taskId={} fileId={} shop={} device={} 占用任务={} 占用设备={}",
taskId, fileId, shopName, device,
shopRunning.getTaskId(), shopRunning.getDeviceId());
throw new BusinessException("店铺「" + shopName + "」已有上架任务正在执行(任务 "
+ shopRunning.getTaskId() + "),请等它完成后再提交");
}
@@ -224,11 +253,13 @@ public class PublishTaskService {
.eq(PublishFileEntity::getTaskId, taskId)
.eq(PublishFileEntity::getStatus, STATUS_PENDING)
.set(PublishFileEntity::getStatus, STATUS_RUNNING)
.set(PublishFileEntity::getDeviceId, device.isEmpty() ? null : device)
.set(PublishFileEntity::getUpdatedAt, LocalDateTime.now())
.set(PublishFileEntity::getErrorMessage, null));
if (updated <= 0) {
throw new BusinessException("文件激活失败,请刷新后重试");
}
log.info("[publish] 文件激活成功 taskId={} fileId={} shop={} device={}", taskId, fileId, shopName, device);
if (STATUS_PENDING.equals(task.getStatus())) {
fileTaskMapper.update(null, new LambdaUpdateWrapper<FileTaskEntity>()
.eq(FileTaskEntity::getId, taskId)
@@ -676,8 +676,7 @@ public class ShopMatchTaskService {
changed = true;
ShopMatchShopPayloadDto merged = mergeShopPayload(taskId, shopKey, incoming);
if (incoming.getError() != null && !incoming.getError().isBlank()) {
markResultFailed(result, incoming.getError().trim());
shopMatchTaskCacheService.removeShopMergedPayload(taskId, shopKey);
finalizeFailedShop(result, shopKey, merged, incoming.getError().trim());
continue;
}
if (!isShopPayloadCompleted(merged)) {
@@ -756,9 +755,8 @@ public class ShopMatchTaskService {
}
if (cachedPayload.getError() != null && !cachedPayload.getError().isBlank()) {
markResultFailed(result, cachedPayload.getError());
batchErrors.add(shopKey + ": " + cachedPayload.getError());
shopMatchTaskCacheService.removeShopMergedPayload(taskId, shopKey);
// 陈旧收尾同样保留已跑出来的行:失败原因照常回显,文件顺手组装
batchErrors.add(shopKey + ": " + finalizeFailedShop(result, shopKey, cachedPayload, cachedPayload.getError()));
changed = true;
continue;
}
@@ -819,6 +817,9 @@ public class ShopMatchTaskService {
String displayName = payload.getShopName() != null && !payload.getShopName().isBlank() ? payload.getShopName().trim() : shopKey;
String stem = safeFileStem(displayName);
File xlsx = FileUtil.file(workRoot, stem + ".xlsx");
// 失败店铺的部分结果(errorMessage 已写明原因):组装完成时保留失败态,只挂文件。
// 否则组装一落地就把行"洗成成功",用户再也看不到「这个店铺其实没跑完」。
boolean partialFailure = result.getErrorMessage() != null && !result.getErrorMessage().isBlank();
try {
excelAssemblyService.writeWorkbook(xlsx, countries);
String objectKey = ossStorageService.uploadResultFile(xlsx, MODULE_TYPE);
@@ -827,8 +828,12 @@ public class ShopMatchTaskService {
result.setResultFileSize(xlsx.length());
result.setResultContentType(CONTENT_TYPE_XLSX);
result.setRowCount(excelAssemblyService.countRows(countries));
result.setSuccess(1);
result.setErrorMessage(null);
if (partialFailure) {
result.setSuccess(0);
} else {
result.setSuccess(1);
result.setErrorMessage(null);
}
fileResultMapper.updateById(result);
} finally {
FileUtil.del(xlsx);
@@ -861,12 +866,55 @@ public class ShopMatchTaskService {
}
private void enqueueResultFileAssembly(FileResultEntity result, String shopKey, ShopMatchShopPayloadDto payload) {
enqueueResultFileAssembly(result, shopKey, payload, false);
}
/**
* @param preserveFailure 失败店铺的部分结果:保留 success=0 + 失败原因,只把文件挂上去,
* 任务状态不变(仍 FAILED),用户仍能下载已跑出来的行
*/
private void enqueueResultFileAssembly(FileResultEntity result, String shopKey,
ShopMatchShopPayloadDto payload, boolean preserveFailure) {
taskResultPayloadService.saveLatest(result.getTaskId(), MODULE_TYPE, shopKey, payload);
markResultFilePending(result, shopKey, payload);
markResultFilePending(result, shopKey, payload, preserveFailure);
taskFileJobService.enqueueAssembleResult(result.getTaskId(), MODULE_TYPE, result.getId(), shopKey);
}
private void markResultFilePending(FileResultEntity result, String shopKey, ShopMatchShopPayloadDto payload) {
/**
* 失败店铺的收尾:任务照旧标 FAILED(原因回显给用户),但已经把跑出来的行组装成
* 部分结果文件随任务交付——否则用户只看到「失败」,却拿不到「哪些 ASIN 实际已被匹配」
* 的记录(会话掉线这类"跑了几个国家才断"的场景尤其需要)。一行可用数据都没有时才退化成纯失败。
*
* @return 最终写入结果记录的失败原因(组装排队失败时会附上原因)
*/
private String finalizeFailedShop(FileResultEntity result, String shopKey,
ShopMatchShopPayloadDto mergedPayload, String errorMessage) {
int rows = mergedPayload == null ? 0 : countPayloadRows(mergedPayload);
String message = errorMessage;
if (rows > 0) {
markResultFailed(result, errorMessage);
try {
enqueueResultFileAssembly(result, shopKey, mergedPayload, true);
shopMatchTaskCacheService.removeShopMergedPayload(result.getTaskId(), shopKey);
log.info("[shop-match] 失败店铺仍产出部分结果 taskId={} shop={} rows={} error={}",
result.getTaskId(), shopKey, rows, errorMessage);
return errorMessage;
} catch (Exception ex) {
message = errorMessage + "(部分结果组装排队失败:" + (ex.getMessage() == null ? "未知错误" : ex.getMessage()) + ")";
log.warn("[shop-match] 失败店铺部分结果排队失败,仅标记失败 taskId={} shop={} msg={}",
result.getTaskId(), shopKey, ex.getMessage(), ex);
}
} else {
log.info("[shop-match] 失败店铺无可用行,不产出结果文件 taskId={} shop={} error={}",
result.getTaskId(), shopKey, errorMessage);
}
markResultFailed(result, message);
shopMatchTaskCacheService.removeShopMergedPayload(result.getTaskId(), shopKey);
return message;
}
private void markResultFilePending(FileResultEntity result, String shopKey,
ShopMatchShopPayloadDto payload, boolean preserveFailure) {
Map<String, List<ShopMatchRowDto>> countries = excelAssemblyService.normalizeCountriesMap(payload.getCountries());
String displayName = payload.getShopName() != null && !payload.getShopName().isBlank() ? payload.getShopName().trim() : shopKey;
String stem = safeFileStem(displayName);
@@ -875,8 +923,16 @@ public class ShopMatchTaskService {
result.setResultFileSize(0L);
result.setResultContentType(CONTENT_TYPE_XLSX);
result.setRowCount(excelAssemblyService.countRows(countries));
result.setSuccess(1);
result.setErrorMessage(null);
if (preserveFailure) {
// 失败店铺的部分结果:成功态与失败原因都不能动,只标「文件名已定、文件待组装」
result.setSuccess(0);
if (result.getErrorMessage() == null || result.getErrorMessage().isBlank()) {
result.setErrorMessage("店铺未跑完,仅产出部分结果");
}
} else {
result.setSuccess(1);
result.setErrorMessage(null);
}
fileResultMapper.updateById(result);
}
@@ -26,6 +26,10 @@ public class FileTaskEntity {
private String createdBy;
private Long userId;
private String ownerInstanceId;
/** 续跑来源任务 ID:本行是客户端中断后由服务端自动重排队的续跑任务时非空(V129)。 */
private Long resumeOfTaskId;
/** 续跑代数:0=原始任务,N=第 N 次自动续跑(封顶用,V129)。 */
private Integer resumeAttempt;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
private LocalDateTime finishedAt;
@@ -0,0 +1,190 @@
package com.nanri.aiimage.modules.task.service;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import com.nanri.aiimage.modules.task.spi.ClientTaskPullSpi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* 客户端中断任务的自动续跑:**保留失败记录 + 重新排队一条 PENDING 续跑任务**。
*
* <p>场景:客户端被更新脚本/任务管理器杀掉时,{@code TaskHeartbeatService.markInterrupted} 会把在跑的任务
* 标 FAILED(原因「客户端异常中断: …」),用户能看到发生过什么;但长任务(采集/相似ASIN/外观专利/单次跟价)
* 一遇客户端重启就整个白跑,需要有人把它重新放回队列。本服务负责这件事。
*
* <p>续跑方式刻意复用已有链路:新建的任务落 PENDING,由 {@link TaskClientPullService} 的兜底拉取
* (客户端每分钟 {@code GET /api/tasks/pull-pending})领走执行——不再新造第二套派发机制。
* 只有注册了 {@link ClientTaskPullSpi} 的模块才会被续跑(这些模块的载荷能由服务端自行组装);
* 上架/改价等写操作模块不在其中,避免盲目重跑。
*
* <p>封顶 {@code max-attempt}:会话持续不可用(账号被风控、紫鸟未就绪)时,不封顶会无限重排队。
* 计数写在 {@code biz_file_task.resume_attempt}(V129),随续跑任务代代递增。
*
* <p>幂等:同一原任务已存在续跑任务({@code resume_of_task_id} 反查)则跳过,重复扫描安全。
*/
@Slf4j
@Service
public class TaskResumeService {
private static final String STATUS_FAILED = "FAILED";
private static final String STATUS_PENDING = "PENDING";
/** 客户端重启中断的失败原因前缀,由 TaskHeartbeatService.markInterrupted 写入。 */
private static final String CLIENT_INTERRUPT_PREFIX = "客户端异常中断";
private final FileTaskMapper fileTaskMapper;
/** moduleType → 模块兜底载荷实现;只有注册了 SPI 的模块才能被自动续跑。 */
private final Map<String, ClientTaskPullSpi> resumeHandlers;
@Value("${aiimage.task-resume.enabled:true}")
private boolean enabled;
/** 续跑代数上限:达到后不再重排队,任务保持 FAILED 等人工介入。 */
@Value("${aiimage.task-resume.max-attempt:3}")
private int maxAttempt;
/** 只处理最近这段时间内中断的任务,避免开机扫描历史积压。 */
@Value("${aiimage.task-resume.window-minutes:30}")
private long windowMinutes;
@Value("${aiimage.task-resume.limit:20}")
private int limit;
public TaskResumeService(FileTaskMapper fileTaskMapper, List<ClientTaskPullSpi> pullSpiHandlers) {
this.fileTaskMapper = fileTaskMapper;
Map<String, ClientTaskPullSpi> index = new LinkedHashMap<>();
if (pullSpiHandlers != null) {
for (ClientTaskPullSpi handler : pullSpiHandlers) {
String moduleType = handler.moduleType();
if (moduleType == null || moduleType.isBlank()) {
continue;
}
index.put(moduleType.trim().toUpperCase(Locale.ROOT), handler);
}
}
this.resumeHandlers = Map.copyOf(index);
log.info("[task-resume] 可自动续跑模块注册完成 count={} modules={}", index.size(), index.keySet());
}
/** 扫描一轮:把最近因客户端中断而失败、且未续跑过的任务重新排队。 */
public ResumeStats resumeInterruptedTasks() {
ResumeStats stats = new ResumeStats();
if (!enabled) {
return stats;
}
if (resumeHandlers.isEmpty()) {
log.warn("[task-resume] 没有注册任何 ClientTaskPullSpi,跳过本轮续跑");
return stats;
}
LocalDateTime cutoff = LocalDateTime.now().minusMinutes(Math.max(1L, windowMinutes));
int safeLimit = Math.max(1, limit);
List<FileTaskEntity> candidates = fileTaskMapper.selectList(new LambdaQueryWrapper<FileTaskEntity>()
.eq(FileTaskEntity::getStatus, STATUS_FAILED)
.likeRight(FileTaskEntity::getErrorMessage, CLIENT_INTERRUPT_PREFIX)
.in(FileTaskEntity::getModuleType, resumeHandlers.keySet())
.lt(FileTaskEntity::getResumeAttempt, maxAttempt)
.ge(FileTaskEntity::getFinishedAt, cutoff)
.orderByAsc(FileTaskEntity::getId)
.last("limit " + safeLimit));
if (candidates.isEmpty()) {
stats.unsupportedTaskCount = countUnsupportedInterrupts(cutoff);
return stats;
}
stats.unsupportedTaskCount = countUnsupportedInterrupts(cutoff);
stats.scannedTaskCount = candidates.size();
for (FileTaskEntity original : candidates) {
if (original.getUserId() == null || original.getUserId() <= 0) {
log.warn("[task-resume] 原任务没有归属用户,跳过 taskId={}", original.getId());
stats.skippedTaskCount++;
continue;
}
// 幂等:同一原任务已经排过一次续跑就跳过(重复扫描 / 双实例竞态下不会重复建单)
if (hasResumeChild(original.getId())) {
stats.skippedTaskCount++;
continue;
}
FileTaskEntity resume = buildResumeTask(original);
try {
fileTaskMapper.insert(resume);
stats.resumedTaskCount++;
log.warn("[task-resume] 已自动重新排队 taskId={} moduleType={} userId={} 续跑任务={} 代数={}/{} 中断原因={}",
original.getId(), original.getModuleType(), original.getUserId(),
resume.getId(), resume.getResumeAttempt(), maxAttempt, original.getErrorMessage());
} catch (Exception ex) {
stats.skippedTaskCount++;
log.error("[task-resume] 重新排队失败 taskId={} moduleType={} err={}",
original.getId(), original.getModuleType(), ex.getMessage(), ex);
}
}
return stats;
}
/**
* 统计「因客户端中断而失败、但模块不支持自动续跑」的任务数。
*
* <p>这些模块(上架/改价/审批/商品管理采集/跟价的非循环任务等)的续跑载荷需要**用户在页面上选的
* 执行参数**(如 ziniao_version),而这份选择只存在于派发那一刻的浏览器里、没落到服务端
* request_json —— 自动重排队会用错参数。因此它们只做**可见**:数量进巡检 summary,
* 运维据此人工重跑;将来把这类参数回写落库后即可纳入续跑白名单。
*/
private int countUnsupportedInterrupts(LocalDateTime cutoff) {
try {
Long count = fileTaskMapper.selectCount(new LambdaQueryWrapper<FileTaskEntity>()
.eq(FileTaskEntity::getStatus, STATUS_FAILED)
.likeRight(FileTaskEntity::getErrorMessage, CLIENT_INTERRUPT_PREFIX)
.notIn(FileTaskEntity::getModuleType, resumeHandlers.keySet())
.ge(FileTaskEntity::getFinishedAt, cutoff));
return count == null ? 0 : count.intValue();
} catch (Exception ex) {
log.warn("[task-resume] 统计不支持续跑的中断任务失败(忽略): {}", ex.getMessage());
return 0;
}
}
/** 该原任务是否已经有续跑任务(反查 resume_of_task_id)。 */
private boolean hasResumeChild(Long originalTaskId) {
Long count = fileTaskMapper.selectCount(new LambdaQueryWrapper<FileTaskEntity>()
.eq(FileTaskEntity::getResumeOfTaskId, originalTaskId));
return count != null && count > 0;
}
private FileTaskEntity buildResumeTask(FileTaskEntity original) {
LocalDateTime now = LocalDateTime.now();
FileTaskEntity resume = new FileTaskEntity();
resume.setTaskNo(original.getModuleType() + "-" + IdUtil.getSnowflakeNextIdStr());
resume.setModuleType(original.getModuleType());
resume.setTaskMode(original.getTaskMode());
resume.setStatus(STATUS_PENDING);
resume.setSourceFileCount(original.getSourceFileCount());
resume.setSuccessFileCount(0);
resume.setFailedFileCount(0);
// 原任务的请求参数整体带走:各模块的 ClientTaskPullSpi 从 request_json / 关联表还原执行参数
resume.setRequestJson(original.getRequestJson());
resume.setCreatedBy(original.getCreatedBy());
resume.setUserId(original.getUserId());
resume.setResumeOfTaskId(original.getId());
int attempt = original.getResumeAttempt() == null ? 0 : original.getResumeAttempt();
resume.setResumeAttempt(attempt + 1);
resume.setCreatedAt(now);
resume.setUpdatedAt(now);
return resume;
}
/** 单轮统计(合并进 stale-check 的 summary 日志,避免定期刷屏)。 */
public static final class ResumeStats {
public int scannedTaskCount;
public int resumedTaskCount;
public int skippedTaskCount;
/** 模块不支持自动续跑的中断任务数(仅计数,供运维人工重跑)。 */
public int unsupportedTaskCount;
}
}
@@ -279,6 +279,17 @@ aiimage:
module-types: ${AIIMAGE_CLIENT_TASK_PULL_MODULE_TYPES:SIMILAR_ASIN,COLLECT_DATA,APPEARANCE_PATENT}
min-pending-minutes: ${AIIMAGE_CLIENT_TASK_PULL_MIN_PENDING_MINUTES:5}
limit: ${AIIMAGE_CLIENT_TASK_PULL_LIMIT:5}
# 客户端中断任务的自动续跑(V129):客户端被更新脚本/任务管理器杀掉时,在跑的任务会被
# 客户端启动时上报中断并标 FAILED(用户能看到真实原因),这里把这些任务重新排队成 PENDING,
# 由上面的兜底拉取通道交给在线客户端继续跑——长任务不再因为一次客户端更新就整个白跑。
# 只有注册了 ClientTaskPullSpi 的模块会被续跑(相似ASIN/采集/外观专利),
# 上架/改价等写操作模块刻意不在内,避免盲目重跑。
# enabled 默认跟随兜底拉取开关:拉了没人领的话,续跑任务只会积压并被 stale 判死。
task-resume:
enabled: ${AIIMAGE_TASK_RESUME_ENABLED:${AIIMAGE_CLIENT_TASK_PULL_ENABLED:false}}
max-attempt: ${AIIMAGE_TASK_RESUME_MAX_ATTEMPT:3}
window-minutes: ${AIIMAGE_TASK_RESUME_WINDOW_MINUTES:30}
limit: ${AIIMAGE_TASK_RESUME_LIMIT:20}
coze-task:
max-concurrent: ${AIIMAGE_COZE_TASK_MAX_CONCURRENT:12}
brand-check:
@@ -289,6 +300,7 @@ aiimage:
retry-times: ${AIIMAGE_BRAND_CHECK_RETRY_TIMES:10}
retry-interval-millis: ${AIIMAGE_BRAND_CHECK_RETRY_INTERVAL_MILLIS:1000}
retry-max-interval-millis: ${AIIMAGE_BRAND_CHECK_RETRY_MAX_INTERVAL_MILLIS:10000}
total-timeout-millis: ${AIIMAGE_BRAND_CHECK_TOTAL_TIMEOUT_MILLIS:90000}
connect-timeout-millis: ${AIIMAGE_BRAND_CHECK_CONNECT_TIMEOUT_MILLIS:10000}
read-timeout-millis: ${AIIMAGE_BRAND_CHECK_READ_TIMEOUT_MILLIS:60000}
appearance-patent:
@@ -0,0 +1,55 @@
-- V129: 客户端中断后的自动续跑(保留失败记录 + 服务端重新排队)
--
-- 背景:2026-09-18 任务 28587(跟价,uid 977 店铺「张美莺」)在客户端 09:51/09:57 被重启后中断,
-- 旧行为是任务一直挂 RUNNING 到 stale 兜底判死(最长 2 小时),长任务一旦撞上客户端更新就白跑。
-- 新契约:中断任务**保留失败记录**(用户能看到「因客户端重启中断」),同时由服务端自动重新排队续跑。
--
-- 两条续跑路径各需要一个计数:
-- 1) biz_file_task.resume_of_task_id + resume_attempt —— 通用模块(相似ASIN/采集/外观专利/跟价单次任务)
-- 由 TaskResumeService 复制出一条 PENDING 续跑任务,交给客户端兜底拉取;代数用于封顶。
-- 2) biz_price_track_loop_run.resume_attempt —— 跟价循环由 loop_run 驱动,中断时不让循环终止,
-- 而是清掉 active_task_id 重新派发当前轮(客户端下次 dispatch 即拿到同一店铺/轮次),同样封顶。
--
-- 封顶的意义:会话持续不可用(如账号被风控)时,不封顶会无限重排队、无限重开浏览器。
--
-- 风险:ADD COLUMN 走 INSTANT,两张表均为小表,秒级完成;建议低峰执行。
-- 回滚:ALTER TABLE biz_file_task DROP COLUMN resume_of_task_id, DROP COLUMN resume_attempt;
-- ALTER TABLE biz_price_track_loop_run DROP COLUMN resume_attempt;
SET @db_name = DATABASE();
SET @col_exists := (
SELECT COUNT(*) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'biz_file_task' AND COLUMN_NAME = 'resume_of_task_id'
);
SET @sql := IF(@col_exists = 0,
'ALTER TABLE biz_file_task ADD COLUMN resume_of_task_id BIGINT NULL COMMENT ''续跑来源任务ID(客户端中断后自动重排队)'' AFTER owner_instance_id',
'SELECT 1'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @col_exists := (
SELECT COUNT(*) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'biz_file_task' AND COLUMN_NAME = 'resume_attempt'
);
SET @sql := IF(@col_exists = 0,
'ALTER TABLE biz_file_task ADD COLUMN resume_attempt INT NOT NULL DEFAULT 0 COMMENT ''续跑代数:0=原始任务,N=第N次自动续跑'' AFTER resume_of_task_id',
'SELECT 1'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @col_exists := (
SELECT COUNT(*) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'biz_price_track_loop_run' AND COLUMN_NAME = 'resume_attempt'
);
SET @sql := IF(@col_exists = 0,
'ALTER TABLE biz_price_track_loop_run ADD COLUMN resume_attempt INT NOT NULL DEFAULT 0 COMMENT ''中断后自动重派当前轮的次数(用于封顶)'' AFTER stop_requested',
'SELECT 1'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
@@ -0,0 +1,33 @@
-- V130: biz_publish_file 增加 device_id 列(激活该文件时客户端所在设备)
--
-- 背景:同店铺互斥原本只按 shop_name 全局判定(PublishTaskService.activateFile)。
-- 但紫鸟浏览器会话是**每台机器一份**:不同客户端各自持有独立的店铺会话,同一家店
-- 完全可以在两台机器上并行跑不同国家。原来的全局判定把这种合法的跨机器并行也挡了
-- (2026-09-18 任务 28624 被 28616 误挡:两条在不同机器上)。
-- 真正必须串行的是「同一台机器上的同一家店」——那里只有一个浏览器会话,两个任务会
-- 互相切换国家(add_product.py 的 SwitchingCountries 是会话级状态,任务中途断线重连
-- 还会再切一次),轻则失败,重则把 A 国家的商品提交进 B 国家的店铺。
--
-- 因此互斥键由 shop_name 改为 (device_id, shop_name)。device 取自 JWT 里**签名的**
-- deviceId claim(绝不使用客户端可控的 X-Device-Id 请求头,见 DeviceSessionPolicy 注释)。
--
-- 空值语义:NULL/空串表示"来源不明"——旧客户端(未升级、token 无 claim)或内部令牌调用。
-- 该情形退回改动前的全局店铺互斥,保持保守,不因迁移把风险放开。存量 RUNNING 行均为 NULL,
-- 因此会继续全挡直到跑完,随后新激活的行都带设备号,跨机器并行自然生效。
--
-- 风险:ADD COLUMN 走 INSTANT/INPLACE,生产该表仅数百行,秒级完成;建议低峰执行。
-- 回滚:ALTER TABLE biz_publish_file DROP COLUMN device_id;
SET @db_name = DATABASE();
SET @col_exists := (
SELECT COUNT(*) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'biz_publish_file' AND COLUMN_NAME = 'device_id'
);
SET @sql := IF(@col_exists = 0,
'ALTER TABLE biz_publish_file ADD COLUMN device_id VARCHAR(128) NULL COMMENT ''device that activated this file, from signed JWT deviceId claim'' AFTER matched_user_id',
'SELECT 1'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
@@ -264,6 +264,30 @@ class CollectDataServiceTxBoundaryTest {
verify(transactionTemplate, never()).execute(any());
}
/** taskId 28599:失败时已收到的分片仍要组装成结果文件,让用户能下载已采集的数据。 */
@Test
void failedSubmitWithReceivedChunksEnqueuesPartialWorkbook() {
when(taskChunkMapper.selectCount(any())).thenReturn(170L);
CollectDataSubmitResultRequest request = submitRequest();
request.setError("中间分批回传失败,终止本次采集以避免服务端数据残缺");
service.submitResult(TASK_ID, request);
verify(taskFileJobService).enqueueAssembleResult(
eq(TASK_ID), eq("COLLECT_DATA"), eq(5001L), anyString());
}
@Test
void failedSubmitWithoutReceivedChunksEnqueuesNothing() {
CollectDataSubmitResultRequest request = submitRequest();
request.setError("采集端启动失败");
service.submitResult(TASK_ID, request);
verify(taskFileJobService, never())
.enqueueAssembleResult(anyLong(), anyString(), anyLong(), anyString());
}
private CollectDataSubmitResultRequest submitRequest() {
CollectDataSubmitRowDto row = new CollectDataSubmitRowDto();
row.setAsin("B0COLLECT1");
@@ -14,6 +14,7 @@ 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.TaskHeartbeatPositionService;
import com.nanri.aiimage.modules.task.service.TaskResumeService;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
@@ -59,6 +60,7 @@ class DeleteBrandStaleTaskServiceTest {
@Mock private ProductRiskTaskService productRiskTaskService;
@Mock private ProductRiskTaskCacheService productRiskTaskCacheService;
@Mock private TaskHeartbeatPositionService taskHeartbeatPositionService;
@Mock private TaskResumeService taskResumeService;
@BeforeAll
static void initializeTableInfo() {
@@ -374,6 +376,9 @@ class DeleteBrandStaleTaskServiceTest {
private void noUploadEnabled() {
when(deleteBrandProgressProperties.isNoResultUploadCheckEnabled()).thenReturn(true);
when(deleteBrandProgressProperties.getNoResultUploadTimeoutMinutes()).thenReturn(180L);
// 续跑巡检在判死主流程里被调用:默认返回空统计(无中断任务可续跑);
// 只有跑到 failStaleRunningTasks 的用例会用到,故 lenient
lenient().when(taskResumeService.resumeInterruptedTasks()).thenReturn(new TaskResumeService.ResumeStats());
}
private void noUploadTaskLockAvailable() {
@@ -398,7 +403,7 @@ class DeleteBrandStaleTaskServiceTest {
null, null, null, null, null, null, null, null, null, null,
null, null, null,
deleteBrandProgressProperties, null, taskDistributedLockService, taskFileJobService, null,
taskScopeStateMapper, taskHeartbeatPositionService);
taskScopeStateMapper, taskHeartbeatPositionService, taskResumeService);
}
private void lockAvailable() {
@@ -82,7 +82,7 @@ class TaskModuleCoverageTest {
mock(SimilarAsinTaskService.class),
null, null, null, null,
mock(ShopDataCrawlTaskService.class),
null, null);
null, null, null);
}
@Test
@@ -14,6 +14,7 @@ import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
@@ -120,6 +121,200 @@ class PriceTrackLoopRunServiceTest {
verify(loopRunMapper, never()).updateById(loop);
}
@Test
void 子任务因客户端中断失败时循环保持运行并重派当前轮() throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
PriceTrackLoopRunMapper loopRunMapper = mock(PriceTrackLoopRunMapper.class);
FileTaskMapper fileTaskMapper = mock(FileTaskMapper.class);
PriceTrackLoopRunService service = new PriceTrackLoopRunService(
loopRunMapper, fileTaskMapper, objectMapper, mock(ZiniaoShopSwitchService.class));
PriceTrackLoopRunEntity loop = new PriceTrackLoopRunEntity();
loop.setId(2699L);
loop.setUserId(977L);
loop.setStatus("RUNNING");
loop.setExecutionMode("INFINITE");
loop.setCurrentRound(1);
loop.setCurrentShopIndex(0);
loop.setActiveTaskId(28587L);
loop.setResumeAttempt(0);
loop.setStopRequested(false);
loop.setShopsJson(objectMapper.writeValueAsString(List.of(shop("张美莺"))));
FileTaskEntity task = new FileTaskEntity();
task.setId(28587L);
task.setUserId(977L);
task.setModuleType("PRICE_TRACK");
task.setStatus("FAILED");
task.setErrorMessage("客户端异常中断: 客户端重启恢复上报(上次任务类型: price-track-run)");
task.setRequestJson(objectMapper.writeValueAsString(Map.of(
"loopRunId", 2699, "roundIndex", 1, "shopIndex", 0)));
when(loopRunMapper.selectList(any())).thenReturn(List.of(loop));
when(fileTaskMapper.selectById(28587L)).thenReturn(task);
service.syncLoopRunAfterChildTerminal(28587L);
assertEquals("RUNNING", loop.getStatus(), "中断不该终止循环");
assertNull(loop.getActiveTaskId(), "必须清空 active_task_id 才能重派当前轮");
assertNull(loop.getFinishedAt());
assertNull(loop.getErrorMessage());
assertEquals(1, loop.getCurrentRound(), "轮次不变:原地续跑");
assertEquals(0, loop.getCurrentShopIndex(), "店铺不变:原地续跑");
assertEquals(1, loop.getResumeAttempt(), "中断计数递增");
}
@Test
void 中断重派达上限后循环判失败() throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
PriceTrackLoopRunMapper loopRunMapper = mock(PriceTrackLoopRunMapper.class);
FileTaskMapper fileTaskMapper = mock(FileTaskMapper.class);
PriceTrackLoopRunService service = new PriceTrackLoopRunService(
loopRunMapper, fileTaskMapper, objectMapper, mock(ZiniaoShopSwitchService.class));
PriceTrackLoopRunEntity loop = new PriceTrackLoopRunEntity();
loop.setId(2699L);
loop.setUserId(977L);
loop.setStatus("RUNNING");
loop.setExecutionMode("INFINITE");
loop.setCurrentRound(1);
loop.setCurrentShopIndex(0);
loop.setActiveTaskId(28587L);
loop.setResumeAttempt(3);
loop.setStopRequested(false);
loop.setShopsJson(objectMapper.writeValueAsString(List.of(shop("张美莺"))));
FileTaskEntity task = new FileTaskEntity();
task.setId(28587L);
task.setUserId(977L);
task.setModuleType("PRICE_TRACK");
task.setStatus("FAILED");
task.setErrorMessage("客户端异常中断: 客户端重启恢复上报");
task.setRequestJson(objectMapper.writeValueAsString(Map.of(
"loopRunId", 2699, "roundIndex", 1, "shopIndex", 0)));
when(loopRunMapper.selectList(any())).thenReturn(List.of(loop));
when(fileTaskMapper.selectById(28587L)).thenReturn(task);
service.syncLoopRunAfterChildTerminal(28587L);
assertEquals("FAILED", loop.getStatus(), "达上限后不再重派,交人工介入");
assertNotNull(loop.getErrorMessage());
}
@Test
void 非中断原因的子任务失败仍终止循环() throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
PriceTrackLoopRunMapper loopRunMapper = mock(PriceTrackLoopRunMapper.class);
FileTaskMapper fileTaskMapper = mock(FileTaskMapper.class);
PriceTrackLoopRunService service = new PriceTrackLoopRunService(
loopRunMapper, fileTaskMapper, objectMapper, mock(ZiniaoShopSwitchService.class));
PriceTrackLoopRunEntity loop = new PriceTrackLoopRunEntity();
loop.setId(2699L);
loop.setUserId(977L);
loop.setStatus("RUNNING");
loop.setExecutionMode("INFINITE");
loop.setCurrentRound(1);
loop.setCurrentShopIndex(0);
loop.setActiveTaskId(28587L);
loop.setResumeAttempt(0);
loop.setStopRequested(false);
loop.setShopsJson(objectMapper.writeValueAsString(List.of(shop("张美莺"))));
FileTaskEntity task = new FileTaskEntity();
task.setId(28587L);
task.setUserId(977L);
task.setModuleType("PRICE_TRACK");
task.setStatus("FAILED");
task.setErrorMessage("张美莺: 国家 德国 未跑完:重试后仍未获取到页码信息");
task.setRequestJson(objectMapper.writeValueAsString(Map.of(
"loopRunId", 2699, "roundIndex", 1, "shopIndex", 0)));
when(loopRunMapper.selectList(any())).thenReturn(List.of(loop));
when(fileTaskMapper.selectById(28587L)).thenReturn(task);
service.syncLoopRunAfterChildTerminal(28587L);
assertEquals("FAILED", loop.getStatus(), "业务失败照旧终止循环,只有中断才续跑");
assertEquals(0, loop.getResumeAttempt());
}
@Test
void 子任务成功后中断计数归零() throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
PriceTrackLoopRunMapper loopRunMapper = mock(PriceTrackLoopRunMapper.class);
FileTaskMapper fileTaskMapper = mock(FileTaskMapper.class);
PriceTrackLoopRunService service = new PriceTrackLoopRunService(
loopRunMapper, fileTaskMapper, objectMapper, mock(ZiniaoShopSwitchService.class));
PriceTrackLoopRunEntity loop = new PriceTrackLoopRunEntity();
loop.setId(2699L);
loop.setUserId(977L);
loop.setStatus("RUNNING");
loop.setExecutionMode("FINITE");
loop.setTargetRounds(1);
loop.setCurrentRound(1);
loop.setCurrentShopIndex(0);
loop.setActiveTaskId(28587L);
loop.setResumeAttempt(2);
loop.setStopRequested(false);
loop.setShopsJson(objectMapper.writeValueAsString(List.of(shop("张美莺"))));
FileTaskEntity task = new FileTaskEntity();
task.setId(28587L);
task.setUserId(977L);
task.setModuleType("PRICE_TRACK");
task.setStatus("SUCCESS");
task.setRequestJson(objectMapper.writeValueAsString(Map.of(
"loopRunId", 2699, "roundIndex", 1, "shopIndex", 0)));
when(loopRunMapper.selectList(any())).thenReturn(List.of(loop));
when(fileTaskMapper.selectById(28587L)).thenReturn(task);
service.syncLoopRunAfterChildTerminal(28587L);
assertEquals(0, loop.getResumeAttempt(), "成功一轮后中断计数归零,避免历史中断占用额度");
}
@Test
void 已请求停止时中断失败不续派而是停止() throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
PriceTrackLoopRunMapper loopRunMapper = mock(PriceTrackLoopRunMapper.class);
FileTaskMapper fileTaskMapper = mock(FileTaskMapper.class);
PriceTrackLoopRunService service = new PriceTrackLoopRunService(
loopRunMapper, fileTaskMapper, objectMapper, mock(ZiniaoShopSwitchService.class));
PriceTrackLoopRunEntity loop = new PriceTrackLoopRunEntity();
loop.setId(2699L);
loop.setUserId(977L);
loop.setStatus("RUNNING");
loop.setExecutionMode("INFINITE");
loop.setCurrentRound(1);
loop.setCurrentShopIndex(0);
loop.setActiveTaskId(28587L);
loop.setResumeAttempt(0);
loop.setStopRequested(true);
loop.setShopsJson(objectMapper.writeValueAsString(List.of(shop("张美莺"))));
FileTaskEntity task = new FileTaskEntity();
task.setId(28587L);
task.setUserId(977L);
task.setModuleType("PRICE_TRACK");
task.setStatus("FAILED");
task.setErrorMessage("客户端异常中断: 客户端重启恢复上报");
task.setRequestJson(objectMapper.writeValueAsString(Map.of(
"loopRunId", 2699, "roundIndex", 1, "shopIndex", 0)));
when(loopRunMapper.selectList(any())).thenReturn(List.of(loop));
when(fileTaskMapper.selectById(28587L)).thenReturn(task);
service.syncLoopRunAfterChildTerminal(28587L);
assertEquals("STOPPED", loop.getStatus(), "停止意图优先于自动续跑");
assertEquals(0, loop.getResumeAttempt());
}
private PriceTrackMatchShopsVo.PriceTrackShopQueueItem shop(String name) {
PriceTrackMatchShopsVo.PriceTrackShopQueueItem item = new PriceTrackMatchShopsVo.PriceTrackShopQueueItem();
item.setShopName(name);
@@ -37,6 +37,7 @@ import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
@@ -109,6 +110,10 @@ class PublishTaskServiceTest {
@InjectMocks private PublishTaskService service;
/** 店铺互斥按 (设备, 店铺) 判定:两台机器各自的设备标识。 */
private static final String DEVICE_A = "device-aaaa";
private static final String DEVICE_B = "device-bbbb";
private final List<TaskChunkEntity> storedChunks = new ArrayList<>();
private final List<TaskScopeStateEntity> storedScopes = new ArrayList<>();
private final Map<String, String> rustfsPayloads = new LinkedHashMap<>();
@@ -744,7 +749,7 @@ class PublishTaskServiceTest {
when(publishFileMapper.selectOne(any())).thenReturn(running);
BusinessException error = assertThrows(BusinessException.class,
() -> service.activateFile(taskId, fileId, 7L));
() -> service.activateFile(taskId, fileId, 7L, DEVICE_A));
assertTrue(error.getMessage().contains("已有文件正在执行"));
verify(publishFileMapper, never()).update(isNull(), any());
@@ -752,25 +757,26 @@ class PublishTaskServiceTest {
}
@Test
void activateFileRejectsShopAlreadyRunningInAnotherTask() {
void activateFileRejectsShopAlreadyRunningOnSameDevice() {
long taskId = 106L;
long fileId = 206L;
FileTaskEntity task = task(taskId, 7L, "RUNNING");
PublishFileEntity target = file(taskId, fileId, "PENDING", "林洪武.xlsx");
target.setShopName("林洪武");
// 另一个任务(28520)正跑同一店铺 —— 2026-09-17 事故形态
// 同一台设备上另一个任务(28520)正跑同一店铺 —— 2026-09-17 事故形态
PublishFileEntity otherTaskRunning = file(105L, 205L, "RUNNING", "林洪武.xlsx");
otherTaskRunning.setShopName("林洪武");
otherTaskRunning.setDeviceId(DEVICE_A);
TaskDistributedLockService.LockHandle lock = mock(TaskDistributedLockService.LockHandle.class);
when(taskDistributedLockService.acquire(PublishTaskService.MODULE_TYPE, taskId)).thenReturn(lock);
when(fileTaskMapper.selectById(taskId)).thenReturn(task);
when(publishFileMapper.selectById(fileId)).thenReturn(target);
// 第一次 selectOne:同任务其它 RUNNING 文件(无);第二次:同店铺跨任务(有)
// 第一次 selectOne:同任务其它 RUNNING 文件(无);第二次:同设备同店铺跨任务(有)
when(publishFileMapper.selectOne(any())).thenReturn(null, otherTaskRunning);
BusinessException error = assertThrows(BusinessException.class,
() -> service.activateFile(taskId, fileId, 7L));
() -> service.activateFile(taskId, fileId, 7L, DEVICE_A));
assertTrue(error.getMessage().contains("林洪武"), "提示要带店铺名: " + error.getMessage());
assertTrue(error.getMessage().contains("105"), "提示要带占用中的任务号: " + error.getMessage());
@@ -778,6 +784,90 @@ class PublishTaskServiceTest {
verify(lock).close();
}
/** 用户需求:同一家店允许在不同客户端(不同机器)上并行跑不同国家。 */
@Test
void activateFileAllowsShopRunningOnAnotherDevice() {
long taskId = 109L;
long fileId = 209L;
FileTaskEntity task = task(taskId, 7L, "RUNNING");
PublishFileEntity target = file(taskId, fileId, "PENDING", "林芳.xlsx");
target.setShopName("林芳");
TaskDistributedLockService.LockHandle lock = mock(TaskDistributedLockService.LockHandle.class);
when(taskDistributedLockService.acquire(PublishTaskService.MODULE_TYPE, taskId)).thenReturn(lock);
when(fileTaskMapper.selectById(taskId)).thenReturn(task);
when(publishFileMapper.selectById(fileId)).thenReturn(target);
// 另一台设备的占用行不会命中本设备的查询,因此这里返回 null
when(publishFileMapper.selectOne(any())).thenReturn(null);
when(publishFileMapper.update(isNull(), any())).thenReturn(1);
service.activateFile(taskId, fileId, 7L, DEVICE_B);
verify(publishFileMapper).update(isNull(), any());
// 店铺互斥查询必须真正带上设备维度,否则跨机器并行会被重新挡住
ArgumentCaptor<LambdaQueryWrapper> captor = ArgumentCaptor.forClass(LambdaQueryWrapper.class);
verify(publishFileMapper, times(2)).selectOne(captor.capture());
String shopSql = captor.getAllValues().get(1).getSqlSegment();
assertTrue(shopSql.contains("device_id"), "店铺互斥查询要带设备维度: " + shopSql);
assertTrue(shopSql.contains("shop_name"), "设备维度不能替代店铺维度: " + shopSql);
}
/** 存量行(改动前激活、device_id 为空)无法判断落在哪台机器上,一律保守视为可能同机。 */
@Test
void activateFileRejectsWhenRunningRowHasUnknownDevice() {
long taskId = 110L;
long fileId = 210L;
FileTaskEntity task = task(taskId, 7L, "RUNNING");
PublishFileEntity target = file(taskId, fileId, "PENDING", "林芳.xlsx");
target.setShopName("林芳");
PublishFileEntity legacyRunning = file(105L, 205L, "RUNNING", "林芳.xlsx");
legacyRunning.setShopName("林芳");
legacyRunning.setDeviceId(null);
TaskDistributedLockService.LockHandle lock = mock(TaskDistributedLockService.LockHandle.class);
when(taskDistributedLockService.acquire(PublishTaskService.MODULE_TYPE, taskId)).thenReturn(lock);
when(fileTaskMapper.selectById(taskId)).thenReturn(task);
when(publishFileMapper.selectById(fileId)).thenReturn(target);
when(publishFileMapper.selectOne(any())).thenReturn(null, legacyRunning);
BusinessException error = assertThrows(BusinessException.class,
() -> service.activateFile(taskId, fileId, 7L, DEVICE_B));
assertTrue(error.getMessage().contains("105"), "存量未知设备行必须继续拦住: " + error.getMessage());
verify(publishFileMapper, never()).update(isNull(), any());
verify(lock).close();
}
/** 无设备标识(旧客户端 token 无 deviceId claim / 内部令牌调用)→ 退回改动前的全局店铺互斥。 */
@Test
void activateFileFallsBackToGlobalShopCheckWhenDeviceMissing() {
long taskId = 111L;
long fileId = 211L;
FileTaskEntity task = task(taskId, 7L, "RUNNING");
PublishFileEntity target = file(taskId, fileId, "PENDING", "林芳.xlsx");
target.setShopName("林芳");
PublishFileEntity otherDeviceRunning = file(105L, 205L, "RUNNING", "林芳.xlsx");
otherDeviceRunning.setShopName("林芳");
otherDeviceRunning.setDeviceId(DEVICE_A);
TaskDistributedLockService.LockHandle lock = mock(TaskDistributedLockService.LockHandle.class);
when(taskDistributedLockService.acquire(PublishTaskService.MODULE_TYPE, taskId)).thenReturn(lock);
when(fileTaskMapper.selectById(taskId)).thenReturn(task);
when(publishFileMapper.selectById(fileId)).thenReturn(target);
when(publishFileMapper.selectOne(any())).thenReturn(null, otherDeviceRunning);
BusinessException error = assertThrows(BusinessException.class,
() -> service.activateFile(taskId, fileId, 7L, ""));
assertTrue(error.getMessage().contains("105"), "来源不明时必须保持全局互斥: " + error.getMessage());
ArgumentCaptor<LambdaQueryWrapper> captor = ArgumentCaptor.forClass(LambdaQueryWrapper.class);
verify(publishFileMapper, times(2)).selectOne(captor.capture());
assertFalse(captor.getAllValues().get(1).getSqlSegment().contains("device_id"),
"来源不明时不应按设备收窄,否则等于放宽互斥");
verify(publishFileMapper, never()).update(isNull(), any());
verify(lock).close();
}
@Test
void activateFileAllowsWhenShopHasNoOtherRunningTask() {
long taskId = 107L;
@@ -793,7 +883,7 @@ class PublishTaskServiceTest {
when(publishFileMapper.selectOne(any())).thenReturn(null);
when(publishFileMapper.update(isNull(), any())).thenReturn(1);
service.activateFile(taskId, fileId, 7L);
service.activateFile(taskId, fileId, 7L, DEVICE_A);
verify(publishFileMapper).update(isNull(), any());
}
@@ -813,7 +903,7 @@ class PublishTaskServiceTest {
when(publishFileMapper.selectOne(any())).thenReturn(null);
when(publishFileMapper.update(isNull(), any())).thenReturn(1);
service.activateFile(taskId, fileId, 7L);
service.activateFile(taskId, fileId, 7L, DEVICE_A);
verify(publishFileMapper, times(1)).selectOne(any());
}
@@ -830,7 +920,7 @@ class PublishTaskServiceTest {
when(fileTaskMapper.selectById(taskId)).thenReturn(task);
when(publishFileMapper.selectById(fileId)).thenReturn(running);
service.activateFile(taskId, fileId, 7L);
service.activateFile(taskId, fileId, 7L, DEVICE_A);
verify(publishFileMapper, never()).selectOne(any());
verify(publishFileMapper, never()).update(isNull(), any());
@@ -107,7 +107,9 @@ class ResultSuccessTimingContractTest {
doAnswer(invocation -> null)
.when(publishTaskService).submitResult(eq(TASK_ID), any(PublishSubmitResultRequest.class));
ApiResponse<Void> response = new PublishController(publishTaskService)
// 第二个构造参数是 AdminAuthSupport(activateFile 取设备号用),本用例只测 submitResult,
// 不经过该依赖,故传 null(同文件其它 controller 用例亦有传 null 的先例)。
ApiResponse<Void> response = new PublishController(publishTaskService, null)
.submitResult(TASK_ID, new PublishSubmitResultRequest());
assertTrue(response.isSuccess(), "success=true");
@@ -107,6 +107,8 @@ class SuccessTimingContractTest {
.thenReturn("oss://shufuai/collect-data/6868.xlsx");
lenient().when(fileResultMapper.updateById(any(FileResultEntity.class))).thenReturn(1);
lenient().when(fileTaskMapper.updateById(any(FileTaskEntity.class))).thenReturn(1);
// 终态条件更新的返回值为「匹配行数」:任务非 FAILED 时匹配 1 行(默认用例都基于 RUNNING 任务)。
lenient().when(fileTaskMapper.update(isNull(), any(LambdaUpdateWrapper.class))).thenReturn(1);
}
private TaskFileJobEntity job() {
@@ -124,6 +126,8 @@ class SuccessTimingContractTest {
void successHappensOnlyAfterFileGeneratedAndUploaded() {
service.processResultFileJob(job());
// 契约核心:结果文件「生成并上传」必须先于任何落库(结果行与任务终态)。
// 保持结果行先写:若进程在这两步之间退出,任务仍是 RUNNING,陈旧巡检可重新组装(自愈)。
var order = inOrder(ossStorageService, fileResultMapper, fileTaskMapper);
order.verify(ossStorageService).uploadResultFile(any(), eq("COLLECT_DATA"));
order.verify(fileResultMapper).updateById(any(FileResultEntity.class));
@@ -220,6 +224,35 @@ class SuccessTimingContractTest {
verify(fileTaskMapper, org.mockito.Mockito.times(1)).update(isNull(), any(LambdaUpdateWrapper.class));
}
/**
* taskId 28599:组装完成时任务已是 FAILED(客户端上报失败或陈旧判死在前)——
* 条件更新不匹配,任务保持失败态与真实原因,但结果文件的 url 照常落库,
* 用户「看到失败」的同时仍能下载已采集的部分结果。
*/
@Test
void failedTaskKeepsFailureButStillCarriesDownloadUrl() {
String reason = "中间分批回传失败,终止本次采集以避免服务端数据残缺";
when(fileTaskMapper.update(isNull(), any(LambdaUpdateWrapper.class))).thenReturn(0);
FileTaskEntity failedTask = runningTask();
failedTask.setStatus("FAILED");
failedTask.setErrorMessage(reason);
when(fileTaskMapper.selectById(TASK_ID)).thenReturn(failedTask);
FileResultEntity failedResult = runningResult();
failedResult.setErrorMessage(reason);
when(fileResultMapper.selectById(RESULT_ID)).thenReturn(failedResult);
service.processResultFileJob(job());
ArgumentCaptor<FileResultEntity> resultCaptor = ArgumentCaptor.forClass(FileResultEntity.class);
// 失败态是补偿写:先乐观写成功,条件更新不匹配后再写回失败语义
verify(fileResultMapper, org.mockito.Mockito.times(2)).updateById(resultCaptor.capture());
FileResultEntity result = resultCaptor.getAllValues().get(1);
assertEquals("oss://shufuai/collect-data/6868.xlsx", result.getResultFileUrl(),
"失败任务也要有可下载的结果文件");
assertEquals(0, result.getSuccess(), "任务失败则结果记录保持失败语义,前端显示「失败」而非「已完成」");
assertEquals(reason, result.getErrorMessage(), "真实失败原因不能被组装流程清掉");
}
private FileTaskEntity runningTask() {
FileTaskEntity task = new FileTaskEntity();
task.setId(TASK_ID);
@@ -0,0 +1,168 @@
package com.nanri.aiimage.modules.task.service;
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import com.nanri.aiimage.modules.task.spi.ClientTaskPullSpi;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.test.util.ReflectionTestUtils;
import java.time.LocalDateTime;
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.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* 客户端中断任务的自动续跑:保留失败记录 + 重新排队 PENDING 续跑任务。
*
* <p>背景:2026-09-18 任务 28587 因客户端被更新脚本重启而中断后一直挂 RUNNING;
* 中断上报把任务标 FAILED 之后,还需要有人把长任务放回队列,否则一遇客户端更新就整个白跑。
*/
class TaskResumeServiceTest {
private static ClientTaskPullSpi spi(String moduleType) {
return new ClientTaskPullSpi() {
@Override
public String moduleType() {
return moduleType;
}
@Override
public Map<String, Object> buildQueuePayload(FileTaskEntity task) {
return Map.of("type", "x-run", "data", Map.of("taskId", task.getId()));
}
};
}
private static TaskResumeService service(FileTaskMapper mapper, List<ClientTaskPullSpi> handlers,
boolean enabled, int maxAttempt) {
TaskResumeService service = new TaskResumeService(mapper, handlers);
ReflectionTestUtils.setField(service, "enabled", enabled);
ReflectionTestUtils.setField(service, "maxAttempt", maxAttempt);
ReflectionTestUtils.setField(service, "windowMinutes", 30L);
ReflectionTestUtils.setField(service, "limit", 20);
return service;
}
private static FileTaskEntity interruptedTask(Long id, String moduleType) {
FileTaskEntity task = new FileTaskEntity();
task.setId(id);
task.setModuleType(moduleType);
task.setUserId(977L);
task.setTaskMode("PYTHON_QUEUE");
task.setStatus("FAILED");
task.setErrorMessage("客户端异常中断: 客户端重启恢复上报(上次任务类型: similar-asin-run)");
task.setRequestJson("{\"items\":[]}");
task.setResumeAttempt(0);
task.setFinishedAt(LocalDateTime.now());
return task;
}
@Test
void 中断任务会被重新排队为待执行的续跑任务() {
FileTaskMapper mapper = mock(FileTaskMapper.class);
when(mapper.selectList(any())).thenReturn(List.of(interruptedTask(28587L, "SIMILAR_ASIN")));
when(mapper.selectCount(any())).thenReturn(0L);
TaskResumeService service = service(mapper, List.of(spi("SIMILAR_ASIN")), true, 3);
TaskResumeService.ResumeStats stats = service.resumeInterruptedTasks();
assertEquals(1, stats.scannedTaskCount);
assertEquals(1, stats.resumedTaskCount);
ArgumentCaptor<FileTaskEntity> captor = ArgumentCaptor.forClass(FileTaskEntity.class);
verify(mapper).insert(captor.capture());
FileTaskEntity resumed = captor.getValue();
assertEquals("PENDING", resumed.getStatus(), "续跑任务必须是待领取状态,交给客户端兜底拉取");
assertEquals(28587L, resumed.getResumeOfTaskId(), "必须回指原任务,用于追溯与幂等");
assertEquals(1, resumed.getResumeAttempt());
assertEquals(977L, resumed.getUserId());
assertEquals("SIMILAR_ASIN", resumed.getModuleType());
assertEquals("{\"items\":[]}", resumed.getRequestJson(), "原任务参数必须整体带走");
assertTrue(resumed.getTaskNo().startsWith("SIMILAR_ASIN-"), "任务号沿用模块前缀");
}
@Test
void 已有续跑任务时跳过避免重复排队() {
FileTaskMapper mapper = mock(FileTaskMapper.class);
when(mapper.selectList(any())).thenReturn(List.of(interruptedTask(28587L, "SIMILAR_ASIN")));
when(mapper.selectCount(any())).thenReturn(1L, 1L);
TaskResumeService service = service(mapper, List.of(spi("SIMILAR_ASIN")), true, 3);
TaskResumeService.ResumeStats stats = service.resumeInterruptedTasks();
assertEquals(1, stats.skippedTaskCount);
assertEquals(0, stats.resumedTaskCount);
verify(mapper, never()).insert(any(FileTaskEntity.class));
}
@Test
void 开关关闭时不扫描() {
FileTaskMapper mapper = mock(FileTaskMapper.class);
TaskResumeService service = service(mapper, List.of(spi("SIMILAR_ASIN")), false, 3);
TaskResumeService.ResumeStats stats = service.resumeInterruptedTasks();
assertEquals(0, stats.scannedTaskCount);
verify(mapper, never()).selectList(any());
}
@Test
void 没有注册模块兜底实现时不扫描() {
FileTaskMapper mapper = mock(FileTaskMapper.class);
TaskResumeService service = service(mapper, List.of(), true, 3);
TaskResumeService.ResumeStats stats = service.resumeInterruptedTasks();
assertEquals(0, stats.scannedTaskCount);
verify(mapper, never()).selectList(any());
}
@Test
void 插入失败只计入跳过不抛出() {
FileTaskMapper mapper = mock(FileTaskMapper.class);
when(mapper.selectList(any())).thenReturn(List.of(interruptedTask(28587L, "SIMILAR_ASIN")));
when(mapper.selectCount(any())).thenReturn(0L);
doThrow(new RuntimeException("库挂了")).when(mapper).insert(any(FileTaskEntity.class));
TaskResumeService service = service(mapper, List.of(spi("SIMILAR_ASIN")), true, 3);
TaskResumeService.ResumeStats stats = service.resumeInterruptedTasks();
assertEquals(1, stats.skippedTaskCount);
assertEquals(0, stats.resumedTaskCount);
}
@Test
void 无候选时统计不支持续跑的中断任务数() {
FileTaskMapper mapper = mock(FileTaskMapper.class);
when(mapper.selectList(any())).thenReturn(List.of());
when(mapper.selectCount(any())).thenReturn(3L);
TaskResumeService service = service(mapper, List.of(spi("SIMILAR_ASIN")), true, 3);
TaskResumeService.ResumeStats stats = service.resumeInterruptedTasks();
assertEquals(0, stats.resumedTaskCount);
assertEquals(3, stats.unsupportedTaskCount, "不支持续跑的模块也要可见,供运维人工重跑");
}
@Test
void 没有归属用户的中断任务跳过() {
FileTaskMapper mapper = mock(FileTaskMapper.class);
FileTaskEntity orphan = interruptedTask(28587L, "SIMILAR_ASIN");
orphan.setUserId(null);
when(mapper.selectList(any())).thenReturn(List.of(orphan));
TaskResumeService service = service(mapper, List.of(spi("SIMILAR_ASIN")), true, 3);
TaskResumeService.ResumeStats stats = service.resumeInterruptedTasks();
assertEquals(1, stats.skippedTaskCount);
verify(mapper, never()).insert(any(FileTaskEntity.class));
}
}
@@ -596,7 +596,9 @@ function taskKeywordProgress(item: CollectDataHistoryItem) {
function canDownload(item: CollectDataHistoryItem) {
const status = normalizeTaskStatus(item)
return Boolean(item.downloadUrl && (item.success || status === 'SUCCESS'))
// 失败任务只要已生成结果文件也允许下载:失败时后端按已收到的分片组装部分结果,
// 已采集的数据不应随任务失败一起不可用(taskId 28599 事故)。
return Boolean(item.downloadUrl && (item.success || status === 'SUCCESS' || status === 'FAILED'))
}
async function downloadResult(item: CollectDataHistoryItem) {
@@ -1658,7 +1658,8 @@ function statusClass(item: PriceTrackHistoryItem) {
function canDownload(item: PriceTrackHistoryItem) {
if (!item.resultId || (!item.fileReady && !item.downloadUrl)) return false
const st = resolvedTaskStatus(item)
return st === 'SUCCESS' || item.success === true
// 失败任务也可能有已跑出来的部分结果文件(后端按已收分片组装),有文件就允许下载
return st === 'SUCCESS' || item.success === true || st === 'FAILED'
}
async function downloadResult(item: PriceTrackHistoryItem) {
@@ -1018,7 +1018,8 @@ function statusClass(item: ProductRiskHistoryItem) {
function canDownload(item: ProductRiskHistoryItem) {
if (!item.resultId || (!item.fileReady && !item.downloadUrl)) return false
const st = resolvedTaskStatus(item)
return st === 'SUCCESS' || item.success === true
// 失败任务也可能有已跑出来的部分结果文件(后端按已收分片组装),有文件就允许下载
return st === 'SUCCESS' || item.success === true || st === 'FAILED'
}
async function downloadResult(item: ProductRiskHistoryItem) {
@@ -531,7 +531,8 @@ function currentTaskStageText(item: ShopMatchHistoryItem) { const snapshot = tas
function nextScheduledDisplay(item: ShopMatchHistoryItem) { const snapshot = taskSnapshotOf(item); const task = snapshot?.task; const stages = task?.scheduleStages || []; if (typeof task?.currentStageIndex === 'number') { const stage = stages.find((entry) => entry.stageIndex === task.currentStageIndex); if (stage?.scheduledAt) return formatMonthDayTime(stage.scheduledAt) } if (item.scheduledAt) return formatMonthDayTime(item.scheduledAt); return '' }
function statusText(item: ShopMatchHistoryItem) { const status = resolvedTaskStatus(item); if (status === 'SCHEDULED') return '待执行'; if (status === 'RUNNING') return '执行中'; if (status === 'SUCCESS' || status === 'COMPLETED') return '已完成'; if (status === 'FAILED') return '失败'; return item.success ? '已完成' : '未知' }
function statusClass(item: ShopMatchHistoryItem) { const status = resolvedTaskStatus(item); return status === 'SUCCESS' || status === 'COMPLETED' ? 'success' : status === 'FAILED' ? 'failed' : 'running' }
function canDownload(item: ShopMatchHistoryItem) { const status = resolvedTaskStatus(item); return !!item.resultId && (!!item.fileReady || !!item.downloadUrl) && (status === 'SUCCESS' || status === 'COMPLETED') }
// 失败任务也可能有已跑出来的部分结果文件(后端按已收分片组装),有文件就允许下载
function canDownload(item: ShopMatchHistoryItem) { const status = resolvedTaskStatus(item); return !!item.resultId && (!!item.fileReady || !!item.downloadUrl) && (status === 'SUCCESS' || status === 'COMPLETED' || status === 'FAILED') }
async function downloadResult(item: ShopMatchHistoryItem) { if (!item.resultId) return; const url = getShopMatchResultDownloadUrl(item.resultId); const filename = item.outputFilename || `${item.shopName || 'result'}.xlsx`; const result = await saveUrlWithProgress(url, filename, `shop-match:${item.resultId}`); if (result.success) ElMessage.success(`已保存: ${result.path || filename}`); else if (result.error && result.error !== '用户取消') ElMessage.error(result.error) }
async function deleteTaskRecord(item: ShopMatchHistoryItem) {
const taskId = normalizeTaskId(item.taskId)