Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 19a291ec39 | |||
| df77a62b22 | |||
| f5e5717443 | |||
| 73838916ef | |||
| 4d70a0d3f8 | |||
| 7da9311265 |
@@ -27,7 +27,8 @@ public class BrandCheckProperties {
|
||||
* 一次批量检查的总耗时上限(毫秒):整批用尽后不再重试,剩余品牌按「查询失败」收尾。
|
||||
* 上限的意义不是省时间,而是给「分片回传」这类同步调用方一个时延上界——上游卡死时
|
||||
* 单品牌 10 次重试曾把一次回传拖到 103.5 秒(taskId 28599),客户端重试预算耗尽后
|
||||
* 中止了整个采集。首轮请求始终执行,故上游只是略慢时不会误降级。
|
||||
* 中止了整个采集。首轮请求在「预算 + 1 秒排队宽限」内执行;检查池被慢请求占满时
|
||||
* 不再无限等队列,剩余品牌按查询失败转补测,避免把同步回传线程拖到分钟级。
|
||||
* 设为 0 或负数表示不限制。
|
||||
*/
|
||||
private int totalTimeoutMillis = 90000;
|
||||
|
||||
+90
-749
File diff suppressed because it is too large
Load Diff
+140
@@ -0,0 +1,140 @@
|
||||
package com.nanri.aiimage.modules.appearancepatent.service.support;
|
||||
|
||||
import cn.hutool.crypto.digest.DigestUtil;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.nanri.aiimage.modules.appearancepatent.model.dto.AppearancePatentResultRowDto;
|
||||
import com.nanri.aiimage.modules.task.mapper.TaskChunkMapper;
|
||||
import com.nanri.aiimage.modules.task.model.entity.TaskChunkEntity;
|
||||
import com.nanri.aiimage.modules.task.service.TransientPayloadStorageService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
|
||||
/**
|
||||
* 外观专利的分片载荷合并(D 聚类的一格),从 {@code AppearancePatentTaskService}
|
||||
* <b>原样搬移</b>(3A 拆薄第十三笔):CAS 重试、版本化对象保留、冲突哈希读回与全部日志文案
|
||||
* 一字未改;读分片行、行键、载荷写入、序列化出口仍由服务侧以回调交入。
|
||||
*/
|
||||
@Slf4j
|
||||
public class AppearancePatentChunkPayloadMerger {
|
||||
|
||||
@FunctionalInterface
|
||||
public interface ChunkPayloadVersionWriter {
|
||||
String storeVersioned(Long taskId, String scopeHash, Integer chunkIndex, String payloadJson);
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
public interface JsonWriter {
|
||||
String write(Object value, String failureMessage);
|
||||
}
|
||||
|
||||
private static final int CHUNK_PAYLOAD_MERGE_RETRY_LIMIT = 3;
|
||||
|
||||
private final String moduleType;
|
||||
private final TaskChunkMapper taskChunkMapper;
|
||||
private final TransientPayloadStorageService transientPayloadStorageService;
|
||||
private final Function<TaskChunkEntity, Map<String, AppearancePatentResultRowDto>> chunkRowReader;
|
||||
private final Function<AppearancePatentResultRowDto, String> rowKeyer;
|
||||
private final ChunkPayloadVersionWriter versionWriter;
|
||||
private final JsonWriter jsonWriter;
|
||||
|
||||
public AppearancePatentChunkPayloadMerger(String moduleType,
|
||||
TaskChunkMapper taskChunkMapper,
|
||||
TransientPayloadStorageService transientPayloadStorageService,
|
||||
Function<TaskChunkEntity, Map<String, AppearancePatentResultRowDto>> chunkRowReader,
|
||||
Function<AppearancePatentResultRowDto, String> rowKeyer,
|
||||
ChunkPayloadVersionWriter versionWriter,
|
||||
JsonWriter jsonWriter) {
|
||||
this.moduleType = moduleType;
|
||||
this.taskChunkMapper = taskChunkMapper;
|
||||
this.transientPayloadStorageService = transientPayloadStorageService;
|
||||
this.chunkRowReader = chunkRowReader;
|
||||
this.rowKeyer = rowKeyer;
|
||||
this.versionWriter = versionWriter;
|
||||
this.jsonWriter = jsonWriter;
|
||||
}
|
||||
|
||||
/** 返回真正写进这一片载荷的行键:一片也没写成时返回空集,调用方据此决定哪些行还能重发。 */
|
||||
public List<String> mergeChunkPayload(Long taskId, String scopeHash, Integer chunkIndex,
|
||||
List<AppearancePatentResultRowDto> rows) {
|
||||
if (rows == null || rows.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
String conflictDetail = "未发生冲突";
|
||||
for (int attempt = 1; attempt <= CHUNK_PAYLOAD_MERGE_RETRY_LIMIT; attempt++) {
|
||||
TaskChunkEntity chunk = taskChunkMapper.selectOne(new LambdaQueryWrapper<TaskChunkEntity>()
|
||||
.eq(TaskChunkEntity::getTaskId, taskId)
|
||||
.eq(TaskChunkEntity::getModuleType, moduleType)
|
||||
.eq(TaskChunkEntity::getScopeHash, scopeHash)
|
||||
.eq(TaskChunkEntity::getChunkIndex, chunkIndex)
|
||||
.last("limit 1"));
|
||||
if (chunk == null) {
|
||||
return List.of();
|
||||
}
|
||||
Map<String, AppearancePatentResultRowDto> persistedRows = chunkRowReader.apply(chunk);
|
||||
for (AppearancePatentResultRowDto row : rows) {
|
||||
String key = rowKeyer.apply(row);
|
||||
AppearancePatentResultRowDto submittedRow = persistedRows.get(key);
|
||||
if (submittedRow != null) {
|
||||
row.setPrice(submittedRow.getPrice());
|
||||
}
|
||||
persistedRows.put(key, row);
|
||||
}
|
||||
String payloadJson = jsonWriter.write(new ArrayList<>(persistedRows.values()), "appearance patent chunk payload merge failed");
|
||||
String oldPayload = chunk.getPayloadJson();
|
||||
String oldPayloadHash = chunk.getPayloadHash();
|
||||
String newPayloadHash = DigestUtil.sha256Hex(payloadJson);
|
||||
String storedPayload = versionWriter.storeVersioned(taskId, scopeHash, chunkIndex, payloadJson);
|
||||
LambdaUpdateWrapper<TaskChunkEntity> updateWrapper = new LambdaUpdateWrapper<TaskChunkEntity>()
|
||||
.eq(TaskChunkEntity::getId, chunk.getId())
|
||||
.set(TaskChunkEntity::getPayloadJson, storedPayload)
|
||||
.set(TaskChunkEntity::getPayloadHash, newPayloadHash)
|
||||
.set(TaskChunkEntity::getUpdatedAt, LocalDateTime.now());
|
||||
if (oldPayloadHash == null) {
|
||||
updateWrapper.isNull(TaskChunkEntity::getPayloadHash);
|
||||
} else {
|
||||
updateWrapper.eq(TaskChunkEntity::getPayloadHash, oldPayloadHash);
|
||||
}
|
||||
int updated = taskChunkMapper.update(null, updateWrapper);
|
||||
if (updated > 0) {
|
||||
log.debug("[appearance-patent] chunk payload replaced taskId={} scopeHash={} chunk={} oldPayload={} newPayload={} attempt={}",
|
||||
taskId, scopeHash, chunkIndex, oldPayload, storedPayload, attempt);
|
||||
transientPayloadStorageService.deleteReplacedPayloadIfNeeded(oldPayload, storedPayload);
|
||||
return rows.stream().map(rowKeyer).filter(key -> !key.isBlank()).toList();
|
||||
}
|
||||
// CAS 冲突:读回行上的当前哈希,否则只有一句 conflict 无从判断是谁改的(线上 28459 至今未能定位)
|
||||
String currentHash = currentPayloadHash(chunk.getId());
|
||||
conflictDetail = "期望hash=" + oldPayloadHash + " 当前hash=" + currentHash;
|
||||
if (attempt < CHUNK_PAYLOAD_MERGE_RETRY_LIMIT) {
|
||||
log.warn("[appearance-patent] chunk payload CAS conflict, retry merge taskId={} scopeHash={} chunk={} attempt={}/{} 期望hash={} 当前hash={}",
|
||||
taskId, scopeHash, chunkIndex, attempt, CHUNK_PAYLOAD_MERGE_RETRY_LIMIT, oldPayloadHash, currentHash);
|
||||
// 还要重试:这次写的对象会被下次重写,先删掉避免堆积
|
||||
transientPayloadStorageService.deletePayloadIfPresent(storedPayload);
|
||||
} else {
|
||||
// 终局失败:保留这次写入的版本化对象,作为读路径「同槽位兄弟对象」兜底的恢复源。
|
||||
// 行没指过去不该让该分片永久判死——删掉它才是线上 28459 丢数据的形态。
|
||||
log.error("[appearance-patent] chunk payload 合并冲突重试耗尽,保留兜底对象 taskId={} scopeHash={} chunk={} 期望hash={} 当前hash={} 保留对象={}",
|
||||
taskId, scopeHash, chunkIndex, oldPayloadHash, currentHash, storedPayload);
|
||||
}
|
||||
}
|
||||
throw new IllegalStateException("appearance patent chunk payload update conflict " + conflictDetail);
|
||||
}
|
||||
|
||||
/** 读回 chunk 行当前的 payload_hash,用于 CAS 冲突定位(行已不存在/读取失败时返回可读标记)。 */
|
||||
private String currentPayloadHash(Long chunkId) {
|
||||
if (chunkId == null) {
|
||||
return "chunkId 为空";
|
||||
}
|
||||
try {
|
||||
TaskChunkEntity latest = taskChunkMapper.selectById(chunkId);
|
||||
return latest == null ? "行已不存在" : latest.getPayloadHash();
|
||||
} catch (Exception ex) {
|
||||
return "读取失败:" + ex.getMessage();
|
||||
}
|
||||
}
|
||||
}
|
||||
+92
@@ -167,6 +167,98 @@ public class AppearancePatentChunkSubmissionSupport {
|
||||
request.getError(), payloadJson, storedPayload, DigestUtil.sha256Hex(payloadJson));
|
||||
}
|
||||
|
||||
/**
|
||||
* 无事务管理器时的直写回传(原 {@code submitResultLocked} 的 {@code transactionManager == null}
|
||||
* 分支,3A 拆薄第十三笔原样搬移):准入、归属、分片去重、scope 合并与收尾都在同一段里,
|
||||
* 判序、日志与「重复分片不删赢家载荷」那条注释一字未改。
|
||||
*/
|
||||
public SubmitContext receiveWithoutTransaction(Long taskId, AppearancePatentSubmitResultRequest request) {
|
||||
FileTaskEntity task = fileTaskMapper.selectById(taskId);
|
||||
if (task == null || !moduleType.equals(task.getModuleType())) {
|
||||
throw new BusinessException("任务不存在");
|
||||
}
|
||||
ownershipChecker.check(task, "submit result");
|
||||
if (!STATUS_RUNNING.equals(task.getStatus())) {
|
||||
TaskResultAdmission.rejectNotRunning(task.getStatus());
|
||||
}
|
||||
|
||||
int chunkIndex = request.getChunkIndex() == null ? 0 : request.getChunkIndex();
|
||||
int chunkTotal = request.getChunkTotal() == null ? 1 : request.getChunkTotal();
|
||||
String scopeKey = firstNonBlank.pick(request.getSubmissionId(), "task:" + taskId);
|
||||
String scopeHash = DigestUtil.sha256Hex(scopeKey);
|
||||
taskCacheService.touchTaskHeartbeat(taskId);
|
||||
|
||||
TaskChunkEntity existing = taskChunkMapper.selectOne(new LambdaQueryWrapper<TaskChunkEntity>()
|
||||
.eq(TaskChunkEntity::getTaskId, taskId)
|
||||
.eq(TaskChunkEntity::getModuleType, moduleType)
|
||||
.eq(TaskChunkEntity::getScopeHash, scopeHash)
|
||||
.eq(TaskChunkEntity::getChunkIndex, chunkIndex)
|
||||
.last("limit 1"));
|
||||
if (existing == null) {
|
||||
List<AppearancePatentResultRowDto> rawRows = rowFlattener.flatten(request);
|
||||
String payloadJson = jsonWriter.write(rawRows, "结果序列化失败");
|
||||
|
||||
TaskChunkEntity chunk = new TaskChunkEntity();
|
||||
chunk.setTaskId(taskId);
|
||||
chunk.setModuleType(moduleType);
|
||||
chunk.setScopeKey(scopeKey);
|
||||
chunk.setScopeHash(scopeHash);
|
||||
chunk.setChunkIndex(chunkIndex);
|
||||
chunk.setChunkTotal(chunkTotal);
|
||||
String storedPayload = chunkPayloadWriter.store(taskId, scopeHash, chunkIndex, payloadJson);
|
||||
chunk.setPayloadJson(storedPayload);
|
||||
chunk.setPayloadHash(DigestUtil.sha256Hex(payloadJson));
|
||||
chunk.setCreatedAt(LocalDateTime.now());
|
||||
chunk.setUpdatedAt(LocalDateTime.now());
|
||||
try {
|
||||
taskChunkMapper.insert(chunk);
|
||||
} catch (DuplicateKeyException ex) {
|
||||
// storeChunkPayload uses a deterministic key like chunk-{index}. When two
|
||||
// concurrent callbacks submit the same chunk, deleting the loser payload here
|
||||
// can also remove the winner's shared object and break later assembly.
|
||||
log.info("[appearance-patent] duplicate chunk inserted concurrently taskId={} scope={} chunk={}", taskId, scopeKey, chunkIndex);
|
||||
}
|
||||
} else {
|
||||
log.info("[appearance-patent] duplicate chunk ignored taskId={} scope={} chunk={}", taskId, scopeKey, chunkIndex);
|
||||
}
|
||||
|
||||
TaskScopeStateEntity scope = taskScopeStateMapper.selectOne(new LambdaQueryWrapper<TaskScopeStateEntity>()
|
||||
.eq(TaskScopeStateEntity::getTaskId, taskId)
|
||||
.eq(TaskScopeStateEntity::getModuleType, moduleType)
|
||||
.eq(TaskScopeStateEntity::getScopeHash, scopeHash)
|
||||
.last("limit 1"));
|
||||
if (scope == null) {
|
||||
scope = new TaskScopeStateEntity();
|
||||
scope.setTaskId(taskId);
|
||||
scope.setModuleType(moduleType);
|
||||
scope.setScopeKey(scopeKey);
|
||||
scope.setScopeHash(scopeHash);
|
||||
scope.setCreatedAt(LocalDateTime.now());
|
||||
}
|
||||
scope.setChunkTotal(chunkTotal);
|
||||
scope.setReceivedChunkCount(countChunks(taskId, scopeHash));
|
||||
scope.setLastChunkAt(LocalDateTime.now());
|
||||
scope.setLastError(request.getError());
|
||||
scope.setCompleted(Boolean.TRUE.equals(request.getDone()) ? 1 : 0);
|
||||
scope.setUpdatedAt(LocalDateTime.now());
|
||||
scope.setStateJson("{\"phase\":\"RECEIVED\",\"llm\":\"PENDING\"}");
|
||||
if (scope.getId() == null) {
|
||||
taskScopeStateMapper.insert(scope);
|
||||
} else {
|
||||
taskScopeStateMapper.updateById(scope);
|
||||
}
|
||||
|
||||
SubmitContext context = new SubmitContext(task, scopeKey, scopeHash, chunkIndex,
|
||||
Boolean.TRUE.equals(request.getDone()), request.getError());
|
||||
if (Boolean.TRUE.equals(request.getDone()) || request.getError() != null && !request.getError().isBlank()) {
|
||||
finalizer.finalizeTask(task, request.getError(), rowCounter.count(task), true);
|
||||
} else {
|
||||
task.setUpdatedAt(LocalDateTime.now());
|
||||
fileTaskMapper.updateById(task);
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
||||
public SubmitContext persistSubmittedChunk(PreparedSubmittedChunk prepared) {
|
||||
Long taskId = prepared.task().getId();
|
||||
FileTaskEntity task = fileTaskMapper.selectById(taskId);
|
||||
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package com.nanri.aiimage.modules.appearancepatent.service.support;
|
||||
|
||||
import com.nanri.aiimage.modules.appearancepatent.model.vo.AppearancePatentParsedGroupVo;
|
||||
import com.nanri.aiimage.modules.appearancepatent.model.vo.AppearancePatentParsedRowVo;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 外观专利的解析行分组(建单与解析载荷共用),从 {@code AppearancePatentTaskService}
|
||||
* <b>原样搬移</b>(3A 拆薄第十三笔)。归一、首非空与基 id 直接引用
|
||||
* {@link AppearancePatentRowNormalizer}——服务侧那两枚同名私有件的重复实现随之退场
|
||||
* (2026-10-19 登记的那笔「服务对 util 零引用」的账)。
|
||||
*/
|
||||
public final class AppearancePatentGroupingSupport {
|
||||
|
||||
public List<AppearancePatentParsedGroupVo> buildParsedGroups(List<AppearancePatentParsedRowVo> rows) {
|
||||
List<AppearancePatentParsedGroupVo> groups = new ArrayList<>();
|
||||
for (List<AppearancePatentParsedRowVo> siblings : groupRowsByBaseId(rows).values()) {
|
||||
if (siblings == null || siblings.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
AppearancePatentParsedRowVo first = siblings.getFirst();
|
||||
AppearancePatentParsedGroupVo group = new AppearancePatentParsedGroupVo();
|
||||
group.setSourceFileKey(first.getSourceFileKey());
|
||||
group.setSourceFilename(first.getSourceFilename());
|
||||
group.setGroupKey(AppearancePatentRowNormalizer.firstNonBlank(first.getGroupKey(),
|
||||
buildGroupKey(first.getSourceFileKey(), AppearancePatentRowNormalizer.baseId(first.getDisplayId()), first.getRowIndex())));
|
||||
group.setBaseId(AppearancePatentRowNormalizer.baseId(first.getDisplayId()));
|
||||
group.setDisplayId(AppearancePatentRowNormalizer.firstNonBlank(first.getDisplayId(), first.getSourceId()));
|
||||
group.setItemCount(siblings.size());
|
||||
group.setItems(new ArrayList<>(siblings));
|
||||
groups.add(group);
|
||||
}
|
||||
return groups;
|
||||
}
|
||||
|
||||
public int countParsedGroups(List<AppearancePatentParsedRowVo> rows) {
|
||||
return groupRowsByBaseId(rows).size();
|
||||
}
|
||||
|
||||
public Map<String, List<AppearancePatentParsedRowVo>> groupRowsByBaseId(List<AppearancePatentParsedRowVo> rows) {
|
||||
Map<String, List<AppearancePatentParsedRowVo>> result = new LinkedHashMap<>();
|
||||
if (rows == null) {
|
||||
return result;
|
||||
}
|
||||
for (AppearancePatentParsedRowVo row : rows) {
|
||||
String key = AppearancePatentRowNormalizer.firstNonBlank(
|
||||
AppearancePatentRowNormalizer.normalize(row.getGroupKey()),
|
||||
AppearancePatentRowNormalizer.baseId(row.getDisplayId()));
|
||||
result.computeIfAbsent(key, ignored -> new ArrayList<>()).add(row);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public String buildGroupKey(String sourceFileKey, String rowBaseId, Integer rowIndex) {
|
||||
return AppearancePatentRowNormalizer.normalize(sourceFileKey) + "::"
|
||||
+ AppearancePatentRowNormalizer.normalize(rowBaseId) + "@" + (rowIndex == null ? 0 : rowIndex);
|
||||
}
|
||||
}
|
||||
+171
@@ -0,0 +1,171 @@
|
||||
package com.nanri.aiimage.modules.appearancepatent.service.support;
|
||||
|
||||
import com.nanri.aiimage.common.task.TaskStatuses;
|
||||
import com.nanri.aiimage.modules.appearancepatent.model.dto.AppearancePatentParsedPayloadDto;
|
||||
import com.nanri.aiimage.modules.appearancepatent.service.support.AppearancePatentChunkSubmissionSupport.SubmitContext;
|
||||
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.TaskChunkEntity;
|
||||
import com.nanri.aiimage.modules.task.model.entity.TaskFileJobEntity;
|
||||
import com.nanri.aiimage.modules.task.service.TaskFileJobService;
|
||||
import com.nanri.aiimage.modules.usersecret.service.UserApiSecretService;
|
||||
import com.nanri.aiimage.modules.usersecret.support.UserSecretModule;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
/**
|
||||
* 外观专利的 LLM 提交调度与凭据读取,从 {@code AppearancePatentTaskService} <b>原样搬移</b>
|
||||
* (3A 拆薄第十三笔):回传后的组装 job 排期、Python 超时恢复时的补提交,以及
|
||||
* 任务 payload/用户密钥两级读取,连同日志与判序一字未改。
|
||||
*
|
||||
* <p><b>搬的是调度,不是批管线本身。</b>批管线在 {@link AppearancePatentLlmBatchPipeline},
|
||||
* 收尾、行计数、结果行创建与心跳触活仍由服务侧以回调交入。
|
||||
*/
|
||||
@Slf4j
|
||||
public class AppearancePatentLlmSubmissionSupport {
|
||||
|
||||
@FunctionalInterface
|
||||
public interface BatchSubmitter {
|
||||
void submit(FileTaskEntity task, FileResultEntity result, TaskFileJobEntity job, List<TaskChunkEntity> chunks);
|
||||
}
|
||||
|
||||
private static final String STATUS_SUCCESS = TaskStatuses.FileTask.SUCCESS;
|
||||
|
||||
private final String moduleType;
|
||||
private final FileTaskMapper fileTaskMapper;
|
||||
private final TaskFileJobService taskFileJobService;
|
||||
private final Function<Long, List<TaskChunkEntity>> submittedChunksLoader;
|
||||
private final Function<FileTaskEntity, Integer> rowCounter;
|
||||
private final BiFunction<FileTaskEntity, Integer, FileResultEntity> resultRecordFinder;
|
||||
private final BatchSubmitter batchSubmitter;
|
||||
private final Predicate<Long> submissionComplete;
|
||||
private final Consumer<Long> taskActivityToucher;
|
||||
private final Function<FileTaskEntity, String> taskOwnerScopeKeyBuilder;
|
||||
private final Function<FileTaskEntity, AppearancePatentParsedPayloadDto> payloadReader;
|
||||
private final UserApiSecretService userApiSecretService;
|
||||
private final Function<String, String> normalizer;
|
||||
|
||||
public AppearancePatentLlmSubmissionSupport(String moduleType,
|
||||
FileTaskMapper fileTaskMapper,
|
||||
TaskFileJobService taskFileJobService,
|
||||
Function<Long, List<TaskChunkEntity>> submittedChunksLoader,
|
||||
Function<FileTaskEntity, Integer> rowCounter,
|
||||
BiFunction<FileTaskEntity, Integer, FileResultEntity> resultRecordFinder,
|
||||
BatchSubmitter batchSubmitter,
|
||||
Predicate<Long> submissionComplete,
|
||||
Consumer<Long> taskActivityToucher,
|
||||
Function<FileTaskEntity, String> taskOwnerScopeKeyBuilder,
|
||||
Function<FileTaskEntity, AppearancePatentParsedPayloadDto> payloadReader,
|
||||
UserApiSecretService userApiSecretService,
|
||||
Function<String, String> normalizer) {
|
||||
this.moduleType = moduleType;
|
||||
this.fileTaskMapper = fileTaskMapper;
|
||||
this.taskFileJobService = taskFileJobService;
|
||||
this.submittedChunksLoader = submittedChunksLoader;
|
||||
this.rowCounter = rowCounter;
|
||||
this.resultRecordFinder = resultRecordFinder;
|
||||
this.batchSubmitter = batchSubmitter;
|
||||
this.submissionComplete = submissionComplete;
|
||||
this.taskActivityToucher = taskActivityToucher;
|
||||
this.taskOwnerScopeKeyBuilder = taskOwnerScopeKeyBuilder;
|
||||
this.payloadReader = payloadReader;
|
||||
this.userApiSecretService = userApiSecretService;
|
||||
this.normalizer = normalizer;
|
||||
}
|
||||
|
||||
public void submitLlmForSubmittedChunk(SubmitContext context) {
|
||||
if (context == null || context.task() == null || context.task().getId() == null) {
|
||||
return;
|
||||
}
|
||||
FileTaskEntity task = fileTaskMapper.selectById(context.task().getId());
|
||||
if (task == null || !moduleType.equals(task.getModuleType()) || STATUS_SUCCESS.equals(task.getStatus())) {
|
||||
return;
|
||||
}
|
||||
List<TaskChunkEntity> chunks = submittedChunksLoader.apply(task.getId());
|
||||
if (chunks.isEmpty()) {
|
||||
log.info("[appearance-patent] skip stale recovery llm submission because no submitted chunks remain taskId={}",
|
||||
task.getId());
|
||||
return;
|
||||
}
|
||||
FileResultEntity result = resultRecordFinder.apply(task, rowCounter.apply(task));
|
||||
if (result == null) {
|
||||
log.warn("[appearance-patent] stale recovery could not create result record taskId={}", task.getId());
|
||||
return;
|
||||
}
|
||||
TaskFileJobEntity job = taskFileJobService.enqueueAssembleResult(
|
||||
task.getId(), moduleType, result.getId(), taskOwnerScopeKeyBuilder.apply(task));
|
||||
if (job == null || "SUCCESS".equals(job.getStatus())) {
|
||||
log.info("[appearance-patent] stale recovery skipped llm submission because result job unavailable taskId={} resultId={} jobStatus={}",
|
||||
task.getId(), result.getId(), job == null ? null : job.getStatus());
|
||||
return;
|
||||
}
|
||||
log.info("[appearance-patent] stale recovery created assemble job taskId={} resultId={} jobId={} jobStatus={} chunkCount={}",
|
||||
task.getId(), result.getId(), job.getId(), job.getStatus(), chunks.size());
|
||||
batchSubmitter.submit(task, result, job, chunks);
|
||||
if (submissionComplete.test(task.getId())) {
|
||||
taskFileJobService.requeue(job.getId(), "检测结果已回流,正在组装 xlsx");
|
||||
} else {
|
||||
taskFileJobService.touchRunning(job.getId());
|
||||
}
|
||||
taskActivityToucher.accept(task.getId());
|
||||
}
|
||||
|
||||
public void scheduleLlmPipelineForSubmittedChunk(SubmitContext context) {
|
||||
if (context == null || context.task() == null || context.task().getId() == null) {
|
||||
return;
|
||||
}
|
||||
FileTaskEntity task = fileTaskMapper.selectById(context.task().getId());
|
||||
if (task == null || !moduleType.equals(task.getModuleType()) || STATUS_SUCCESS.equals(task.getStatus())) {
|
||||
return;
|
||||
}
|
||||
List<TaskChunkEntity> chunks = submittedChunksLoader.apply(task.getId());
|
||||
if (chunks.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
FileResultEntity result = resultRecordFinder.apply(task, rowCounter.apply(task));
|
||||
if (result == null) {
|
||||
return;
|
||||
}
|
||||
TaskFileJobEntity job = taskFileJobService.enqueueAssembleResult(
|
||||
task.getId(), moduleType, result.getId(), taskOwnerScopeKeyBuilder.apply(task));
|
||||
if (job == null || "SUCCESS".equals(job.getStatus())) {
|
||||
return;
|
||||
}
|
||||
taskFileJobService.requeue(job.getId(), "Appearance patent result uploaded, scheduling LLM/file assembly");
|
||||
taskActivityToucher.accept(task.getId());
|
||||
}
|
||||
|
||||
public String readAiPrompt(FileTaskEntity task) {
|
||||
try {
|
||||
return payloadReader.apply(task).getAiPrompt();
|
||||
} catch (Exception ignored) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
/** 密钥读取:任务 payload 优先(兼容老任务与显式覆盖),为空时按任务归属用户从服务端密钥表兜底。 */
|
||||
public String readApiKey(FileTaskEntity task) {
|
||||
try {
|
||||
String fromPayload = normalizer.apply(payloadReader.apply(task).getApiKey());
|
||||
if (!fromPayload.isEmpty()) {
|
||||
return fromPayload;
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
log.warn("[appearance-patent] 读取任务 payload 密钥失败,尝试用户密钥兜底 taskId={} err={}",
|
||||
task.getId(), ex.getMessage());
|
||||
}
|
||||
String fromUserSecret = userApiSecretService.findPlainValue(
|
||||
task.getUserId(), UserSecretModule.APPEARANCE_PATENT.key());
|
||||
if (fromUserSecret.isEmpty()) {
|
||||
log.warn("[appearance-patent] 任务未携带密钥且用户未配置密钥,LLM 检测将保留原始行 taskId={} userId={}",
|
||||
task.getId(), task.getUserId());
|
||||
}
|
||||
return fromUserSecret;
|
||||
}
|
||||
}
|
||||
+471
@@ -0,0 +1,471 @@
|
||||
package com.nanri.aiimage.modules.appearancepatent.service.support;
|
||||
|
||||
import cn.hutool.crypto.digest.DigestUtil;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.util.FailedStatusRowFilter;
|
||||
import com.nanri.aiimage.config.AppearancePatentProperties;
|
||||
import com.nanri.aiimage.modules.appearancepatent.model.dto.AppearancePatentParseRequest;
|
||||
import com.nanri.aiimage.modules.appearancepatent.model.dto.AppearancePatentSourceFileDto;
|
||||
import com.nanri.aiimage.modules.appearancepatent.model.vo.AppearancePatentParseVo;
|
||||
import com.nanri.aiimage.modules.appearancepatent.model.vo.AppearancePatentParsedRowVo;
|
||||
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.TaskScopeStateMapper;
|
||||
import com.nanri.aiimage.modules.task.model.entity.FileResultEntity;
|
||||
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
|
||||
import com.nanri.aiimage.common.task.TaskStatuses;
|
||||
import com.nanri.aiimage.modules.task.model.entity.TaskScopeStateEntity;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.File;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* 外观专利**建单段(parse)聚类**——3A 拆薄第十二笔。
|
||||
*
|
||||
* <p>搬过来的是 {@code parseAndCreateTask} 本体(建单四段:解析 → 头行 → 载荷/索引 → 结果行/作用域行)、
|
||||
* {@code parseWorkbook}(Excel 行级组装、状态列过滤、组内字段补齐)、以及只被这两段用的表头/键件
|
||||
* ({@code statusHeaderName}/{@code hydratePromptFields}/{@code isAppearanceResultWorkbook}/
|
||||
* {@code hasHeader}/{@code normalizeDisplayId}/{@code mergeHeaders}/{@code buildRowToken})
|
||||
* 与两个聚合命名件({@code buildAggregateScopeKey}/{@code buildAggregateSourceFilenameLabel})。
|
||||
*
|
||||
* <p><b>为什么这些能一次性搬、又为什么剩下的不能顺手搬</b>:
|
||||
* <ul>
|
||||
* <li>{@code baseId}/{@code buildGroupKey}/{@code normalize}/{@code firstNonBlank} 在服务侧
|
||||
* 还被 {@code buildParsedGroups}/{@code groupRowsByBaseId}/{@code shouldInspectRow} 等
|
||||
* 非 parse 面共用 ⇒ 本件只接回调,不搬实现(不复制第二份,也不把它们从服务侧抽走)。</li>
|
||||
* <li>底座四件({@code requireUserId}/{@code newTaskHeader}/{@code insertTask}/
|
||||
* {@code newScopeRow})与序列化出口 {@code writeJson} 是 {@code protected} 的宿主能力,
|
||||
* 经回调交入;本件不继承底座、也不持有 mapper 之外的底座状态。</li>
|
||||
* <li>载荷三段(组装/落库/索引 JSON)仍归 {@link AppearancePatentPayloadSupport}(I 聚类),
|
||||
* 本件只经 {@link Supplier} 取用既有实例。</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p><b>可观测差异(如实登记)</b>:parse 分段计时那行日志的 logger 名从
|
||||
* {@code ...service.AppearancePatentTaskService} 变为 {@code ...service.support.AppearancePatentParsePipeline},
|
||||
* 消息文本、级别、字段顺序一字未动;按 logger 名做日志检索的人要跟着换。
|
||||
*
|
||||
* <p><b>事务语义一字未动</b>:本支建单<b>全程无事务</b>(载荷存储失败时头行已 insert),
|
||||
* 与 {@code AppearancePatentCreateTaskSnapshotTest} 的 golden 一致;本件不引入任何事务包装。
|
||||
*/
|
||||
public final class AppearancePatentParsePipeline {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(AppearancePatentParsePipeline.class);
|
||||
|
||||
@FunctionalInterface
|
||||
public interface HeaderFactory {
|
||||
FileTaskEntity create(String status, String taskMode, Long userId, String deviceId, int sourceFileCount);
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
public interface ScopeRowFactory {
|
||||
FileResultEntity create(Long taskId, Long userId, String sourceFilename, String sourceFileUrl,
|
||||
Integer rowCount, Integer success);
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
public interface JsonWriter {
|
||||
String write(Object value, String failureMessage);
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
public interface RowCounter {
|
||||
int count(List<AppearancePatentParsedRowVo> rows);
|
||||
}
|
||||
|
||||
private final String moduleType;
|
||||
private final LocalFileStorageService localFileStorageService;
|
||||
private final AppearancePatentProperties properties;
|
||||
private final FileTaskMapper fileTaskMapper;
|
||||
private final FileResultMapper fileResultMapper;
|
||||
private final TaskScopeStateMapper taskScopeStateMapper;
|
||||
private final Consumer<Long> requireUserId;
|
||||
private final HeaderFactory headerFactory;
|
||||
private final Function<FileTaskEntity, FileTaskEntity> insertTask;
|
||||
private final ScopeRowFactory scopeRowFactory;
|
||||
private final JsonWriter jsonWriter;
|
||||
private final Supplier<AppearancePatentPayloadSupport> payloadSupport;
|
||||
private final RowCounter rowCounter;
|
||||
private final Function<String, String> normalize;
|
||||
private final java.util.function.BiFunction<String, String, String> firstNonBlank;
|
||||
private final Function<String, String> baseId;
|
||||
private final GroupKeyBuilder groupKeyBuilder;
|
||||
/** 组内归并仍住服务侧({@code buildParsedGroups}/{@code countParsedGroups} 共用同一份),本件只接回调。 */
|
||||
private final Function<List<AppearancePatentParsedRowVo>, Map<String, List<AppearancePatentParsedRowVo>>> groupRowsByBaseId;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface GroupKeyBuilder {
|
||||
String build(String sourceFileKey, String rowBaseId, Integer rowIndex);
|
||||
}
|
||||
|
||||
public AppearancePatentParsePipeline(String moduleType,
|
||||
LocalFileStorageService localFileStorageService,
|
||||
AppearancePatentProperties properties,
|
||||
FileTaskMapper fileTaskMapper,
|
||||
FileResultMapper fileResultMapper,
|
||||
TaskScopeStateMapper taskScopeStateMapper,
|
||||
Consumer<Long> requireUserId,
|
||||
HeaderFactory headerFactory,
|
||||
Function<FileTaskEntity, FileTaskEntity> insertTask,
|
||||
ScopeRowFactory scopeRowFactory,
|
||||
JsonWriter jsonWriter,
|
||||
Supplier<AppearancePatentPayloadSupport> payloadSupport,
|
||||
RowCounter rowCounter,
|
||||
Function<String, String> normalize,
|
||||
java.util.function.BiFunction<String, String, String> firstNonBlank,
|
||||
Function<String, String> baseId,
|
||||
GroupKeyBuilder groupKeyBuilder,
|
||||
Function<List<AppearancePatentParsedRowVo>, Map<String, List<AppearancePatentParsedRowVo>>> groupRowsByBaseId) {
|
||||
this.moduleType = moduleType;
|
||||
this.localFileStorageService = localFileStorageService;
|
||||
this.properties = properties;
|
||||
this.fileTaskMapper = fileTaskMapper;
|
||||
this.fileResultMapper = fileResultMapper;
|
||||
this.taskScopeStateMapper = taskScopeStateMapper;
|
||||
this.requireUserId = requireUserId;
|
||||
this.headerFactory = headerFactory;
|
||||
this.insertTask = insertTask;
|
||||
this.scopeRowFactory = scopeRowFactory;
|
||||
this.jsonWriter = jsonWriter;
|
||||
this.payloadSupport = payloadSupport;
|
||||
this.rowCounter = rowCounter;
|
||||
this.normalize = normalize;
|
||||
this.firstNonBlank = firstNonBlank;
|
||||
this.baseId = baseId;
|
||||
this.groupKeyBuilder = groupKeyBuilder;
|
||||
this.groupRowsByBaseId = groupRowsByBaseId;
|
||||
}
|
||||
|
||||
public AppearancePatentParseVo parseAndCreateTask(AppearancePatentParseRequest request, String deviceId) {
|
||||
long startedAt = System.nanoTime();
|
||||
requireUserId.accept(request.getUserId());
|
||||
if (request.getFiles() == null || request.getFiles().isEmpty()) {
|
||||
throw new BusinessException("请先上传 Excel 文件");
|
||||
}
|
||||
List<AppearancePatentSourceFileDto> sourceFiles = request.getFiles().stream()
|
||||
.filter(Objects::nonNull)
|
||||
.toList();
|
||||
if (sourceFiles.isEmpty()) {
|
||||
throw new BusinessException("请先上传 Excel 文件");
|
||||
}
|
||||
List<AppearancePatentParsedRowVo> allRows = new ArrayList<>();
|
||||
List<String> mergedHeaders = new ArrayList<>();
|
||||
int totalRows = 0;
|
||||
int droppedRows = 0;
|
||||
long parseStartedAt = System.nanoTime();
|
||||
for (AppearancePatentSourceFileDto source : sourceFiles) {
|
||||
if (source.getFileKey() == null || source.getFileKey().isBlank()) {
|
||||
throw new BusinessException("fileKey 不能为空");
|
||||
}
|
||||
File input = localFileStorageService.findLocalSourceFile(source.getFileKey());
|
||||
if (input == null || !input.exists()) {
|
||||
throw new BusinessException("源文件不存在");
|
||||
}
|
||||
|
||||
ParsedWorkbook parsed = parseWorkbook(input, source);
|
||||
int maxParseRows = Math.max(1, properties.getMaxParseRows());
|
||||
if ((long) allRows.size() + parsed.allRows().size() > maxParseRows) {
|
||||
throw new BusinessException("解析总行数超过上限: " + maxParseRows);
|
||||
}
|
||||
totalRows += parsed.totalRows();
|
||||
droppedRows += parsed.droppedRows();
|
||||
allRows.addAll(parsed.allRows());
|
||||
mergeHeaders(mergedHeaders, parsed.headers());
|
||||
}
|
||||
if (allRows.isEmpty()) {
|
||||
throw new BusinessException("未解析到有效 ASIN 数据");
|
||||
}
|
||||
long parsedAt = System.nanoTime();
|
||||
int groupCount = rowCounter.count(allRows);
|
||||
long groupedAt = System.nanoTime();
|
||||
|
||||
FileTaskEntity task = headerFactory.create(TaskStatuses.FileTask.PENDING, "PYTHON_QUEUE", request.getUserId(), deviceId,
|
||||
sourceFiles.size());
|
||||
task.setSuccessFileCount(0);
|
||||
task.setFailedFileCount(0);
|
||||
task.setRequestJson(jsonWriter.write(request, "序列化解析结果失败"));
|
||||
task.setResultJson("{}");
|
||||
insertTask.apply(task);
|
||||
long taskInsertedAt = System.nanoTime();
|
||||
|
||||
String aggregateScopeKey = buildAggregateScopeKey(sourceFiles);
|
||||
String sourceScopeHash = DigestUtil.sha256Hex(aggregateScopeKey);
|
||||
String parsedPayload = payloadSupport.get().buildParsedPayloadJson(request.getAiPrompt(), request.getApiKey(), sourceFiles, mergedHeaders, allRows);
|
||||
long payloadBuiltAt = System.nanoTime();
|
||||
String parsedPayloadPointer = payloadSupport.get().storeParsedPayload(task.getId(), sourceScopeHash, parsedPayload);
|
||||
long payloadStoredAt = System.nanoTime();
|
||||
task.setResultJson(payloadSupport.get().buildTaskResultJson(request.getAiPrompt(), request.getApiKey(), sourceFiles, parsedPayloadPointer));
|
||||
task.setUpdatedAt(LocalDateTime.now());
|
||||
fileTaskMapper.updateById(task);
|
||||
|
||||
String sourceFilename = buildAggregateSourceFilenameLabel(sourceFiles);
|
||||
// rowCount 记接受行数、success 留 NULL(本支建单不写占位值),这两列底座刻意不替它定
|
||||
FileResultEntity result = scopeRowFactory.create(task.getId(), request.getUserId(), sourceFilename,
|
||||
aggregateScopeKey, allRows.size(), null);
|
||||
fileResultMapper.insert(result);
|
||||
|
||||
TaskScopeStateEntity scope = new TaskScopeStateEntity();
|
||||
scope.setTaskId(task.getId());
|
||||
scope.setModuleType(moduleType);
|
||||
scope.setScopeKey(aggregateScopeKey);
|
||||
scope.setScopeHash(sourceScopeHash);
|
||||
scope.setParsedPayloadJson(jsonWriter.write(parsedPayloadPointer, "保存解析载荷指针失败"));
|
||||
scope.setStateJson("{\"phase\":\"PARSED\"}");
|
||||
scope.setChunkTotal(0);
|
||||
scope.setReceivedChunkCount(0);
|
||||
scope.setCompleted(0);
|
||||
scope.setCreatedAt(LocalDateTime.now());
|
||||
scope.setUpdatedAt(LocalDateTime.now());
|
||||
taskScopeStateMapper.insert(scope);
|
||||
long persistedAt = System.nanoTime();
|
||||
|
||||
AppearancePatentParseVo vo = new AppearancePatentParseVo();
|
||||
vo.setTaskId(task.getId());
|
||||
vo.setSourceFilename(sourceFilename);
|
||||
vo.setSourceFileCount(sourceFiles.size());
|
||||
vo.setTotalRows(totalRows);
|
||||
vo.setAcceptedRows(allRows.size());
|
||||
vo.setDroppedRows(droppedRows);
|
||||
vo.setGroupCount(groupCount);
|
||||
vo.setAiPrompt(normalize.apply(request.getAiPrompt()));
|
||||
vo.setItems(List.of());
|
||||
vo.setGroups(List.of());
|
||||
long finishedAt = System.nanoTime();
|
||||
log.info("[appearance-patent] parse timing taskId={} files={} rows={} groups={} totalMs={} parseMs={} groupMs={} taskInsertMs={} payloadJsonMs={} payloadStoreMs={} persistMs={} responseMs={}",
|
||||
task.getId(),
|
||||
sourceFiles.size(),
|
||||
allRows.size(),
|
||||
groupCount,
|
||||
elapsedMs(startedAt, finishedAt),
|
||||
elapsedMs(parseStartedAt, parsedAt),
|
||||
elapsedMs(parsedAt, groupedAt),
|
||||
elapsedMs(groupedAt, taskInsertedAt),
|
||||
elapsedMs(taskInsertedAt, payloadBuiltAt),
|
||||
elapsedMs(payloadBuiltAt, payloadStoredAt),
|
||||
elapsedMs(payloadStoredAt, persistedAt),
|
||||
elapsedMs(persistedAt, finishedAt));
|
||||
return vo;
|
||||
}
|
||||
|
||||
private ParsedWorkbook parseWorkbook(File input, AppearancePatentSourceFileDto source) {
|
||||
int maxParseRows = Math.max(1, properties.getMaxParseRows());
|
||||
AppearancePatentExcelParser.ParsedSheet sheet = new AppearancePatentExcelParser().parse(input, maxParseRows);
|
||||
List<String> headers = sheet.headers();
|
||||
int statusCol = FailedStatusRowFilter.findStatusColumnIndex(headers);
|
||||
boolean includeBlankStatusRows = statusCol >= 0 && isAppearanceResultWorkbook(headers);
|
||||
|
||||
Map<String, Integer> headerIndex = new LinkedHashMap<>();
|
||||
for (int i = 0; i < headers.size(); i++) {
|
||||
headerIndex.putIfAbsent(headers.get(i), i);
|
||||
}
|
||||
|
||||
List<ParsedAppearanceRow> parsedRows = new ArrayList<>();
|
||||
int total = 0;
|
||||
int dropped = 0;
|
||||
int validRows = 0;
|
||||
String currentBlockBaseId = "";
|
||||
String currentGroupKey = "";
|
||||
for (AppearancePatentExcelParser.AppearanceExcelRow parsed : sheet.rows()) {
|
||||
String id = parsed.id() == null ? "" : parsed.id();
|
||||
String asin = parsed.asin() == null ? "" : parsed.asin().toUpperCase(Locale.ROOT);
|
||||
String country = parsed.country() == null ? "" : parsed.country();
|
||||
if (id.isBlank() && asin.isBlank() && country.isBlank()) {
|
||||
continue;
|
||||
}
|
||||
total++;
|
||||
if (id.isBlank() || asin.isBlank() || country.isBlank()) {
|
||||
dropped++;
|
||||
continue;
|
||||
}
|
||||
validRows++;
|
||||
if (validRows > maxParseRows) {
|
||||
throw new BusinessException("解析行数超过上限: " + maxParseRows);
|
||||
}
|
||||
AppearancePatentParsedRowVo vo = new AppearancePatentParsedRowVo();
|
||||
vo.setSourceFileKey(source.getFileKey());
|
||||
vo.setSourceFilename(firstNonBlank.apply(source.getOriginalFilename(), input.getName()));
|
||||
vo.setRowIndex(parsed.rowIndex());
|
||||
vo.setSourceId(id);
|
||||
vo.setDisplayId(normalizeDisplayId(id));
|
||||
String rowBaseId = baseId.apply(vo.getDisplayId());
|
||||
if (!Objects.equals(currentBlockBaseId, rowBaseId)) {
|
||||
currentBlockBaseId = rowBaseId;
|
||||
currentGroupKey = groupKeyBuilder.build(source.getFileKey(), rowBaseId, vo.getRowIndex());
|
||||
}
|
||||
vo.setGroupKey(currentGroupKey);
|
||||
vo.setRowToken(buildRowToken(source.getFileKey(), vo.getRowIndex()));
|
||||
vo.setAsin(asin);
|
||||
vo.setCountry(country);
|
||||
vo.setPrice(parsed.price() == null ? "" : parsed.price());
|
||||
vo.setSku(parsed.sku() == null ? "" : parsed.sku());
|
||||
vo.setUrl(parsed.url() == null ? "" : parsed.url());
|
||||
vo.setTitle(parsed.title() == null ? "" : parsed.title());
|
||||
vo.setValues(parsed.values() == null ? new LinkedHashMap<>() : new LinkedHashMap<>(parsed.values()));
|
||||
String statusValue = statusCol >= 0 && parsed.values() != null
|
||||
? parsed.values().getOrDefault(statusHeaderName(headers, statusCol), "")
|
||||
: "";
|
||||
parsedRows.add(new ParsedAppearanceRow(vo, statusValue == null ? "" : statusValue));
|
||||
}
|
||||
List<AppearancePatentParsedRowVo> allRows = parsedRows.stream()
|
||||
.map(ParsedAppearanceRow::row)
|
||||
.toList();
|
||||
hydratePromptFields(allRows);
|
||||
FailedStatusRowFilter.FilterResult<ParsedAppearanceRow> filteredRows =
|
||||
FailedStatusRowFilter.retainRows(
|
||||
parsedRows,
|
||||
statusCol >= 0,
|
||||
ParsedAppearanceRow::sourceStatus,
|
||||
status -> FailedStatusRowFilter.matchesFailedStatus(status)
|
||||
|| (includeBlankStatusRows && FailedStatusRowFilter.isBlankStatus(status))
|
||||
);
|
||||
dropped += filteredRows.filteredCount();
|
||||
allRows = filteredRows.rows().stream()
|
||||
.map(ParsedAppearanceRow::row)
|
||||
.toList();
|
||||
if (statusCol >= 0 && validRows > 0 && allRows.isEmpty()) {
|
||||
throw new BusinessException(FailedStatusRowFilter.noMatchedRowsMessage());
|
||||
}
|
||||
if (allRows.isEmpty()) {
|
||||
throw new BusinessException("没有解析到可检测的外观专利行,请检查表格内容");
|
||||
}
|
||||
return new ParsedWorkbook(total, dropped, new ArrayList<>(headers), allRows);
|
||||
}
|
||||
|
||||
/** 状态列的原始表头名(流式行只带"表头→值"映射,状态值需按表头名取回)。 */
|
||||
private static String statusHeaderName(List<String> headers, int statusCol) {
|
||||
return statusCol >= 0 && statusCol < headers.size() ? headers.get(statusCol) : "";
|
||||
}
|
||||
|
||||
private void hydratePromptFields(List<AppearancePatentParsedRowVo> rows) {
|
||||
if (rows == null || rows.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
Map<String, List<AppearancePatentParsedRowVo>> rowsByBaseId = groupRowsByBaseId.apply(rows);
|
||||
for (List<AppearancePatentParsedRowVo> siblings : rowsByBaseId.values()) {
|
||||
String title = "";
|
||||
String url = "";
|
||||
String sku = "";
|
||||
for (AppearancePatentParsedRowVo sibling : siblings) {
|
||||
title = firstNonBlank.apply(title, sibling.getTitle());
|
||||
url = firstNonBlank.apply(url, sibling.getUrl());
|
||||
sku = firstNonBlank.apply(sku, sibling.getSku());
|
||||
}
|
||||
for (AppearancePatentParsedRowVo sibling : siblings) {
|
||||
if (normalize.apply(sibling.getTitle()).isBlank()) {
|
||||
sibling.setTitle(title);
|
||||
}
|
||||
if (normalize.apply(sibling.getUrl()).isBlank()) {
|
||||
sibling.setUrl(url);
|
||||
}
|
||||
if (normalize.apply(sibling.getSku()).isBlank()) {
|
||||
sibling.setSku(sku);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isAppearanceResultWorkbook(List<String> headers) {
|
||||
return hasHeader(headers, "状态")
|
||||
&& (hasHeader(headers, "结论")
|
||||
|| hasHeader(headers, "标题维度(商标)")
|
||||
|| hasHeader(headers, "外观维度(外观设计专利)")
|
||||
|| hasHeader(headers, "专利维度(发明/实用新型专利)"));
|
||||
}
|
||||
|
||||
private boolean hasHeader(List<String> headers, String candidate) {
|
||||
if (headers == null || headers.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
// 复用 FailedStatusRowFilter.canonicalizeHeader,统一归一化规则,
|
||||
// 避免专利模块自己维护一份只去半角括号的实现导致全角括号表头识别失败。
|
||||
String normalizedCandidate = FailedStatusRowFilter.canonicalizeHeader(candidate);
|
||||
if (normalizedCandidate.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
for (String header : headers) {
|
||||
if (normalizedCandidate.equals(FailedStatusRowFilter.canonicalizeHeader(header))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private String normalizeDisplayId(String id) {
|
||||
return id == null ? "" : id.trim();
|
||||
}
|
||||
|
||||
private void mergeHeaders(List<String> mergedHeaders, List<String> headers) {
|
||||
if (mergedHeaders == null || headers == null || headers.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
Set<String> existing = new LinkedHashSet<>(mergedHeaders);
|
||||
for (String header : headers) {
|
||||
if (existing.add(header)) {
|
||||
mergedHeaders.add(header);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 结果作业({@code AppearancePatentResultJobSupport})与建单共用,服务侧保留薄委托。 */
|
||||
public String buildAggregateScopeKey(List<AppearancePatentSourceFileDto> sourceFiles) {
|
||||
List<String> fileKeys = sourceFiles == null ? List.of() : sourceFiles.stream()
|
||||
.map(AppearancePatentSourceFileDto::getFileKey)
|
||||
.filter(Objects::nonNull)
|
||||
.map(String::trim)
|
||||
.filter(value -> !value.isBlank())
|
||||
.toList();
|
||||
if (fileKeys.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
if (fileKeys.size() == 1) {
|
||||
return fileKeys.get(0);
|
||||
}
|
||||
return "aggregate:" + DigestUtil.sha256Hex(String.join("|", fileKeys));
|
||||
}
|
||||
|
||||
/** 结果作业与建单共用,服务侧保留薄委托。 */
|
||||
public String buildAggregateSourceFilenameLabel(List<AppearancePatentSourceFileDto> sourceFiles) {
|
||||
if (sourceFiles == null || sourceFiles.isEmpty()) {
|
||||
return "appearance-patent";
|
||||
}
|
||||
String firstFilename = sourceFiles.stream()
|
||||
.map(AppearancePatentSourceFileDto::getOriginalFilename)
|
||||
.filter(Objects::nonNull)
|
||||
.map(String::trim)
|
||||
.filter(value -> !value.isBlank())
|
||||
.findFirst()
|
||||
.orElse("appearance-patent");
|
||||
if (sourceFiles.size() == 1) {
|
||||
return firstFilename;
|
||||
}
|
||||
return firstFilename + " 等 " + sourceFiles.size() + " 个文件";
|
||||
}
|
||||
|
||||
private String buildRowToken(String sourceFileKey, Integer rowIndex) {
|
||||
return normalize.apply(sourceFileKey) + "::row::" + (rowIndex == null ? 0 : rowIndex);
|
||||
}
|
||||
|
||||
private static long elapsedMs(long start, long end) {
|
||||
return (end - start) / 1_000_000L;
|
||||
}
|
||||
|
||||
private record ParsedWorkbook(int totalRows, int droppedRows, List<String> headers,
|
||||
List<AppearancePatentParsedRowVo> allRows) {
|
||||
}
|
||||
|
||||
private record ParsedAppearanceRow(AppearancePatentParsedRowVo row, String sourceStatus) {
|
||||
}
|
||||
}
|
||||
+132
@@ -0,0 +1,132 @@
|
||||
package com.nanri.aiimage.modules.appearancepatent.service.support;
|
||||
|
||||
import com.nanri.aiimage.common.task.TaskStatuses;
|
||||
import com.nanri.aiimage.modules.appearancepatent.service.support.AppearancePatentChunkSubmissionSupport.SubmitContext;
|
||||
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
|
||||
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
|
||||
import com.nanri.aiimage.modules.task.model.entity.TaskChunkEntity;
|
||||
import com.nanri.aiimage.modules.task.service.TaskFileJobService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
/**
|
||||
* 外观专利的陈旧任务收尾(A 聚类的收尾一格),从 {@code AppearancePatentTaskService}
|
||||
* <b>原样搬移</b>(3A 拆薄第十三笔):判死收尾、Python 超时恢复探针、封口与 LLM 补提交,
|
||||
* 连同事务边界之外的形状与全部日志文案一字未改。
|
||||
*
|
||||
* <p><b>搬的是收尾编排,不是事务与封口本身。</b>{@code inNewTransaction} 两处包装仍留在服务侧
|
||||
* 以 {@code markSubmissionComplete}/{@code finalizer} 两个回调交入——它们要动的是现网事务边界,
|
||||
* 跟着一起搬只会把「哪个线程在哪个事务里」这句读丢。
|
||||
*/
|
||||
@Slf4j
|
||||
public class AppearancePatentStaleTaskFinalizer {
|
||||
|
||||
private static final String STATUS_RUNNING = TaskStatuses.FileTask.RUNNING;
|
||||
|
||||
private final String moduleType;
|
||||
private final FileTaskMapper fileTaskMapper;
|
||||
private final TaskFileJobService taskFileJobService;
|
||||
private final Function<FileTaskEntity, Integer> rowCounter;
|
||||
private final Predicate<Long> submissionComplete;
|
||||
private final Predicate<Long> persistedRowsPresent;
|
||||
private final Function<Long, Integer> markSubmissionComplete;
|
||||
private final Function<Long, List<TaskChunkEntity>> submittedChunksLoader;
|
||||
private final Function<List<TaskChunkEntity>, Integer> uninspectedRowCounter;
|
||||
private final Consumer<SubmitContext> llmSubmitter;
|
||||
private final Consumer<Long> taskActivityToucher;
|
||||
private final BiConsumer<FileTaskEntity, String> finalizer;
|
||||
|
||||
public AppearancePatentStaleTaskFinalizer(String moduleType,
|
||||
FileTaskMapper fileTaskMapper,
|
||||
TaskFileJobService taskFileJobService,
|
||||
Function<FileTaskEntity, Integer> rowCounter,
|
||||
Predicate<Long> submissionComplete,
|
||||
Predicate<Long> persistedRowsPresent,
|
||||
Function<Long, Integer> markSubmissionComplete,
|
||||
Function<Long, List<TaskChunkEntity>> submittedChunksLoader,
|
||||
Function<List<TaskChunkEntity>, Integer> uninspectedRowCounter,
|
||||
Consumer<SubmitContext> llmSubmitter,
|
||||
Consumer<Long> taskActivityToucher,
|
||||
BiConsumer<FileTaskEntity, String> finalizer) {
|
||||
this.moduleType = moduleType;
|
||||
this.fileTaskMapper = fileTaskMapper;
|
||||
this.taskFileJobService = taskFileJobService;
|
||||
this.rowCounter = rowCounter;
|
||||
this.submissionComplete = submissionComplete;
|
||||
this.persistedRowsPresent = persistedRowsPresent;
|
||||
this.markSubmissionComplete = markSubmissionComplete;
|
||||
this.submittedChunksLoader = submittedChunksLoader;
|
||||
this.uninspectedRowCounter = uninspectedRowCounter;
|
||||
this.llmSubmitter = llmSubmitter;
|
||||
this.taskActivityToucher = taskActivityToucher;
|
||||
this.finalizer = finalizer;
|
||||
}
|
||||
|
||||
/**
|
||||
* stale 判死收尾:事务只包住真正需要原子的两段(封口状态批量更新、任务终态 + 结果 + 组装作业入队),
|
||||
* **LLM 批次留在事务之外**。
|
||||
*
|
||||
* <p>外层调用点曾把整个方法包进 {@code inNewTransaction},于是恢复分支里
|
||||
* {@code submitLlmBatches} 每批开头 {@code touchRunning} 对 biz_task_file_job 取的 X 锁,
|
||||
* 要一直活到串行发完整批 LLM 请求
|
||||
* (线上实测单批 costMs=1077959)之后才释放——两台的卡死自愈扫描 UPDATE 同一行,
|
||||
* 每 110 秒撞一次 50 秒锁等待,还顺手按住一条 Hikari 连接十几分钟、并把已扣过 LLM 次数的状态
|
||||
* 置于可回滚的位置。同源的 {@code SimilarAsinTaskService#finalizeStaleTask} 一直是这个形状。
|
||||
*/
|
||||
public void finalizeStaleTask(Long taskId, String error) {
|
||||
FileTaskEntity task = fileTaskMapper.selectById(taskId);
|
||||
if (task == null || !moduleType.equals(task.getModuleType()) || !STATUS_RUNNING.equals(task.getStatus())) {
|
||||
return;
|
||||
}
|
||||
if (tryRecoverTimedOutPythonTask(task)) {
|
||||
return;
|
||||
}
|
||||
finalizer.accept(task, error);
|
||||
}
|
||||
|
||||
private boolean tryRecoverTimedOutPythonTask(FileTaskEntity task) {
|
||||
if (task == null || task.getId() == null) {
|
||||
return false;
|
||||
}
|
||||
Long taskId = task.getId();
|
||||
boolean uploadComplete = submissionComplete.test(taskId);
|
||||
long activeAssembleJobs = taskFileJobService.countActiveAssembleJobs(taskId, moduleType);
|
||||
log.info("[appearance-patent] stale recovery probe taskId={} uploadComplete={} activeAssembleJobs={} persistedRows={}",
|
||||
taskId, uploadComplete, activeAssembleJobs, persistedRowsPresent.test(taskId));
|
||||
// 已有「重试耗尽且已终态收尾」的 assemble job:说明恢复已经试过、缺失是永久的。
|
||||
// 再重建只会每 30 秒空转一轮,而且恢复过程刷新任务心跳会让任务永远 RUNNING
|
||||
// (线上任务 28459 实测:48 分钟里每隔 30 秒重建一次 job)。返回 false 交给
|
||||
// finalizeStaleTask 按失败收尾,用户看到明确失败而不是无限等待。
|
||||
if (taskFileJobService.hasExhaustedAssembleJob(taskId, moduleType)) {
|
||||
log.warn("[appearance-patent] stale recovery 放弃:已有重试耗尽的 assemble job,按失败收尾 taskId={}", taskId);
|
||||
return false;
|
||||
}
|
||||
if (!persistedRowsPresent.test(taskId)) {
|
||||
log.info("[appearance-patent] stale recovery aborted because no persisted rows taskId={}", taskId);
|
||||
return false;
|
||||
}
|
||||
if (!uploadComplete) {
|
||||
// 封口是多行 scope 状态更新,单独占一个短事务;紧随其后的 LLM 批次不在事务里
|
||||
int forcedScopes = markSubmissionComplete.apply(taskId);
|
||||
if (forcedScopes <= 0) {
|
||||
log.warn("[appearance-patent] stale recovery aborted because submission could not be marked complete taskId={}",
|
||||
taskId);
|
||||
return false;
|
||||
}
|
||||
int pendingRows = uninspectedRowCounter.apply(submittedChunksLoader.apply(taskId));
|
||||
log.warn("[appearance-patent] Python 回传心跳超时,已封口上传并继续检测/文件收尾 taskId={} pendingRows={} activeAssembleJobs={} forcedScopes={}",
|
||||
taskId, pendingRows, activeAssembleJobs, forcedScopes);
|
||||
} else {
|
||||
log.warn("[appearance-patent] Python 超时恢复继续推进检测/文件收尾 taskId={} activeAssembleJobs={}",
|
||||
taskId, activeAssembleJobs);
|
||||
}
|
||||
llmSubmitter.accept(new SubmitContext(task, null, null, 0, true, null));
|
||||
taskActivityToucher.accept(taskId);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
package com.nanri.aiimage.modules.appearancepatent.service.support;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.task.TaskStatuses;
|
||||
import com.nanri.aiimage.common.service.ResultDownloadResolver;
|
||||
import com.nanri.aiimage.modules.appearancepatent.service.AppearancePatentTaskCacheService;
|
||||
import com.nanri.aiimage.modules.task.mapper.FileResultMapper;
|
||||
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
|
||||
import com.nanri.aiimage.modules.task.mapper.TaskChunkMapper;
|
||||
import com.nanri.aiimage.modules.task.mapper.TaskScopeStateMapper;
|
||||
import com.nanri.aiimage.modules.task.model.entity.FileResultEntity;
|
||||
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
|
||||
import com.nanri.aiimage.modules.task.model.entity.TaskChunkEntity;
|
||||
import com.nanri.aiimage.modules.task.model.entity.TaskScopeStateEntity;
|
||||
import com.nanri.aiimage.modules.task.service.TaskFileJobService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
|
||||
/**
|
||||
* 外观专利的任务记录操作(删除、历史、下载与激活校验),从 {@code AppearancePatentTaskService}
|
||||
* <b>原样搬移</b>(3A 拆薄第十三笔):事务注解仍留在服务侧入口(委托调用发生在同一事务内),
|
||||
* 提交后远端载荷删除与缓存清理的顺序、文案一字未改。
|
||||
*/
|
||||
@Slf4j
|
||||
public class AppearancePatentTaskRecordSupport {
|
||||
|
||||
private static final String STATUS_PENDING = TaskStatuses.FileTask.PENDING;
|
||||
private static final String STATUS_RUNNING = TaskStatuses.FileTask.RUNNING;
|
||||
|
||||
private final String moduleType;
|
||||
private final FileTaskMapper fileTaskMapper;
|
||||
private final FileResultMapper fileResultMapper;
|
||||
private final TaskScopeStateMapper taskScopeStateMapper;
|
||||
private final TaskChunkMapper taskChunkMapper;
|
||||
private final TaskFileJobService taskFileJobService;
|
||||
private final AppearancePatentTaskCacheService taskCacheService;
|
||||
private final ResultDownloadResolver resultDownloadResolver;
|
||||
private final Function<Long, List<String>> payloadCollector;
|
||||
private final BiConsumer<List<String>, Long> payloadDeleter;
|
||||
private final Consumer<Runnable> afterCommitRunner;
|
||||
|
||||
public AppearancePatentTaskRecordSupport(String moduleType,
|
||||
FileTaskMapper fileTaskMapper,
|
||||
FileResultMapper fileResultMapper,
|
||||
TaskScopeStateMapper taskScopeStateMapper,
|
||||
TaskChunkMapper taskChunkMapper,
|
||||
TaskFileJobService taskFileJobService,
|
||||
AppearancePatentTaskCacheService taskCacheService,
|
||||
ResultDownloadResolver resultDownloadResolver,
|
||||
Function<Long, List<String>> payloadCollector,
|
||||
BiConsumer<List<String>, Long> payloadDeleter,
|
||||
Consumer<Runnable> afterCommitRunner) {
|
||||
this.moduleType = moduleType;
|
||||
this.fileTaskMapper = fileTaskMapper;
|
||||
this.fileResultMapper = fileResultMapper;
|
||||
this.taskScopeStateMapper = taskScopeStateMapper;
|
||||
this.taskChunkMapper = taskChunkMapper;
|
||||
this.taskFileJobService = taskFileJobService;
|
||||
this.taskCacheService = taskCacheService;
|
||||
this.resultDownloadResolver = resultDownloadResolver;
|
||||
this.payloadCollector = payloadCollector;
|
||||
this.payloadDeleter = payloadDeleter;
|
||||
this.afterCommitRunner = afterCommitRunner;
|
||||
}
|
||||
|
||||
public void activateTask(Long taskId, Long userId) {
|
||||
FileTaskEntity task = fileTaskMapper.selectById(taskId);
|
||||
if (task == null || !moduleType.equals(task.getModuleType()) || !Objects.equals(userId, task.getUserId())) {
|
||||
throw new BusinessException("任务不存在");
|
||||
}
|
||||
// 2026-09-30 起外观专利已整体迁移 Linux 后台执行(无浏览器抓取):
|
||||
// activate 不再把任务推给客户端浏览器。任务保持 PENDING,由内部认领端点
|
||||
// (/api/internal/tasks/pull-pending + maixiang-ap worker)在等待窗口后自动接管。
|
||||
// 这里保留接口仅做状态校验:旧前端(未刷新页面缓存)点「启动」时给出明确提示,
|
||||
// 前端收到业务异常会中止入队逻辑,任务不会被执行两次。
|
||||
if (STATUS_PENDING.equals(task.getStatus())) {
|
||||
log.info("[外观专利] activate 不再推送客户端,任务保持 PENDING 等待 Linux 后台认领 taskId={} userId={}", taskId, userId);
|
||||
throw new BusinessException("外观专利已切换后台自动执行,无需打开浏览器,稍候自动开始");
|
||||
}
|
||||
if (STATUS_RUNNING.equals(task.getStatus())) {
|
||||
throw new BusinessException("任务已在执行中(可能已由后台自动接管),无需重复启动");
|
||||
}
|
||||
throw new BusinessException("任务已结束");
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除任务。
|
||||
*
|
||||
* <p>事务边界:远端载荷删除与缓存清理移到事务提交后执行 —— 单次删除超时 120s、重试 3 次,
|
||||
* 放在 DB 事务里会让连接被长时间占用(项目在 TaskScopePayloadStorageService 已写明该约束)。
|
||||
*/
|
||||
public void deleteTask(Long taskId, Long userId) {
|
||||
FileTaskEntity task = fileTaskMapper.selectById(taskId);
|
||||
if (task == null || !moduleType.equals(task.getModuleType()) || !Objects.equals(userId, task.getUserId())) {
|
||||
throw new BusinessException("任务不存在");
|
||||
}
|
||||
List<String> payloads = payloadCollector.apply(taskId);
|
||||
fileResultMapper.delete(new LambdaQueryWrapper<FileResultEntity>().eq(FileResultEntity::getTaskId, taskId).eq(FileResultEntity::getModuleType, moduleType));
|
||||
taskScopeStateMapper.delete(new LambdaQueryWrapper<TaskScopeStateEntity>().eq(TaskScopeStateEntity::getTaskId, taskId).eq(TaskScopeStateEntity::getModuleType, moduleType));
|
||||
taskChunkMapper.delete(new LambdaQueryWrapper<TaskChunkEntity>().eq(TaskChunkEntity::getTaskId, taskId).eq(TaskChunkEntity::getModuleType, moduleType));
|
||||
// 同步清理 task_file_job,避免被删除任务遗留的 PENDING/FAILED 行被 TaskResultFileJobWorker 反复扫描出 task not found。
|
||||
taskFileJobService.deleteTaskJobs(taskId, moduleType);
|
||||
fileTaskMapper.deleteById(taskId);
|
||||
// 事务提交后再做远端删除与缓存清理
|
||||
payloadDeleter.accept(payloads, taskId);
|
||||
afterCommitRunner.accept(() -> taskCacheService.deleteTaskCache(taskId));
|
||||
}
|
||||
|
||||
public void deleteHistory(Long resultId, Long userId) {
|
||||
FileResultEntity row = fileResultMapper.selectById(resultId);
|
||||
if (row == null || !moduleType.equals(row.getModuleType()) || !Objects.equals(userId, row.getUserId())) {
|
||||
throw new BusinessException("记录不存在");
|
||||
}
|
||||
// 同步清理 task_file_job,避免被删除历史记录残留的 ASSEMBLE_RESULT job 被反复扫描出 result record not found。
|
||||
taskFileJobService.deleteResultJobs(row.getTaskId(), moduleType, resultId);
|
||||
fileResultMapper.deleteById(resultId);
|
||||
}
|
||||
|
||||
public String resolveResultDownloadUrl(Long resultId, Long userId) {
|
||||
// 2026-09 去重:与原实现等价(并修掉 userId.equals 的潜在 NPE),实现收口到 common
|
||||
return resultDownloadResolver.resolveUrl(resultId, userId, moduleType);
|
||||
}
|
||||
|
||||
public String resolveResultDownloadFilename(Long resultId, Long userId) {
|
||||
FileResultEntity row = fileResultMapper.selectById(resultId);
|
||||
if (row == null || !moduleType.equals(row.getModuleType()) || !Objects.equals(userId, row.getUserId())) {
|
||||
throw new BusinessException("记录不存在");
|
||||
}
|
||||
return row.getResultFilename() == null || row.getResultFilename().isBlank()
|
||||
? "appearance-patent-" + resultId + ".xlsx"
|
||||
: row.getResultFilename();
|
||||
}
|
||||
}
|
||||
+151
-18
@@ -22,9 +22,11 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.ThreadFactory;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
@@ -37,12 +39,29 @@ public class BrandCheckClient {
|
||||
/** 品牌检查并发度:避免一次批量检查把第三方服务打满。 */
|
||||
private static final int BRAND_CHECK_CONCURRENCY = 3;
|
||||
|
||||
/** 检查队列容量:有界防 OOM;满员时提交方立即降级,不再回落到调用线程执行。 */
|
||||
private static final int BRAND_CHECK_QUEUE_CAPACITY = 1000;
|
||||
|
||||
/**
|
||||
* 预算用尽后,尚未开始的检查最多再等这么久去拿首轮机会。
|
||||
* 超过即取消并转补测:排队等待必须有上界,否则慢上游会把同步回传线程拖到分钟级。
|
||||
*/
|
||||
private static final long FIRST_ATTEMPT_QUEUE_GRACE_MILLIS = 1_000L;
|
||||
|
||||
private static final String REASON_QUEUE_TIMEOUT = "品牌检查排队超预算";
|
||||
private static final String REASON_QUEUE_FULL = "品牌检查队列已满";
|
||||
private static final String REASON_RESPONSE_TIMEOUT = "品牌检查响应超时";
|
||||
private static final String REASON_INTERRUPTED = "品牌检查被中断";
|
||||
private static final String REASON_UNEXPECTED_FAILURE = "品牌检查异常";
|
||||
|
||||
/** 用户没配代理时交回的原因文案;采集侧与补测队列都按它把行判查询失败。 */
|
||||
public static final String NO_PROXY_REASON = "用户未配置代理";
|
||||
|
||||
private final BrandCheckProperties properties;
|
||||
private final com.nanri.aiimage.metrics.ExternalCallMetricsRecorder externalCallMetrics;
|
||||
private final UserApiSecretService userApiSecretService;
|
||||
/** 提交线程上的拒绝标记:队列满时由拒绝策略置位,提交方据此立即降级(不新增 catch 出口)。 */
|
||||
private final ThreadLocal<AtomicBoolean> rejectedSubmission = new ThreadLocal<>();
|
||||
private volatile RestClient sharedRestClient;
|
||||
|
||||
public BrandCheckClient(BrandCheckProperties properties,
|
||||
@@ -53,14 +72,21 @@ public class BrandCheckClient {
|
||||
this.userApiSecretService = userApiSecretService;
|
||||
}
|
||||
|
||||
// 有界队列 + CallerRuns:大批量(几千品牌)检查时队列洪峰不无界堆内存,
|
||||
// 队列打满时提交线程自己执行一个检查任务,上游天然限速。
|
||||
// 有界队列 + 拒绝即降级:大批量(几千品牌)检查时队列洪峰不无界堆内存。
|
||||
// 队列满时绝不能回退到 CallerRuns——那会让 Tomcat 回传/心跳线程替上游跑完整条重试阶梯,
|
||||
// 正是 2026-10-20 分片回传被拖到 20 分钟的直接成因。拒绝策略只置位提交标记,由提交方
|
||||
// 换成「查询失败」结果转补测;不抛异常,也不在调用线程执行。
|
||||
private final ExecutorService checkExecutor = new java.util.concurrent.ThreadPoolExecutor(
|
||||
BRAND_CHECK_CONCURRENCY, BRAND_CHECK_CONCURRENCY,
|
||||
60L, java.util.concurrent.TimeUnit.SECONDS,
|
||||
new java.util.concurrent.LinkedBlockingQueue<>(1000),
|
||||
new java.util.concurrent.LinkedBlockingQueue<>(BRAND_CHECK_QUEUE_CAPACITY),
|
||||
namedThreadFactory("brand-check"),
|
||||
new java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy());
|
||||
(task, executor) -> {
|
||||
AtomicBoolean rejected = rejectedSubmission.get();
|
||||
if (rejected != null) {
|
||||
rejected.set(true);
|
||||
}
|
||||
});
|
||||
|
||||
@PreDestroy
|
||||
void shutdownCheckExecutor() {
|
||||
@@ -132,8 +158,9 @@ public class BrandCheckClient {
|
||||
}
|
||||
|
||||
/**
|
||||
* 调用方自带整批耗时预算(毫秒,{@code <= 0} 表示不限制):预算只掐「重试」,
|
||||
* 每个品牌的首轮请求始终执行,所以上游只是慢而不是坏时不会因此丢结论。
|
||||
* 调用方自带整批耗时预算(毫秒,{@code <= 0} 表示不限制):预算内等结果,用尽后不再重试;
|
||||
* 尚未开始的品牌再给 1 秒排队宽限拿首轮机会,仍排不上队就按查询失败转补测。
|
||||
* 排队时间也计入上界——否则慢上游会把同步回传线程拖到分钟级。
|
||||
*
|
||||
* <p>分片回传用它把一次 POST 的等待上界收到几秒:{@code total-timeout-millis} 那 90 秒
|
||||
* 是给后台批量任务(外观合批、品牌补测调度)的预算,同步等响应的桌面客户端不该替它扛
|
||||
@@ -223,17 +250,42 @@ public class BrandCheckClient {
|
||||
}
|
||||
return outcomes;
|
||||
}
|
||||
long firstAttemptDeadlineNanos = deadlineNanos == Long.MAX_VALUE
|
||||
? Long.MAX_VALUE
|
||||
: deadlineNanos + FIRST_ATTEMPT_QUEUE_GRACE_MILLIS * 1_000_000L;
|
||||
List<CompletableFuture<BrandCheckOutcome>> futures = new ArrayList<>(brands.size());
|
||||
List<AtomicBoolean> startedFlags = new ArrayList<>(brands.size());
|
||||
// 一次批量一份判定:本批里只要有一个品牌跑满阶梯仍被判查询失败,其余品牌就不再
|
||||
// 各自烧完整条重试阶梯(见 checkOneBrand 的短路分支)。
|
||||
AtomicBoolean upstreamRejecting = new AtomicBoolean(false);
|
||||
for (String brand : brands) {
|
||||
futures.add(CompletableFuture.supplyAsync(
|
||||
() -> checkOneBrand(brand, strategy, deadlineNanos, upstreamRejecting, proxyUrl, userId),
|
||||
checkExecutor));
|
||||
AtomicBoolean started = new AtomicBoolean(false);
|
||||
AtomicBoolean rejected = new AtomicBoolean(false);
|
||||
rejectedSubmission.set(rejected);
|
||||
CompletableFuture<BrandCheckOutcome> future;
|
||||
try {
|
||||
future = CompletableFuture.supplyAsync(
|
||||
() -> {
|
||||
started.set(true);
|
||||
return checkOneBrand(brand, strategy, deadlineNanos, upstreamRejecting, proxyUrl, userId);
|
||||
},
|
||||
checkExecutor);
|
||||
} finally {
|
||||
rejectedSubmission.remove();
|
||||
}
|
||||
if (rejected.get()) {
|
||||
// 队列满:立刻降级,不许在调用线程(Tomcat 回传/心跳线程)里同步跑检查。
|
||||
future.cancel(false);
|
||||
log.warn("[brand-check] 检查队列已满,按查询失败转补测 brand={} capacity={}",
|
||||
brand, BRAND_CHECK_QUEUE_CAPACITY);
|
||||
future = CompletableFuture.completedFuture(queryFailedOutcome(brand, REASON_QUEUE_FULL));
|
||||
}
|
||||
futures.add(future);
|
||||
startedFlags.add(started);
|
||||
}
|
||||
for (int index = 0; index < brands.size(); index++) {
|
||||
outcomes.put(brands.get(index), awaitOutcome(futures.get(index)));
|
||||
outcomes.put(brands.get(index), awaitOutcome(brands.get(index), futures.get(index),
|
||||
startedFlags.get(index), deadlineNanos, firstAttemptDeadlineNanos));
|
||||
}
|
||||
return outcomes;
|
||||
}
|
||||
@@ -347,16 +399,97 @@ public class BrandCheckClient {
|
||||
}
|
||||
}
|
||||
|
||||
private BrandCheckOutcome awaitOutcome(CompletableFuture<BrandCheckOutcome> future) {
|
||||
try {
|
||||
return future.join();
|
||||
} catch (CompletionException ex) {
|
||||
log.warn("[brand-check] unexpected batch failure err={}",
|
||||
ex.getCause() == null ? ex.getMessage() : String.valueOf(ex.getCause().getMessage()));
|
||||
return new BrandCheckOutcome(List.of(), List.of(), "");
|
||||
/**
|
||||
* 等一个品牌检查结果:预算内等完成;预算用尽后只给尚未开始的检查一个短暂的首轮宽限,
|
||||
* 仍排不上队就取消并按查询失败转补测。已在执行的请求最多再等一次读超时。
|
||||
*
|
||||
* <p>原实现用 {@code join()} 无限等队列:上游 16890 卡死时 3 个检查线程被慢请求占满,
|
||||
* 后续分片回传全排在 1000 深的队列里 join,实测一次 chunk 被拖到 1284 秒;客户端
|
||||
* 180 秒超时后 5 次重试耗尽,任务被判「中间分批回传失败」,同批心跳也一起被拖住。
|
||||
*/
|
||||
private BrandCheckOutcome awaitOutcome(String brand,
|
||||
CompletableFuture<BrandCheckOutcome> future,
|
||||
AtomicBoolean started,
|
||||
long deadlineNanos,
|
||||
long firstAttemptDeadlineNanos) {
|
||||
// 0=预算内等待 1=排队宽限 2=取消或放行 3=等读超时 4=不限预算(旧行为)
|
||||
int stage = deadlineNanos == Long.MAX_VALUE ? 4 : 0;
|
||||
while (true) {
|
||||
try {
|
||||
switch (stage) {
|
||||
case 4:
|
||||
return future.get();
|
||||
case 0: {
|
||||
long budgetWait = deadlineNanos - System.nanoTime();
|
||||
if (budgetWait > 0L) {
|
||||
return future.get(budgetWait, TimeUnit.NANOSECONDS);
|
||||
}
|
||||
stage = 1;
|
||||
break;
|
||||
}
|
||||
case 1: {
|
||||
if (future.isDone()) {
|
||||
return future.get();
|
||||
}
|
||||
long graceWait = firstAttemptDeadlineNanos - System.nanoTime();
|
||||
if (graceWait > 0L) {
|
||||
return future.get(graceWait, TimeUnit.NANOSECONDS);
|
||||
}
|
||||
stage = 2;
|
||||
break;
|
||||
}
|
||||
case 2: {
|
||||
if (!started.get() && future.cancel(false)) {
|
||||
log.warn("[brand-check] 排队超过预算+{}ms 宽限,取消未开始的检查并转补测 brand={}",
|
||||
FIRST_ATTEMPT_QUEUE_GRACE_MILLIS, brand);
|
||||
return queryFailedOutcome(brand, REASON_QUEUE_TIMEOUT);
|
||||
}
|
||||
stage = 3;
|
||||
break;
|
||||
}
|
||||
case 3: {
|
||||
long readWait = Math.max(1L, properties.getReadTimeoutMillis()) * 1_000_000L;
|
||||
return future.get(readWait, TimeUnit.NANOSECONDS);
|
||||
}
|
||||
default:
|
||||
return queryFailedOutcome(brand, REASON_UNEXPECTED_FAILURE);
|
||||
}
|
||||
} catch (Exception failure) {
|
||||
if (failure instanceof TimeoutException) {
|
||||
if (stage == 0) {
|
||||
stage = 1;
|
||||
continue;
|
||||
}
|
||||
if (stage == 1) {
|
||||
stage = 2;
|
||||
continue;
|
||||
}
|
||||
if (stage == 3) {
|
||||
future.cancel(true);
|
||||
log.warn("[brand-check] 检查已开始但超过读超时仍未返回,取消并转补测 brand={}",
|
||||
brand);
|
||||
return queryFailedOutcome(brand, REASON_RESPONSE_TIMEOUT);
|
||||
}
|
||||
}
|
||||
if (failure instanceof InterruptedException) {
|
||||
Thread.currentThread().interrupt();
|
||||
future.cancel(true);
|
||||
log.warn("[brand-check] 等待检查结果被中断,按查询失败转补测 brand={}", brand);
|
||||
return queryFailedOutcome(brand, REASON_INTERRUPTED);
|
||||
}
|
||||
// 检查线程异常退出不能当成「品牌没问题」:旧实现返回空结论,调用方会把该品牌放行。
|
||||
Throwable cause = failure instanceof ExecutionException && failure.getCause() != null
|
||||
? failure.getCause() : failure;
|
||||
log.warn("[brand-check] 批量检查异常,按查询失败转补测 brand={} err={}", brand, cause.getMessage());
|
||||
return queryFailedOutcome(brand, REASON_UNEXPECTED_FAILURE);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private BrandCheckOutcome queryFailedOutcome(String brand, String reason) {
|
||||
return new BrandCheckOutcome(List.of(), List.of(brand), reason);
|
||||
}
|
||||
|
||||
/**
|
||||
* 单个品牌的结论。
|
||||
*
|
||||
|
||||
+13
@@ -49,6 +49,7 @@ import com.nanri.aiimage.modules.similarasin.service.support.SimilarAsinPayloadS
|
||||
import com.nanri.aiimage.modules.similarasin.service.support.SimilarAsinPoisonTracker;
|
||||
import com.nanri.aiimage.modules.similarasin.service.support.SimilarAsinResultTextSupport;
|
||||
import com.nanri.aiimage.modules.similarasin.service.support.SimilarAsinResultWorkbookAssembler;
|
||||
import com.nanri.aiimage.modules.similarasin.service.support.SimilarAsinStaleReopenSupport;
|
||||
import com.nanri.aiimage.modules.similarasin.service.support.SimilarAsinTaskProgressSupport;
|
||||
import com.nanri.aiimage.modules.similarasin.service.support.SimilarAsinTaskOwnershipSupport;
|
||||
import com.nanri.aiimage.modules.similarasin.util.SimilarAsinImageEmbedder;
|
||||
@@ -754,6 +755,7 @@ public class SimilarAsinTaskService implements SimilarAsinPipelineHost {
|
||||
if (request == null) {
|
||||
throw new BusinessException("结果请求不能为空");
|
||||
}
|
||||
staleReopenSupport().reopenIfStaleFailed(taskId);
|
||||
PreparedSubmittedChunk prepared = pipelineSupport().prepareSubmittedChunk(taskId, request);
|
||||
PersistSubmittedChunkResult persisted = transactionManager == null
|
||||
? pipelineSupport().persistSubmittedChunk(prepared)
|
||||
@@ -769,10 +771,21 @@ public class SimilarAsinTaskService implements SimilarAsinPipelineHost {
|
||||
taskCacheService.touchTaskHeartbeat(taskId);
|
||||
} else {
|
||||
applyFinalizeSideEffects(persisted.finalizeResult());
|
||||
// 中间分片重开后任务已是 RUNNING,finalize 时不能再靠「本次是否重开」判断;
|
||||
// terminal=false 才是「收尾后等组装」,此时才需要复位判死时一起失败的组装 job。
|
||||
if (!persisted.finalizeResult().terminal()) {
|
||||
staleReopenSupport().recoverTerminalFailedAssemble(taskId);
|
||||
}
|
||||
}
|
||||
pipelineSupport().scheduleLlmPipelineForSubmittedChunk(context);
|
||||
}
|
||||
|
||||
/** 迟到回传恢复:心跳/回传停滞判死任务的重开与组装 job 复位。 */
|
||||
private SimilarAsinStaleReopenSupport staleReopenSupport() {
|
||||
return new SimilarAsinStaleReopenSupport(
|
||||
fileTaskMapper, fileResultMapper, taskFileJobService, taskCacheService, ownershipSupport());
|
||||
}
|
||||
|
||||
public void deleteTask(Long taskId, Long userId) {
|
||||
List<String> payloads;
|
||||
try (TaskDistributedLockService.LockHandle ignored = ownershipSupport().requireTaskLock(taskId, TASK_LOCK_WAIT_MILLIS)) {
|
||||
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
package com.nanri.aiimage.modules.similarasin.service.support;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.nanri.aiimage.common.task.TaskStatuses;
|
||||
import com.nanri.aiimage.modules.similarasin.service.SimilarAsinTaskCacheService;
|
||||
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.TaskFileJobService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* SimilarAsinTaskService 拆分:心跳/回传停滞判死的迟到回传恢复。
|
||||
* <p>
|
||||
* 判死巡检只改 {@code biz_file_task},客户端并不知道;它继续补发时旧逻辑按终态回 40901,
|
||||
* 客户端收到 {@code success=true} 即删本地副本,任务已采集的数据整批丢掉(生产 31577/31472)。
|
||||
* 这里只重开归因于客户端停滞的判死文案、24 小时内、owner 为本实例的记录;业务性失败
|
||||
* (如结果文件生成失败)与 SUCCESS 仍按终态拒绝。
|
||||
*/
|
||||
@Slf4j
|
||||
public class SimilarAsinStaleReopenSupport {
|
||||
|
||||
private static final String MODULE_TYPE = "SIMILAR_ASIN";
|
||||
private static final List<String> STALE_FAILURE_MARKERS = List.of(
|
||||
"任务心跳超时,已自动失败",
|
||||
"长时间未收到 Python 心跳,任务已自动失败",
|
||||
"客户端未回传任何检测结果",
|
||||
"客户端回传中断",
|
||||
"任务创建至今超过",
|
||||
"Python heartbeat alive but no result chunk uploaded");
|
||||
private static final Duration REOPEN_WINDOW = Duration.ofHours(24);
|
||||
|
||||
private final FileTaskMapper fileTaskMapper;
|
||||
private final FileResultMapper fileResultMapper;
|
||||
private final TaskFileJobService taskFileJobService;
|
||||
private final SimilarAsinTaskCacheService taskCacheService;
|
||||
private final SimilarAsinTaskOwnershipSupport ownershipSupport;
|
||||
|
||||
public SimilarAsinStaleReopenSupport(FileTaskMapper fileTaskMapper,
|
||||
FileResultMapper fileResultMapper,
|
||||
TaskFileJobService taskFileJobService,
|
||||
SimilarAsinTaskCacheService taskCacheService,
|
||||
SimilarAsinTaskOwnershipSupport ownershipSupport) {
|
||||
this.fileTaskMapper = fileTaskMapper;
|
||||
this.fileResultMapper = fileResultMapper;
|
||||
this.taskFileJobService = taskFileJobService;
|
||||
this.taskCacheService = taskCacheService;
|
||||
this.ownershipSupport = ownershipSupport;
|
||||
}
|
||||
|
||||
/**
|
||||
* 被心跳/回传超时判死(含首心跳宽限)的任务收到客户端迟到分片时先重开,再走正常落库。
|
||||
*/
|
||||
public void reopenIfStaleFailed(Long taskId) {
|
||||
FileTaskEntity task = fileTaskMapper.selectById(taskId);
|
||||
if (task == null || !MODULE_TYPE.equals(task.getModuleType())
|
||||
|| !TaskStatuses.FileTask.FAILED.equals(task.getStatus())) {
|
||||
return;
|
||||
}
|
||||
if (!isStaleFailure(task.getErrorMessage())) {
|
||||
return;
|
||||
}
|
||||
String reason = task.getErrorMessage();
|
||||
LocalDateTime anchor = task.getFinishedAt() == null ? task.getUpdatedAt() : task.getFinishedAt();
|
||||
if (anchor == null || anchor.isBefore(LocalDateTime.now().minus(REOPEN_WINDOW))) {
|
||||
return;
|
||||
}
|
||||
if (!ownershipSupport.isOwnerCurrent(ownershipSupport.ownerFromTask(task))) {
|
||||
return;
|
||||
}
|
||||
int updated = fileTaskMapper.update(null, new LambdaUpdateWrapper<FileTaskEntity>()
|
||||
.eq(FileTaskEntity::getId, taskId)
|
||||
.eq(FileTaskEntity::getStatus, TaskStatuses.FileTask.FAILED)
|
||||
.eq(FileTaskEntity::getErrorMessage, reason)
|
||||
.set(FileTaskEntity::getStatus, TaskStatuses.FileTask.RUNNING)
|
||||
.set(FileTaskEntity::getErrorMessage, null)
|
||||
.set(FileTaskEntity::getFinishedAt, null)
|
||||
.set(FileTaskEntity::getSuccessFileCount, 0)
|
||||
.set(FileTaskEntity::getFailedFileCount, 0)
|
||||
.set(FileTaskEntity::getUpdatedAt, LocalDateTime.now()));
|
||||
if (updated == 1) {
|
||||
taskCacheService.deleteTaskCache(taskId);
|
||||
log.warn("[similar-asin] 迟到结果回传,重开心跳/回传超时终止的任务 taskId={} reason={}",
|
||||
taskId, reason);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 判死巡检会把在跑的组装 job 一起写成 FAILED + retryCount=max(见
|
||||
* {@code StaleTaskRepairService.markDeadDownstream})。底座对重试耗尽的 job 不会自动重排,
|
||||
* 迟到回传重开后若不复位,任务会永远挂在 RUNNING 等一个不会跑的组装。
|
||||
* {@code resetTerminalFailedForRecovery} 自带「非终态失败不动作」守卫,重复调用安全。
|
||||
*/
|
||||
public void recoverTerminalFailedAssemble(Long taskId) {
|
||||
List<FileResultEntity> results = fileResultMapper.selectList(new LambdaQueryWrapper<FileResultEntity>()
|
||||
.eq(FileResultEntity::getTaskId, taskId)
|
||||
.eq(FileResultEntity::getModuleType, MODULE_TYPE)
|
||||
.last("limit 1"));
|
||||
if (results == null || results.isEmpty() || results.getFirst().getId() == null) {
|
||||
return;
|
||||
}
|
||||
taskFileJobService.resetTerminalFailedForRecovery(taskId, MODULE_TYPE, results.getFirst().getId());
|
||||
}
|
||||
|
||||
private boolean isStaleFailure(String errorMessage) {
|
||||
if (errorMessage == null || errorMessage.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
for (String marker : STALE_FAILURE_MARKERS) {
|
||||
if (errorMessage.contains(marker)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
+6
-3
@@ -24,7 +24,8 @@ import org.junit.jupiter.api.Test;
|
||||
* 类注释里还点名留了三处非同构变体(PriceTrack 要求缓存行 requestJson 非空、ShopMatch 带新旧复活防护、
|
||||
* Withdraw 先按 limit(50) 归一化 id)。剩下的重复不是行,是<b>同一条安全谓词被手抄的遍数</b>:
|
||||
* 「这一行是不是这个模块的」{@code !MODULE_TYPE.equals(x.getModuleType())} 在 <b>16</b> 个文件里写了
|
||||
* <b>130</b> 遍。第 3 项那个超管判定是同一缺陷的小一号版本(19 遍),那个已经收口成出口,这个还没有。</p>
|
||||
* <b>130</b> 遍(2026-10-21 实测 <b>15</b> 个文件 / <b>108</b> 遍:AppearancePatentTaskService 最后一处
|
||||
* 随 3A 拆薄第十三笔退场,新件走构造入参 moduleType,不在本尺的记名面内)。第 3 项那个超管判定是同一缺陷的小一号版本(19 遍),那个已经收口成出口,这个还没有。</p>
|
||||
*
|
||||
* <p>抄本身不是 bug,<b>改不动</b>才是:归属谓词漏一处的表现是某一页的检查静默变成"谁都能读",
|
||||
* 不报错、不 403。今天动它要一次改到 16 个文件,代价太大,所以这里先把<b>遍数钉成棘轮</b>:
|
||||
@@ -48,8 +49,10 @@ class TaskLifecycleDebtRatchetTest {
|
||||
files.add(file.getFileName().toString());
|
||||
}
|
||||
}
|
||||
// 自检:分母本身要说得出数("扫到 16 个文件"与"扫描坏了返回空"是两种红法,别混)
|
||||
assertThat(files).as("手写模块归属谓词的文件数").hasSize(16);
|
||||
// 自检:分母本身要说得出数("扫到 15 个文件"与"扫描坏了返回空"是两种红法,别混)。
|
||||
// 16→15 是 3A 拆薄第十三笔的真下降:AppearancePatentTaskService 最后一处手写归属
|
||||
// 随任务记录/陈旧收尾出件退场(新件用构造入参 moduleType,主件走底座覆写),不是放宽阈值。
|
||||
assertThat(files).as("手写模块归属谓词的文件数").hasSize(15);
|
||||
// 自检:锚点必须真抓得到这一形,否则上一条与下面那条棘轮都是恒绿
|
||||
assertThat(count("if (task == null || !MODULE_TYPE.equals(task.getModuleType())) {", MODULE_OWNERSHIP))
|
||||
.as("锚点自检:这一形抓不到,棘轮等于没写").isEqualTo(1);
|
||||
|
||||
+69
@@ -4,12 +4,16 @@ import com.nanri.aiimage.config.BrandCheckProperties;
|
||||
import com.nanri.aiimage.modules.usersecret.service.UserApiSecretService;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
@@ -260,6 +264,71 @@ class BrandCheckClientTest {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 回归:品牌检查共享池被慢请求占满时,排队中的检查不得把同步回传线程拖到预算之外。
|
||||
*
|
||||
* <p>2026-10-20 现网:16890 超时后 3 个检查线程被慢请求占住,后续分片回传在
|
||||
* {@code future.join()} 上等队列,品牌检测耗时从 447 秒一路涨到 2131 秒;客户端
|
||||
* 180 秒超时、5 次重试耗尽后报「中间分批回传失败」,同批心跳请求也被回传线程拖住。
|
||||
* 契约:排队等待必须有上界;预算用尽且仍未开始的检查取消后按「查询失败」返回,
|
||||
* 由补测队列接手,而不是让 Tomcat 线程分钟级挂着等。
|
||||
*/
|
||||
@Test
|
||||
void saturatedCheckPoolDoesNotHoldCallerBeyondBatchBudget() throws Exception {
|
||||
BrandCheckProperties props = new BrandCheckProperties();
|
||||
// 绝不指向生产 16890:即使回归用例失败,也不允许打出真实请求。
|
||||
props.setBaseUrl("http://127.0.0.1:1");
|
||||
props.setPath("/brand_check");
|
||||
props.setRetryTimes(1);
|
||||
props.setRetryIntervalMillis(1);
|
||||
props.setReadTimeoutMillis(1_000);
|
||||
props.setTotalTimeoutMillis(0);
|
||||
BrandCheckClient client = new BrandCheckClient(props, null, stubbedUserSecrets());
|
||||
|
||||
ExecutorService pool = (ExecutorService) ReflectionTestUtils.getField(client, "checkExecutor");
|
||||
CountDownLatch occupied = new CountDownLatch(3);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
Thread releaser = new Thread(() -> {
|
||||
try {
|
||||
Thread.sleep(3_000);
|
||||
} catch (InterruptedException ex) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
release.countDown();
|
||||
}, "brand-check-regression-releaser");
|
||||
releaser.setDaemon(true);
|
||||
try {
|
||||
for (int i = 0; i < 3; i++) {
|
||||
pool.submit(() -> {
|
||||
occupied.countDown();
|
||||
try {
|
||||
release.await();
|
||||
} catch (InterruptedException ex) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
});
|
||||
}
|
||||
assertThat(occupied.await(2, TimeUnit.SECONDS)).as("3 个品牌检查线程应被占满").isTrue();
|
||||
|
||||
releaser.start();
|
||||
long startedAt = System.nanoTime();
|
||||
BrandCheckClient.BrandCheckBatchResult result =
|
||||
client.checkAll(List.of("queued-brand"), "Terms", 200L, 7L);
|
||||
long elapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startedAt);
|
||||
|
||||
assertThat(elapsedMillis)
|
||||
.as("排队等待必须计入整批预算,不能跟着慢请求一起被拖到分钟级")
|
||||
.isLessThan(2_000L);
|
||||
assertThat(result.queryFaildData())
|
||||
.as("没轮到的品牌按查询失败返回,交给补测队列而不是静默放行")
|
||||
.contains("queued-brand");
|
||||
assertThat(result.reason()).as("失败原因要能看出是排队超预算").contains("排队");
|
||||
} finally {
|
||||
release.countDown();
|
||||
pool.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
||||
private HttpServer startBrandCheckServer(com.sun.net.httpserver.HttpHandler handler) throws IOException {
|
||||
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
server.createContext("/brand_check", handler);
|
||||
|
||||
+88
@@ -45,6 +45,7 @@ import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
||||
import org.apache.ibatis.builder.MapperBuilderAssistant;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
@@ -274,6 +275,93 @@ class SimilarAsinTaskServiceSubmitTest {
|
||||
anyString(), anyLong(), anyString(), any(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void lateResultReopensStaleFailedTaskInsteadOfDroppingIt() throws Exception {
|
||||
// 生产 31577/31472:心跳超时判死后客户端继续补发,旧逻辑回 40901,客户端删本地副本,
|
||||
// 已采数据整批丢失。迟到分片到达时应先把任务拉回 RUNNING,再正常落库。
|
||||
FileTaskEntity task = runningTask("instance-a");
|
||||
task.setStatus("FAILED");
|
||||
task.setErrorMessage("任务心跳超时,已自动失败");
|
||||
task.setFinishedAt(LocalDateTime.now().minusMinutes(30));
|
||||
task.setFailedFileCount(1);
|
||||
AtomicBoolean reopened = new AtomicBoolean();
|
||||
when(fileTaskMapper.selectById(TASK_ID)).thenReturn(task);
|
||||
when(fileTaskMapper.update(any(), any())).thenAnswer(invocation -> {
|
||||
reopened.set(true);
|
||||
task.setStatus("RUNNING");
|
||||
task.setErrorMessage(null);
|
||||
task.setFinishedAt(null);
|
||||
return 1;
|
||||
});
|
||||
configureNewChunkAndScope();
|
||||
configureChunkStore(false);
|
||||
when(taskChunkMapper.selectCount(any())).thenReturn(1L);
|
||||
|
||||
service.submitResult(TASK_ID, request(false));
|
||||
|
||||
assertTrue(reopened.get(), "心跳超时判死的任务收到迟到分片必须先重开,而不是 40901 丢数据");
|
||||
assertEquals("RUNNING", task.getStatus());
|
||||
verify(taskCacheService).touchTaskHeartbeat(TASK_ID);
|
||||
}
|
||||
|
||||
@Test
|
||||
void lateFinalResultResetsTerminalFailedAssembleJob() throws Exception {
|
||||
// 判死巡检把组装 job 一起写成 FAILED+retryCount=max;迟到 done 重开后若不复位,
|
||||
// finalizeTask 只把任务挂回 RUNNING,组装永远不会再跑。31577/31472 正是这个形状。
|
||||
FileTaskEntity task = runningTask("instance-a");
|
||||
task.setStatus("FAILED");
|
||||
task.setErrorMessage("任务心跳超时,已自动失败");
|
||||
task.setFinishedAt(LocalDateTime.now().minusMinutes(30));
|
||||
when(fileTaskMapper.selectById(TASK_ID)).thenReturn(task);
|
||||
when(fileTaskMapper.update(any(), any())).thenAnswer(invocation -> {
|
||||
task.setStatus("RUNNING");
|
||||
task.setErrorMessage(null);
|
||||
task.setFinishedAt(null);
|
||||
return 1;
|
||||
});
|
||||
configureNewChunkAndScope();
|
||||
when(taskChunkMapper.selectCount(any())).thenReturn(1L);
|
||||
when(transientPayloadStorageService.storeChunkPayloadVersioned(
|
||||
eq(SimilarAsinTaskService.MODULE_TYPE), eq(TASK_ID), anyString(), eq(0), anyString()))
|
||||
.thenReturn(STORED_CHUNK_POINTER);
|
||||
when(transientPayloadStorageService.wasLastStoreLocalFallback()).thenReturn(false);
|
||||
String parsedPayload = parsedPayloadJson(List.of(new SimilarAsinParsedRowVo()));
|
||||
when(transientPayloadStorageService.resolvePayload(eq(PARSED_POINTER), anyString()))
|
||||
.thenReturn(parsedPayload);
|
||||
FileResultEntity result = new FileResultEntity();
|
||||
result.setId(501L);
|
||||
result.setTaskId(TASK_ID);
|
||||
result.setModuleType(SimilarAsinTaskService.MODULE_TYPE);
|
||||
result.setSourceFilename("germany.xlsx");
|
||||
when(fileResultMapper.selectList(any())).thenReturn(List.of(result));
|
||||
|
||||
// 先来一个中间分片:任务在这里被重开;随后 done 到达时状态已是 RUNNING,
|
||||
// 不能再用「本次请求是否发生重开」决定要不要复位组装 job。
|
||||
service.submitResult(TASK_ID, request(false));
|
||||
assertEquals("RUNNING", task.getStatus(), "中间分片应先把判死任务重开");
|
||||
|
||||
service.submitResult(TASK_ID, request(true));
|
||||
|
||||
assertEquals("RUNNING", task.getStatus(), "迟到 done 收尾后应进入等待组装态");
|
||||
verify(taskFileJobService).resetTerminalFailedForRecovery(
|
||||
TASK_ID, SimilarAsinTaskService.MODULE_TYPE, 501L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void businessFailedTaskStillRejectsLateResultWithTerminalCode() throws Exception {
|
||||
// 只有客户端停滞类判死可重开;结果文件生成失败等业务失败仍按终态收口。
|
||||
FileTaskEntity task = runningTask("instance-a");
|
||||
task.setStatus("FAILED");
|
||||
task.setErrorMessage("相似ASIN结果文件生成失败");
|
||||
task.setFinishedAt(LocalDateTime.now().minusMinutes(30));
|
||||
when(fileTaskMapper.selectById(TASK_ID)).thenReturn(task);
|
||||
|
||||
BusinessException ex = assertThrows(BusinessException.class,
|
||||
() -> service.submitResult(TASK_ID, request(false)));
|
||||
assertEquals(BusinessCodes.TASK_ALREADY_FINISHED, ex.getCode());
|
||||
verify(fileTaskMapper, never()).update(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void submitResultOnFinishedTaskIsRejectedWithTerminalCode() throws Exception {
|
||||
// 真终态被拒必须带 40901:异常处理器对它幂等回 success=true,客户端据此删本地副本、停止补发。
|
||||
|
||||
@@ -266,13 +266,13 @@ class SourceScanTest {
|
||||
// ---------------------------------------------------------------- N6 moduleSources
|
||||
|
||||
@Test
|
||||
void moduleSources_appearancepatent返回38支含拆分后的support件() {
|
||||
void moduleSources_appearancepatent返回44支含拆分后的support件() {
|
||||
List<Path> files = SourceScan.moduleSources("modules/appearancepatent");
|
||||
|
||||
assertThat(files)
|
||||
.as("真实集成:对真仓目录求值。38 支=1 controller+1 client+1 service 主件+3 spi/cache+"
|
||||
+ "15 service/support+16 model(dto7/vo9),与 find 实测同号")
|
||||
.hasSize(38);
|
||||
.as("真实集成:对真仓目录求值。44 支=1 controller+1 client+1 service 主件+3 spi/cache+"
|
||||
+ "21 service/support+16 model(dto7/vo9),与 find 实测同号(3A 拆薄第十三笔再落 5 支)")
|
||||
.hasSize(44);
|
||||
assertThat(files.stream().map(p -> p.toString().replace('\\', '/')).toList())
|
||||
.as("support 目录里的既有件必须在面里——聚合入口存在的理由就是拆分后的新文件要自动被看到")
|
||||
.anyMatch(rel -> rel.endsWith("service/support/AppearancePatentRowNormalizer.java"));
|
||||
@@ -366,18 +366,18 @@ class SourceScanTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void recursive_包含service_support下的既有15件() {
|
||||
void recursive_包含service_support下的既有21件() {
|
||||
List<String> support = SourceScan.moduleSources("modules/appearancepatent").stream()
|
||||
.map(p -> p.toString().replace('\\', '/'))
|
||||
.filter(rel -> rel.contains("/service/support/"))
|
||||
.toList();
|
||||
|
||||
assertThat(support)
|
||||
.as("真实集成:对真仓 modules/appearancepatent/service/support 求值,实测 15 支(3A 拆薄把归属谓词、陈旧扫描、结果打包、LLM 批管线、载荷读写、结果行读取、进度视图、分片回传、交付闸门、结果作业抽成十枚 support 件,5→15)。"
|
||||
.as("真实集成:对真仓 modules/appearancepatent/service/support 求值,实测 21 支(3A 拆薄把归属谓词、陈旧扫描、结果打包、LLM 批管线、载荷读写、结果行读取、进度视图、分片回传、交付闸门、结果作业、建单解析、载荷合并、提交调度、陈旧收尾、解析分组、任务记录抽成十六枚 support 件,5→21)。"
|
||||
+ "这一格就是聚合入口存在的理由——拆分出去的新文件必须自动进面")
|
||||
.hasSize(15);
|
||||
.hasSize(21);
|
||||
assertThat(support)
|
||||
.as("3A 拆出去的十枚新件必须被逐枚点名扫到:只把分母数字改大,下一回拆件又只剩「数不对」"
|
||||
.as("3A 拆出去的新件必须被逐枚点名扫到:只把分母数字改大,下一回拆件又只剩「数不对」"
|
||||
+ "一记红,证不了「扫得到」这件事")
|
||||
.anyMatch(rel -> rel.endsWith("service/support/AppearancePatentTaskOwnership.java"))
|
||||
.anyMatch(rel -> rel.endsWith("service/support/AppearancePatentStaleTaskScanner.java"))
|
||||
@@ -388,7 +388,13 @@ class SourceScanTest {
|
||||
.anyMatch(rel -> rel.endsWith("service/support/AppearancePatentProgressSupport.java"))
|
||||
.anyMatch(rel -> rel.endsWith("service/support/AppearancePatentChunkSubmissionSupport.java"))
|
||||
.anyMatch(rel -> rel.endsWith("service/support/AppearancePatentDeliverySupport.java"))
|
||||
.anyMatch(rel -> rel.endsWith("service/support/AppearancePatentResultJobSupport.java"));
|
||||
.anyMatch(rel -> rel.endsWith("service/support/AppearancePatentResultJobSupport.java"))
|
||||
.anyMatch(rel -> rel.endsWith("service/support/AppearancePatentParsePipeline.java"))
|
||||
.anyMatch(rel -> rel.endsWith("service/support/AppearancePatentChunkPayloadMerger.java"))
|
||||
.anyMatch(rel -> rel.endsWith("service/support/AppearancePatentLlmSubmissionSupport.java"))
|
||||
.anyMatch(rel -> rel.endsWith("service/support/AppearancePatentStaleTaskFinalizer.java"))
|
||||
.anyMatch(rel -> rel.endsWith("service/support/AppearancePatentGroupingSupport.java"))
|
||||
.anyMatch(rel -> rel.endsWith("service/support/AppearancePatentTaskRecordSupport.java"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
Reference in New Issue
Block a user