fix(文案出口): 用户可见提示语一律走 UserMessages 把关,并补结果作业租约围栏
两件事同源:2026-10-09 任务 30456 的卡片上同时出现中文进度和一句英文异常原文。 围栏:派发链在执行前重读 job 行,让 activateRunningClaim 的 CAS 恒真,撞锁方 deferRunning 把在跑的行翻回 PENDING,markSuccess 静默写 0 行——成功被判成失败。 claim 快照现在贯穿到 runClaimed 不再回读,markSuccess 返回布尔并补 stage=SUCCESS_LOST 日志,让这次丢失可观测。 文案:普查数出 61 处把 ex.getMessage() 拼进用户可见字段(异常响应、任务 error_message、 结果作业 error_msg、看板 message),逐条翻译追不上新增速度,改为出口把关—— UserMessages.with(中文主干, 异常) 只拼接中文详情、orFallback(原文, 兜底句) 只放行含中文的串, 被换掉的原文进日志;GlobalExceptionHandler 按码分档兜底(401/4011/40902 各说各的话)。 另把 chunk-read-failed[N] 摘要写成"第 N 分片读取失败"、TASK_LOCK_BUSY 换成中文(40902 码不动, 客户端按码分支)。数字人两处与结果作业 worker 故意仍存原文:孤儿判定与三条 preserves raw 用例按 error_message 读它,界面侧由前端 userNotice 兜住,已在新尺子里点名豁免并反查豁免是否还被用到。 尺子:RawExceptionMessageSinkGuardTest(出口行数下限硬钉 1500+内存造违例自证)、UserMessagesTest、 UserFacingMessageChineseGuardTest 豁免表收到只剩 JSON 键 msg 一条。mvn -o test 4205 例 0 失败。
This commit is contained in:
+24
-7
@@ -3,6 +3,7 @@ package com.nanri.aiimage.common.exception;
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.security.DeviceSessionPolicy;
|
||||
import com.nanri.aiimage.common.service.TaskOwnerForwardService;
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.nanri.aiimage.config.TaskOperationLockConfig;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.validation.ConstraintViolationException;
|
||||
@@ -54,9 +55,11 @@ public class GlobalExceptionHandler {
|
||||
.headers(safeHeaders)
|
||||
.body(response.getBody());
|
||||
} catch (BusinessException forwardEx) {
|
||||
String reason = UserMessages.orFallback(
|
||||
forwardEx.getMessage(), "任务归属实例暂时联系不上,请稍后重试");
|
||||
return forwardEx.getCode() == null
|
||||
? ApiResponse.fail(forwardEx.getMessage())
|
||||
: ApiResponse.fail(forwardEx.getCode(), forwardEx.getMessage());
|
||||
? ApiResponse.fail(reason)
|
||||
: ApiResponse.fail(forwardEx.getCode(), reason);
|
||||
} catch (Exception forwardEx) {
|
||||
// 转发失败是**瞬时基础设施故障**(归属实例正在滚动重启),不是业务结论,
|
||||
// 更不能表达成「任务不存活」。原先返回 ApiResponse.fail(40903) —— HTTP 200
|
||||
@@ -100,11 +103,13 @@ public class GlobalExceptionHandler {
|
||||
}
|
||||
if (Integer.valueOf(BusinessCodes.TASK_BUSY).equals(ex.getCode())) {
|
||||
// 锁竞争:必须如实返回失败 + 可重试码,否则 worker 会把「未落库」当成功而停止重试
|
||||
return ApiResponse.fail(BusinessCodes.TASK_BUSY, ex.getMessage());
|
||||
return ApiResponse.fail(BusinessCodes.TASK_BUSY,
|
||||
UserMessages.orFallback(ex.getMessage(), "这个任务正在处理中,请稍后重试"));
|
||||
}
|
||||
String userMessage = UserMessages.orFallback(ex.getMessage(), chineseFallbackFor(ex.getCode()));
|
||||
return ex.getCode() == null
|
||||
? ApiResponse.fail(ex.getMessage())
|
||||
: ApiResponse.fail(ex.getCode(), ex.getMessage());
|
||||
? ApiResponse.fail(userMessage)
|
||||
: ApiResponse.fail(ex.getCode(), userMessage);
|
||||
}
|
||||
|
||||
@ExceptionHandler(NoResourceFoundException.class)
|
||||
@@ -122,6 +127,17 @@ public class GlobalExceptionHandler {
|
||||
|| Integer.valueOf(DeviceSessionPolicy.CODE_KICKED).equals(code);
|
||||
}
|
||||
|
||||
/** 兜底句按码分档:整条消息被换成中文时,鉴权类失败不能说得像个业务错。 */
|
||||
private String chineseFallbackFor(Integer code) {
|
||||
if (Integer.valueOf(DeviceSessionPolicy.CODE_KICKED).equals(code)) {
|
||||
return "该账号已在其他设备登录,当前会话已下线";
|
||||
}
|
||||
if (Integer.valueOf(401).equals(code)) {
|
||||
return "登录状态已失效,请重新登录";
|
||||
}
|
||||
return "操作未能完成,请稍后重试";
|
||||
}
|
||||
|
||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||
public ApiResponse<Void> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) { String message = ex.getBindingResult().getFieldError() != null
|
||||
? ex.getBindingResult().getFieldError().getDefaultMessage()
|
||||
@@ -131,7 +147,7 @@ public class GlobalExceptionHandler {
|
||||
|
||||
@ExceptionHandler(ConstraintViolationException.class)
|
||||
public ApiResponse<Void> handleConstraintViolationException(ConstraintViolationException ex) {
|
||||
return ApiResponse.fail(ex.getMessage());
|
||||
return ApiResponse.fail(UserMessages.orFallback(ex.getMessage(), "填写的内容不符合要求,请检查后重试"));
|
||||
}
|
||||
|
||||
@ExceptionHandler(AsyncRequestNotUsableException.class)
|
||||
@@ -142,7 +158,8 @@ public class GlobalExceptionHandler {
|
||||
@ExceptionHandler(ResponseStatusException.class)
|
||||
public ResponseEntity<ApiResponse<Void>> handleResponseStatusException(ResponseStatusException ex) {
|
||||
String message = ex.getReason() == null || ex.getReason().isBlank() ? ex.getMessage() : ex.getReason();
|
||||
return ResponseEntity.status(ex.getStatusCode()).body(ApiResponse.fail(message));
|
||||
return ResponseEntity.status(ex.getStatusCode())
|
||||
.body(ApiResponse.fail(UserMessages.orFallback(message, "请求未能完成,请稍后重试")));
|
||||
}
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.common.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.exception.TaskOwnerMismatchException;
|
||||
import com.nanri.aiimage.config.InstanceRoutingProperties;
|
||||
@@ -173,7 +174,7 @@ public class TaskOwnerForwardService {
|
||||
try {
|
||||
return StreamUtils.copyToByteArray(request.getInputStream());
|
||||
} catch (IOException ex) {
|
||||
throw new BusinessException("读取转发请求体失败:" + ex.getMessage());
|
||||
throw new BusinessException(UserMessages.with("读取转发请求体失败", ex));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.nanri.aiimage.common.util;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* 用户可见文案把关(2026-10-09 收口)。
|
||||
*
|
||||
* <p>背景:任务 30456 的结果文件其实已经生成、能下载,卡片上却跟着一条
|
||||
* {@code Similar ASIN result rows are empty; please retry result generation}。文案是英文不是
|
||||
* 最要命的——最要命的是它是**底层异常原文**:全仓有 61 处把 {@code ex.getMessage()} 直接
|
||||
* 拼进用户可见字段(异常响应、任务 error_message、结果作业 error_msg、看板 message),
|
||||
* 底层抛什么用户就看什么。逐条翻译译不完,因为新的 catch 天天在加。
|
||||
*
|
||||
* <p>本类把"只把中文给用户看"做成出口处的代码约束:中文照原样过,非中文换成中文句子,
|
||||
* 原文只进日志。诊断信息不丢——调用点本来就带着 {@code log.warn} 的堆栈。
|
||||
*/
|
||||
public final class UserMessages {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(UserMessages.class);
|
||||
|
||||
private UserMessages() {
|
||||
}
|
||||
|
||||
/** 中文主干 + 异常详情:详情是中文才拼接,英文详情丢弃(原文进 debug 日志)。 */
|
||||
public static String with(String headline, Throwable ex) {
|
||||
return with(headline, ex == null ? null : ex.getMessage());
|
||||
}
|
||||
|
||||
/** 中文主干 + 详情:详情是中文才拼接。 */
|
||||
public static String with(String headline, String detail) {
|
||||
String head = headline == null ? "" : headline.trim().replaceAll("[::]\\s*$", "");
|
||||
if (detail == null || detail.isBlank()) {
|
||||
return head;
|
||||
}
|
||||
if (hasChinese(detail)) {
|
||||
return head + ":" + detail.trim();
|
||||
}
|
||||
log.debug("[user-message] dropped non-chinese detail headline={} detail={}", head, detail);
|
||||
return head;
|
||||
}
|
||||
|
||||
/**
|
||||
* 整句把关:原文含中文则照原样返回,否则返回中文兜底句。
|
||||
*
|
||||
* <p>用于"整条消息都来自底层"的出口({@code ApiResponse.fail(ex.getMessage())}、
|
||||
* {@code setErrorMessage(ex.getMessage())})。被换掉时原文进 WARN,因为这类出口
|
||||
* 调用点未必另外记日志,静默替换会把根因从系统里彻底抹掉。
|
||||
*/
|
||||
public static String orFallback(String raw, String fallback) {
|
||||
if (raw != null && !raw.isBlank() && hasChinese(raw)) {
|
||||
return raw.trim();
|
||||
}
|
||||
log.warn("[user-message] replaced non-chinese message fallback={} raw={}",
|
||||
fallback, raw == null ? "" : raw);
|
||||
return fallback;
|
||||
}
|
||||
|
||||
/** 是否含汉字:含则认为是给人看的中文文案,可以原样透出。 */
|
||||
public static boolean hasChinese(String text) {
|
||||
if (text == null) {
|
||||
return false;
|
||||
}
|
||||
for (int i = 0; i < text.length(); i++) {
|
||||
char c = text.charAt(i);
|
||||
if (c >= '一' && c <= '鿿') {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -79,7 +79,7 @@ public class TaskOperationLockConfig implements WebMvcConfigurer {
|
||||
if (lockHandle == null) {
|
||||
log.info("[task-operation-lock] rejected busy task operation method={} uri={} moduleType={} taskId={} waitMillis={}",
|
||||
request.getMethod(), uri, moduleType, taskId, waitMillis);
|
||||
throw new BusinessException(40902, "TASK_LOCK_BUSY");
|
||||
throw new BusinessException(40902, "这个任务正在处理中,请稍后重试");
|
||||
}
|
||||
request.setAttribute(LOCK_ATTRIBUTE, lockHandle);
|
||||
return true;
|
||||
|
||||
+5
-5
@@ -1878,7 +1878,7 @@ public class AppearancePatentTaskService {
|
||||
|
||||
public boolean processResultFileJob(TaskFileJobEntity job) {
|
||||
if (job == null || job.getTaskId() == null || job.getResultId() == null) {
|
||||
throw new BusinessException("result file job arguments are incomplete");
|
||||
throw new BusinessException("结果文件作业参数不完整");
|
||||
}
|
||||
TaskDistributedLockService.LockHandle lockHandle = acquireTaskLock(job.getTaskId(), TASK_LOCK_WAIT_MILLIS);
|
||||
if (lockHandle == null) {
|
||||
@@ -1894,7 +1894,7 @@ public class AppearancePatentTaskService {
|
||||
private boolean processResultFileJobLocked(TaskFileJobEntity job) {
|
||||
FileTaskEntity task = fileTaskMapper.selectById(job.getTaskId());
|
||||
if (task == null || !MODULE_TYPE.equals(task.getModuleType())) {
|
||||
throw new BusinessException("task not found");
|
||||
throw new BusinessException("任务不存在");
|
||||
}
|
||||
ensureTaskOwnedByCurrentInstance(task, "assemble result file");
|
||||
job.setScopeKey(buildTaskOwnerScopeKey(task));
|
||||
@@ -1905,7 +1905,7 @@ public class AppearancePatentTaskService {
|
||||
}
|
||||
FileResultEntity result = fileResultMapper.selectById(job.getResultId());
|
||||
if (result == null || !MODULE_TYPE.equals(result.getModuleType())) {
|
||||
throw new BusinessException("result record not found");
|
||||
throw new BusinessException("结果记录不存在");
|
||||
}
|
||||
List<TaskChunkEntity> chunks = taskChunkMapper.selectList(new LambdaQueryWrapper<TaskChunkEntity>()
|
||||
.eq(TaskChunkEntity::getTaskId, task.getId())
|
||||
@@ -2766,7 +2766,7 @@ public class AppearancePatentTaskService {
|
||||
throw new BusinessException(FailedStatusRowFilter.noMatchedRowsMessage());
|
||||
}
|
||||
if (allRows.isEmpty()) {
|
||||
throw new BusinessException("no valid appearance patent rows");
|
||||
throw new BusinessException("没有解析到可检测的外观专利行,请检查表格内容");
|
||||
}
|
||||
return new ParsedWorkbook(total, dropped, new ArrayList<>(headers), allRows);
|
||||
}
|
||||
@@ -3193,7 +3193,7 @@ public class AppearancePatentTaskService {
|
||||
+ " taskId={} chunk={}", chunk.getTaskId(), chunk.getChunkIndex());
|
||||
return rows;
|
||||
}
|
||||
throw new BusinessException("appearance patent chunk payload read failed chunk="
|
||||
throw new BusinessException("读取外观专利结果分片失败,分片="
|
||||
+ chunk.getChunkIndex() + ": " + ex.getMessage(), ex);
|
||||
}
|
||||
return rows;
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.appearancepatent.service.support;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.nanri.aiimage.modules.appearancepatent.model.vo.AppearancePatentHistoryItemVo;
|
||||
import com.nanri.aiimage.modules.appearancepatent.service.AppearancePatentTaskService;
|
||||
import com.nanri.aiimage.modules.task.model.entity.FileResultEntity;
|
||||
@@ -132,7 +133,7 @@ public class AppearancePatentHistoryAssembler {
|
||||
vo.setFileProgressCurrent(current);
|
||||
vo.setFileProgressTotal(total);
|
||||
vo.setFileProgressPercent(percent);
|
||||
vo.setFileProgressMessage(snapshot.getMessage());
|
||||
vo.setFileProgressMessage(UserMessages.orFallback(snapshot.getMessage(), ""));
|
||||
}
|
||||
|
||||
private String fmt(LocalDateTime t) {
|
||||
|
||||
+16
-14
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.brand.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import cn.hutool.core.io.FileUtil;
|
||||
import cn.hutool.json.JSONUtil;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
@@ -269,14 +270,14 @@ public class BrandTaskService {
|
||||
|
||||
public void submitCrawlResult(Long taskId, BrandCrawlResultRequest request) {
|
||||
if (taskId == null || taskId <= 0) {
|
||||
throw new BusinessException("taskId invalid");
|
||||
throw new BusinessException("任务 id 不合法");
|
||||
}
|
||||
try (TaskDistributedLockService.LockHandle ignored = acquireTaskLockOrThrow(taskId, RESULT_SUBMIT_WAIT_MILLIS)) {
|
||||
long startedAt = System.currentTimeMillis();
|
||||
BrandCrawlTaskEntity task = requireActiveTask(taskId);
|
||||
List<BrandSourceFileDto> sourceFiles = parseSourceFiles(task.getFilePaths());
|
||||
if (sourceFiles.isEmpty()) {
|
||||
throw new BusinessException("task source files missing");
|
||||
throw new BusinessException("任务缺少源文件");
|
||||
}
|
||||
|
||||
Map<String, BrandSourceFileDto> sourceByUrl = new LinkedHashMap<>();
|
||||
@@ -288,7 +289,7 @@ public class BrandTaskService {
|
||||
}
|
||||
List<BrandParsedFileCacheDto> cachedFiles = brandTaskStorageService.getParsedPayload(taskId);
|
||||
if (cachedFiles == null || cachedFiles.isEmpty()) {
|
||||
throw new BusinessException("task parsed payload missing");
|
||||
throw new BusinessException("任务解析结果不存在");
|
||||
}
|
||||
Map<String, BrandParsedFileCacheDto> cachedByUrl = new LinkedHashMap<>();
|
||||
for (BrandParsedFileCacheDto cachedFile : cachedFiles) {
|
||||
@@ -297,7 +298,7 @@ public class BrandTaskService {
|
||||
|
||||
List<BrandCrawlResultFileDto> resultFiles = request.getFiles() == null ? List.of() : request.getFiles();
|
||||
if (resultFiles.isEmpty()) {
|
||||
throw new BusinessException("files is empty");
|
||||
throw new BusinessException("文件列表为空");
|
||||
}
|
||||
ensureNoDuplicateResultFiles(resultFiles);
|
||||
|
||||
@@ -315,21 +316,21 @@ public class BrandTaskService {
|
||||
for (BrandCrawlResultFileDto resultFile : resultFiles) {
|
||||
String fileUrl = blankToNull(resultFile.getFileUrl());
|
||||
if (fileUrl == null) {
|
||||
throw new BusinessException("fileUrl is blank");
|
||||
throw new BusinessException("文件地址为空");
|
||||
}
|
||||
BrandSourceFileDto sourceFile = sourceByUrl.get(fileUrl);
|
||||
if (sourceFile == null) {
|
||||
throw new BusinessException("unknown fileUrl: " + fileUrl);
|
||||
throw new BusinessException("未识别的文件地址: " + fileUrl);
|
||||
}
|
||||
BrandParsedFileCacheDto cachedFile = cachedByUrl.get(fileUrl);
|
||||
if (cachedFile == null) {
|
||||
throw new BusinessException("parsed cache missing: " + fileUrl);
|
||||
throw new BusinessException("解析缓存不存在: " + fileUrl);
|
||||
}
|
||||
int totalLines = cachedFile.getRows() == null ? 0 : cachedFile.getRows().size();
|
||||
if (resultFile.getTotalLines() == null || resultFile.getTotalLines() <= 0) {
|
||||
resultFile.setTotalLines(totalLines);
|
||||
} else if (totalLines > 0 && resultFile.getTotalLines() > totalLines) {
|
||||
throw new BusinessException("totalLines exceeds source rows: " + fileUrl);
|
||||
throw new BusinessException("行数超过源数据行数: " + fileUrl);
|
||||
}
|
||||
BrandTaskStorageService.ChunkStoreResult storeResult = brandTaskStorageService.storeChunk(taskId, resultFile);
|
||||
BrandTaskStorageService.ChunkStoreResult refreshResult = brandTaskStorageService.refreshFileAggregate(taskId, fileUrl);
|
||||
@@ -718,13 +719,14 @@ public class BrandTaskService {
|
||||
.set(BrandCrawlTaskEntity::getStatus, STATUS_FAILED)
|
||||
.set(BrandCrawlTaskEntity::getProgressCurrent, brandTaskStorageService.countCompletedFiles(taskId))
|
||||
.set(BrandCrawlTaskEntity::getProgressTotal, totalCount)
|
||||
.set(BrandCrawlTaskEntity::getErrorMessage, ex.getMessage()));
|
||||
brandTaskProgressCacheService.markFailed(taskId, ex.getMessage());
|
||||
saveBrandProgressSnapshot(taskId, STATUS_FAILED, totalCount, brandTaskStorageService.countCompletedFiles(taskId), 1, ex.getMessage());
|
||||
.set(BrandCrawlTaskEntity::getErrorMessage, UserMessages.orFallback(ex.getMessage(), "品牌检测任务执行失败")));
|
||||
brandTaskProgressCacheService.markFailed(taskId, UserMessages.orFallback(ex.getMessage(), "品牌检测任务执行失败"));
|
||||
saveBrandProgressSnapshot(taskId, STATUS_FAILED, totalCount, brandTaskStorageService.countCompletedFiles(taskId), 1,
|
||||
UserMessages.orFallback(ex.getMessage(), "品牌检测任务执行失败"));
|
||||
if (ex instanceof BusinessException businessException) {
|
||||
throw businessException;
|
||||
}
|
||||
throw new BusinessException(ex.getMessage());
|
||||
throw new BusinessException(UserMessages.orFallback(ex.getMessage(), "品牌检测任务执行失败,请稍后重试"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -821,7 +823,7 @@ public class BrandTaskService {
|
||||
*/
|
||||
public Map<String, Object> abortTask(Long taskId, String errorMessage) {
|
||||
if (taskId == null || taskId <= 0) {
|
||||
throw new BusinessException("taskId invalid");
|
||||
throw new BusinessException("任务 id 不合法");
|
||||
}
|
||||
try (TaskDistributedLockService.LockHandle ignored = acquireTaskLockOrThrow(taskId, RESULT_SUBMIT_WAIT_MILLIS)) {
|
||||
BrandCrawlTaskEntity task = requireTask(taskId);
|
||||
@@ -1661,7 +1663,7 @@ public class BrandTaskService {
|
||||
private TaskDistributedLockService.LockHandle acquireTaskLockOrThrow(Long taskId, long waitMillis) {
|
||||
TaskDistributedLockService.LockHandle lockHandle = acquireTaskLock(taskId, waitMillis);
|
||||
if (lockHandle == null) {
|
||||
throw new BusinessException("task lock is busy");
|
||||
throw new BusinessException("任务正被占用,请稍后重试");
|
||||
}
|
||||
return lockHandle;
|
||||
}
|
||||
|
||||
+16
-16
@@ -52,7 +52,7 @@ public class BrandTaskStorageService {
|
||||
}
|
||||
String scopeKey = normalize(item.getFileUrl());
|
||||
String scopeHash = hash(scopeKey);
|
||||
String parsedJson = storeParsedPayload(taskId, scopeHash, writeJson(item, "Save brand task parsed payload failed"));
|
||||
String parsedJson = storeParsedPayload(taskId, scopeHash, writeJson(item, "保存品牌任务解析结果失败"));
|
||||
TaskScopeStateEntity state = getScopeState(taskId, scopeHash);
|
||||
if (state == null) {
|
||||
TaskScopeStateEntity entity = new TaskScopeStateEntity();
|
||||
@@ -74,7 +74,7 @@ public class BrandTaskStorageService {
|
||||
}
|
||||
}
|
||||
if (state == null) {
|
||||
throw new BusinessException("Save brand task parsed payload failed");
|
||||
throw new BusinessException("保存品牌任务解析结果失败");
|
||||
}
|
||||
transientPayloadStorageService.deleteReplacedPayloadIfNeeded(state.getParsedPayloadJson(), parsedJson);
|
||||
taskScopeStateMapper.update(null, new LambdaUpdateWrapper<TaskScopeStateEntity>()
|
||||
@@ -106,7 +106,7 @@ public class BrandTaskStorageService {
|
||||
try {
|
||||
result.add(objectMapper.readValue(payloadJson, BrandParsedFileCacheDto.class));
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("Read brand task parsed payload failed");
|
||||
throw new BusinessException("读取品牌任务解析结果失败");
|
||||
}
|
||||
}
|
||||
return result;
|
||||
@@ -133,7 +133,7 @@ public class BrandTaskStorageService {
|
||||
saveAggregate(taskId, scopeKey, scopeHash, aggregate, now);
|
||||
return new ChunkStoreResult(false, false, countCompletedFiles(taskId), aggregate);
|
||||
}
|
||||
throw new BusinessException("Brand task chunk conflict: " + scopeKey + "#" + file.getChunkIndex());
|
||||
throw new BusinessException("品牌任务分片冲突: " + scopeKey + "#" + file.getChunkIndex());
|
||||
}
|
||||
|
||||
String storedPayload = transientPayloadStorageService.storeChunkPayload(MODULE_TYPE, taskId, scopeHash, file.getChunkIndex(), payloadJson);
|
||||
@@ -164,7 +164,7 @@ public class BrandTaskStorageService {
|
||||
return new ChunkStoreResult(false, false, countCompletedFiles(taskId), aggregate);
|
||||
}
|
||||
transientPayloadStorageService.deletePayloadIfPresent(storedPayload);
|
||||
throw new BusinessException("Brand task chunk conflict: " + scopeKey + "#" + file.getChunkIndex());
|
||||
throw new BusinessException("品牌任务分片冲突: " + scopeKey + "#" + file.getChunkIndex());
|
||||
}
|
||||
|
||||
BrandFileAggregateCacheDto aggregate = rebuildAggregate(taskId, scopeKey, scopeHash);
|
||||
@@ -182,7 +182,7 @@ public class BrandTaskStorageService {
|
||||
String aggregateJson = transientPayloadStorageService.resolvePayload(state.getStateJson(), "read brand task aggregate failed");
|
||||
return objectMapper.readValue(aggregateJson, BrandFileAggregateCacheDto.class);
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("Read brand task aggregate failed");
|
||||
throw new BusinessException("读取品牌任务汇总状态失败");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -207,7 +207,7 @@ public class BrandTaskStorageService {
|
||||
String aggregateJson = transientPayloadStorageService.resolvePayload(state.getStateJson(), "read brand task aggregate failed");
|
||||
result.put(state.getScopeKey(), objectMapper.readValue(aggregateJson, BrandFileAggregateCacheDto.class));
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("Read brand task aggregate failed");
|
||||
throw new BusinessException("读取品牌任务汇总状态失败");
|
||||
}
|
||||
}
|
||||
return result;
|
||||
@@ -328,7 +328,7 @@ public class BrandTaskStorageService {
|
||||
String aggregateJson = writeJson(aggregate, "Save brand task aggregate failed");
|
||||
TaskScopeStateEntity state = getScopeState(taskId, scopeHash);
|
||||
if (state == null) {
|
||||
throw new BusinessException("Brand task aggregate state missing: " + scopeKey);
|
||||
throw new BusinessException("品牌任务汇总状态不存在: " + scopeKey);
|
||||
}
|
||||
String storedAggregate = transientPayloadStorageService.storeScopePayloadVersioned(MODULE_TYPE, taskId, scopeHash, aggregateJson, true);
|
||||
int chunkTotal = aggregate.getChunkTotal() == null ? 0 : aggregate.getChunkTotal();
|
||||
@@ -383,7 +383,7 @@ public class BrandTaskStorageService {
|
||||
|
||||
private void ensureChunkConsistency(BrandFileAggregateCacheDto aggregate, BrandCrawlResultFileDto file) {
|
||||
if (aggregate.getChunkTotal() != null && file.getChunkTotal() != null && !aggregate.getChunkTotal().equals(file.getChunkTotal())) {
|
||||
throw new BusinessException("Brand task chunkTotal mismatch: " + aggregate.getFileUrl());
|
||||
throw new BusinessException("品牌任务分片总数对不上: " + aggregate.getFileUrl());
|
||||
}
|
||||
if (aggregate.getChunkTotal() == null) {
|
||||
aggregate.setChunkTotal(file.getChunkTotal());
|
||||
@@ -454,7 +454,7 @@ public class BrandTaskStorageService {
|
||||
mergeAggregate(aggregate, chunkPayload);
|
||||
}
|
||||
if (aggregate == null) {
|
||||
throw new BusinessException("Read brand task aggregate data failed");
|
||||
throw new BusinessException("读取品牌任务汇总数据失败");
|
||||
}
|
||||
aggregate.setFileUrl(scopeKey);
|
||||
aggregate.setReceivedChunkCount(chunks.size());
|
||||
@@ -469,20 +469,20 @@ public class BrandTaskStorageService {
|
||||
String resolvedPayload = transientPayloadStorageService.resolvePayload(payloadJson, "read brand task chunk failed");
|
||||
return objectMapper.readValue(resolvedPayload, BrandCrawlResultFileDto.class);
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("Read brand task chunk failed");
|
||||
throw new BusinessException("读取品牌任务分片失败");
|
||||
}
|
||||
}
|
||||
|
||||
private void validateChunk(BrandCrawlResultFileDto file) {
|
||||
if (file == null) {
|
||||
throw new BusinessException("Brand task chunk must not be null");
|
||||
throw new BusinessException("品牌任务分片不能为空");
|
||||
}
|
||||
if (file.getChunkIndex() == null || file.getChunkTotal() == null || file.getChunkIndex() <= 0
|
||||
|| file.getChunkTotal() <= 0 || file.getChunkIndex() > file.getChunkTotal()) {
|
||||
throw new BusinessException("Brand task chunk parameters are invalid");
|
||||
throw new BusinessException("品牌任务分片参数不合法");
|
||||
}
|
||||
if (isBlank(file.getFileUrl())) {
|
||||
throw new BusinessException("fileUrl must not be blank");
|
||||
throw new BusinessException("文件地址不能为空");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -492,9 +492,9 @@ public class BrandTaskStorageService {
|
||||
|
||||
private String resolveParsedPayload(String value) {
|
||||
try {
|
||||
return transientPayloadStorageService.resolvePayload(value, "Read brand task parsed payload failed");
|
||||
return transientPayloadStorageService.resolvePayload(value, "读取品牌任务解析结果失败");
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("Read brand task parsed payload failed");
|
||||
throw new BusinessException("读取品牌任务解析结果失败");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.collectdata.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.util.SxssfWorkbookWriter;
|
||||
import com.nanri.aiimage.modules.collectdata.model.dto.CollectDataSummaryRowDto;
|
||||
@@ -98,7 +99,7 @@ public class CollectDataExcelAssemblyService {
|
||||
} catch (Exception ex) {
|
||||
log.warn("[collect-data] write workbook failed: {}", ex.getMessage());
|
||||
deleteQuietly(tmpFile);
|
||||
throw new BusinessException("生成采集数据 Excel 失败: " + ex.getMessage());
|
||||
throw new BusinessException(UserMessages.with("生成采集数据 Excel 失败", ex));
|
||||
} finally {
|
||||
writer.close();
|
||||
deleteQuietly(tmpFile);
|
||||
|
||||
+13
-12
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.convert.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import cn.hutool.core.io.FileUtil;
|
||||
import cn.hutool.core.util.IdUtil;
|
||||
import cn.hutool.json.JSONUtil;
|
||||
@@ -90,7 +91,7 @@ public class ConvertRunService {
|
||||
try {
|
||||
File inputFile = findLocalSourceFile(sourceFile.getFileKey());
|
||||
if (inputFile == null || !inputFile.exists()) {
|
||||
throw new BusinessException("Uploaded source file does not exist, please upload again.");
|
||||
throw new BusinessException("上传的源文件不存在,请重新上传。");
|
||||
}
|
||||
|
||||
String inputName = sourceFile.getOriginalFilename() == null
|
||||
@@ -143,7 +144,7 @@ public class ConvertRunService {
|
||||
ConvertResultItemVo item = new ConvertResultItemVo();
|
||||
item.setSourceFilename(sourceFile.getOriginalFilename());
|
||||
item.setSuccess(false);
|
||||
item.setError(ex.getMessage());
|
||||
item.setError(UserMessages.orFallback(ex.getMessage(), "这个文件转换失败,请检查内容后重新上传"));
|
||||
items.add(item);
|
||||
failedCount++;
|
||||
|
||||
@@ -152,7 +153,7 @@ public class ConvertRunService {
|
||||
resultEntity.setModuleType(MODULE_TYPE);
|
||||
resultEntity.setSourceFilename(sourceFile.getOriginalFilename());
|
||||
resultEntity.setSuccess(0);
|
||||
resultEntity.setErrorMessage(ex.getMessage());
|
||||
resultEntity.setErrorMessage(UserMessages.orFallback(ex.getMessage(), "这个文件转换失败,请检查内容后重新上传"));
|
||||
resultEntity.setUserId(request.getUserId());
|
||||
resultEntity.setCreatedAt(LocalDateTime.now());
|
||||
fileResultMapper.insert(resultEntity);
|
||||
@@ -260,7 +261,7 @@ public class ConvertRunService {
|
||||
public void deleteHistory(Long resultId, Long userId) {
|
||||
FileResultEntity entity = fileResultMapper.selectById(resultId);
|
||||
if (entity == null || !MODULE_TYPE.equals(entity.getModuleType()) || !userId.equals(entity.getUserId())) {
|
||||
throw new BusinessException("Convert result record does not exist.");
|
||||
throw new BusinessException("没有这条转换结果。");
|
||||
}
|
||||
fileResultMapper.deleteById(resultId);
|
||||
}
|
||||
@@ -268,7 +269,7 @@ public class ConvertRunService {
|
||||
public String getResultDownloadUrl(Long resultId, Long userId) {
|
||||
FileResultEntity entity = fileResultMapper.selectById(resultId);
|
||||
if (entity == null || entity.getResultFileUrl() == null || !MODULE_TYPE.equals(entity.getModuleType()) || !userId.equals(entity.getUserId())) {
|
||||
throw new BusinessException("Convert result file does not exist.");
|
||||
throw new BusinessException("转换结果文件不存在。");
|
||||
}
|
||||
return ossStorageService.generateFreshDownloadUrl(entity.getResultFileUrl());
|
||||
}
|
||||
@@ -347,7 +348,7 @@ public class ConvertRunService {
|
||||
.filter(column -> !resolvedHeaderMap.containsKey(column))
|
||||
.toList();
|
||||
if (!missing.isEmpty()) {
|
||||
throw new BusinessException("Missing required columns: " + String.join(", ", missing));
|
||||
throw new BusinessException("缺少必需列: " + String.join(", ", missing));
|
||||
}
|
||||
headerRead[0] = true;
|
||||
headerMapHolder.set(resolvedHeaderMap);
|
||||
@@ -364,7 +365,7 @@ public class ConvertRunService {
|
||||
public void onRow(String sheetName, Integer sheetNo, int excelRowIndex, Map<Integer, String> headerMap, Map<Integer, String> rowMap) throws Exception {
|
||||
Map<String, Integer> resolvedHeaderMap = headerMapHolder.get();
|
||||
if (resolvedHeaderMap == null) {
|
||||
throw new BusinessException("Excel header row is empty.");
|
||||
throw new BusinessException("Excel 表头行为空。");
|
||||
}
|
||||
int asinIndex = resolvedHeaderMap.getOrDefault("ASIN", -1);
|
||||
String asin = asinIndex >= 0 ? normalizeCellText(rowMap.get(asinIndex)) : "";
|
||||
@@ -400,7 +401,7 @@ public class ConvertRunService {
|
||||
}
|
||||
});
|
||||
if (!headerRead[0]) {
|
||||
throw new BusinessException("Excel header row is empty.");
|
||||
throw new BusinessException("Excel 表头行为空。");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -419,7 +420,7 @@ public class ConvertRunService {
|
||||
return objectMapper.readValue(json, new TypeReference<List<String>>() {
|
||||
});
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("Template config parsing failed.");
|
||||
throw new BusinessException("模板配置解析失败。");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -434,7 +435,7 @@ public class ConvertRunService {
|
||||
zos.closeEntry();
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("Convert result packaging failed: " + ex.getMessage());
|
||||
throw new BusinessException(UserMessages.with("转换结果打包失败", ex));
|
||||
}
|
||||
return zipFile;
|
||||
}
|
||||
@@ -450,7 +451,7 @@ public class ConvertRunService {
|
||||
zos.closeEntry();
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("Convert folder result packaging failed: " + ex.getMessage());
|
||||
throw new BusinessException(UserMessages.with("转换目录结果打包失败", ex));
|
||||
}
|
||||
return zipFile;
|
||||
}
|
||||
@@ -489,7 +490,7 @@ public class ConvertRunService {
|
||||
return objectMapper.readValue(json, new TypeReference<Map<String, String>>() {
|
||||
});
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("Template config parsing failed.");
|
||||
throw new BusinessException("模板配置解析失败。");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+12
-14
@@ -94,12 +94,10 @@ public class DedupeTotalDataController {
|
||||
HttpServletRequest request) {
|
||||
RequestOperator operator = requireDedupeTotalDataAccess(request);
|
||||
AdminUserEntity user = operator.user();
|
||||
List<Long> memberIds = operator.superAdmin()
|
||||
? dataReadScope.readScope(user, companyId).userIdsOr(null)
|
||||
: null;
|
||||
Long scopedCompanyId = dataReadScope.superAdminScopedCompanyId(user, companyId);
|
||||
return ApiResponse.success(dedupeTotalDataService.page(
|
||||
page, pageSize, keyword, username, startDate, endDate, groupId, country, lastId,
|
||||
operator.id(), memberIds));
|
||||
operator.id(), scopedCompanyId));
|
||||
}
|
||||
|
||||
@GetMapping("/export")
|
||||
@@ -115,14 +113,12 @@ public class DedupeTotalDataController {
|
||||
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId,
|
||||
HttpServletRequest request) {
|
||||
if (startDate != null && endDate != null && startDate.isAfter(endDate)) {
|
||||
throw new BusinessException(400, "invalid export date range");
|
||||
throw new BusinessException(400, "导出的日期范围不对,请重新选择开始和结束日期");
|
||||
}
|
||||
RequestOperator operator = requireDedupeTotalDataAccess(request);
|
||||
AdminUserEntity user = operator.user();
|
||||
Long operatorId = operator.id();
|
||||
List<Long> memberIds = operator.superAdmin()
|
||||
? dataReadScope.readScope(user, companyId).userIdsOr(null)
|
||||
: null;
|
||||
Long scopedCompanyId = dataReadScope.superAdminScopedCompanyId(user, companyId);
|
||||
boolean monthlyZip = isCrossMonthRange(startDate, endDate);
|
||||
String filename = "dedupe-total-data-" + LocalDateTime.now().format(EXPORT_FILENAME_FORMATTER)
|
||||
+ (monthlyZip ? ".zip" : ".xlsx");
|
||||
@@ -130,9 +126,9 @@ public class DedupeTotalDataController {
|
||||
// 会把它当成"范围没交给任何调用"而假红),所以 operatorId 先在局部变量里落好。
|
||||
StreamingResponseBody body = monthlyZip
|
||||
? outputStream -> dedupeTotalDataService.writeMonthlyZipExport(
|
||||
outputStream, username, startDate, endDate, groupId, country, operatorId, memberIds)
|
||||
outputStream, username, startDate, endDate, groupId, country, operatorId, scopedCompanyId)
|
||||
: outputStream -> dedupeTotalDataService.writeExport(
|
||||
outputStream, username, startDate, endDate, groupId, country, operatorId, memberIds);
|
||||
outputStream, username, startDate, endDate, groupId, country, operatorId, scopedCompanyId);
|
||||
return ResponseEntity.ok()
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION, DownloadHeaderUtil.contentDisposition(filename))
|
||||
.contentType(MediaType.parseMediaType(monthlyZip ? ZIP_CONTENT_TYPE : XLSX_CONTENT_TYPE))
|
||||
@@ -301,10 +297,12 @@ public class DedupeTotalDataController {
|
||||
|
||||
// 公司 tab 的读范围与写侧归属(create / import / delete-import)都就地算在 handler 里,
|
||||
// 不留私有收口方法:G2 的断言 A 只在这支 handler 的
|
||||
// 块内找 readScope(,私有方法在它自己的闭括号处收口、不算在内(CompanyIdParamGoesThroughReadScopeTest
|
||||
// 类注释第 5、7 条),挪进去 = 这一页的 tab 没人看守。收窄只给超管:非超管已由 resolveAccessScope
|
||||
// 按会话裁剪,且他的可见集里含「靠分组可见」的行,叠一层账号 IN 会把那批行静默删掉
|
||||
// (同 ShopManageController 的口径)。
|
||||
// 块内找正门调用,私有方法在它自己的闭括号处收口、不算在内(CompanyIdParamGoesThroughReadScopeTest
|
||||
// 类注释第 5、7 条),挪进去 = 这一页的 tab 没人看守。读侧收窄走 superAdminScopedCompanyId
|
||||
// (2026-10-09 口径切换:从"上传账号集合"改到"行自己的 company_id",超管代导入与上传者已删
|
||||
// 两类行原口径都归错,见该方法 javadoc);写侧 create/import 走 readCompanyIdOrOwn。
|
||||
// 两条都只对超管生效:非超管已由 resolveAccessScope 按会话裁剪,且他的可见集里含
|
||||
// 「靠分组可见」的行,叠一层公司谓词会把那批行静默删掉(同 ShopManageController 的口径)。
|
||||
|
||||
private record RequestOperator(Long id, boolean superAdmin, AdminUserEntity user) {
|
||||
}
|
||||
|
||||
+6
-5
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.dedupe.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import cn.hutool.core.io.FileUtil;
|
||||
import cn.hutool.core.util.IdUtil;
|
||||
import cn.hutool.json.JSONUtil;
|
||||
@@ -197,7 +198,7 @@ public class DedupeRunService {
|
||||
} catch (Exception e) {
|
||||
runProgressMap.remove(runId);
|
||||
decrementRunningCount(request.getUserId());
|
||||
throw new BusinessException("提交去重任务失败:" + e.getMessage());
|
||||
throw new BusinessException(UserMessages.with("提交去重任务失败", e));
|
||||
}
|
||||
|
||||
return snapshot(progress);
|
||||
@@ -375,7 +376,7 @@ public class DedupeRunService {
|
||||
synchronized (progress) {
|
||||
progress.setStatus("failed");
|
||||
progress.setFinished(true);
|
||||
progress.setError("去重任务收尾失败:" + ex.getMessage());
|
||||
progress.setError(UserMessages.with("去重任务收尾失败", ex));
|
||||
}
|
||||
task.setStatus("FAILED");
|
||||
task.setErrorMessage(progress.getError());
|
||||
@@ -558,7 +559,7 @@ public class DedupeRunService {
|
||||
return item;
|
||||
} catch (Exception ex) {
|
||||
item.setSuccess(false);
|
||||
item.setError(ex.getMessage());
|
||||
item.setError(UserMessages.orFallback(ex.getMessage(), "这个文件去重失败,请检查内容后重新上传"));
|
||||
log.error("dedupe run file failed fileKey={} filename={} error",
|
||||
sourceFile.getFileKey(), sourceFile.getOriginalFilename(), ex);
|
||||
try {
|
||||
@@ -567,7 +568,7 @@ public class DedupeRunService {
|
||||
resultEntity.setModuleType("DEDUPE");
|
||||
resultEntity.setSourceFilename(sourceFile.getOriginalFilename());
|
||||
resultEntity.setSuccess(0);
|
||||
resultEntity.setErrorMessage(ex.getMessage());
|
||||
resultEntity.setErrorMessage(UserMessages.orFallback(ex.getMessage(), "这个文件去重失败,请检查内容后重新上传"));
|
||||
resultEntity.setUserId(request.getUserId());
|
||||
resultEntity.setCreatedAt(LocalDateTime.now());
|
||||
fileResultMapper.insert(resultEntity);
|
||||
@@ -963,7 +964,7 @@ public class DedupeRunService {
|
||||
zos.closeEntry();
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("去重结果打包失败:" + ex.getMessage());
|
||||
throw new BusinessException(UserMessages.with("去重结果打包失败", ex));
|
||||
}
|
||||
return zipFile;
|
||||
}
|
||||
|
||||
+7
-6
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.dedupe.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import cn.hutool.core.util.IdUtil;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
@@ -279,7 +280,7 @@ public class DedupeTotalDataService {
|
||||
throw new BusinessException("导出输出流不能为空");
|
||||
}
|
||||
if (startDate != null && endDate != null && startDate.isAfter(endDate)) {
|
||||
throw new BusinessException("invalid export date range");
|
||||
throw new BusinessException("导出的日期范围不对,请重新选择开始和结束日期");
|
||||
}
|
||||
String safeUsername = username == null ? "" : username.trim();
|
||||
AccessScope scope = resolveAccessScope(operatorId);
|
||||
@@ -315,14 +316,14 @@ public class DedupeTotalDataService {
|
||||
Long operatorId,
|
||||
List<Long> companyMemberIds) {
|
||||
if (outputStream == null) {
|
||||
throw new BusinessException("export output stream cannot be null");
|
||||
throw new BusinessException("导出文件写入失败,请稍后重试");
|
||||
}
|
||||
if (startDate == null || endDate == null || YearMonth.from(startDate).equals(YearMonth.from(endDate))) {
|
||||
writeExport(outputStream, username, startDate, endDate, groupId, country, operatorId, companyMemberIds);
|
||||
return;
|
||||
}
|
||||
if (startDate.isAfter(endDate)) {
|
||||
throw new BusinessException("invalid export date range");
|
||||
throw new BusinessException("导出的日期范围不对,请重新选择开始和结束日期");
|
||||
}
|
||||
String safeUsername = username == null ? "" : username.trim();
|
||||
String safeCountry = country == null ? "" : country.trim();
|
||||
@@ -350,7 +351,7 @@ public class DedupeTotalDataService {
|
||||
} catch (BusinessException ex) {
|
||||
throw ex;
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("export dedupe total data failed");
|
||||
throw new BusinessException("去重库数据导出失败,请稍后重试");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -670,7 +671,7 @@ public class DedupeTotalDataService {
|
||||
progress.setStatus("success");
|
||||
} catch (Exception e) {
|
||||
progress.setStatus("failed");
|
||||
progress.setErrorMessage(e instanceof BusinessException ? e.getMessage() : "删除 Excel 匹配数据失败");
|
||||
progress.setErrorMessage(UserMessages.orFallback(e.getMessage(), "删除 Excel 匹配数据失败"));
|
||||
} finally {
|
||||
deleteQuietly(tempFile);
|
||||
deleteImportCompletedAtMap.put(importId, System.currentTimeMillis());
|
||||
@@ -697,7 +698,7 @@ public class DedupeTotalDataService {
|
||||
progress.setStatus("success");
|
||||
} catch (Exception e) {
|
||||
progress.setStatus("failed");
|
||||
progress.setErrorMessage(e instanceof BusinessException ? e.getMessage() : "导入 Excel 失败");
|
||||
progress.setErrorMessage(UserMessages.orFallback(e.getMessage(), "导入 Excel 失败"));
|
||||
// 此前该 catch 既不记日志也不带 cause,线上只有一句「导入 Excel 失败」,无栈无定位线索
|
||||
log.error("[dedupe-total-data] 异步导入失败 filename={} userId={}", filename, uploaderUserId, e);
|
||||
} finally {
|
||||
|
||||
+3
-2
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.deletebrand.controller;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
@@ -148,10 +149,10 @@ public class DeleteBrandRunController {
|
||||
return ApiResponse.success(null);
|
||||
} catch (BusinessException ex) {
|
||||
response.setStatus(HttpStatus.BAD_REQUEST.value());
|
||||
return ApiResponse.fail(ex.getMessage());
|
||||
return ApiResponse.fail(UserMessages.orFallback(ex.getMessage(), "删除ASIN提交失败,请稍后重试"));
|
||||
} catch (Exception ex) {
|
||||
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
|
||||
return ApiResponse.fail("服务异常:" + ex.getMessage());
|
||||
return ApiResponse.fail(UserMessages.with("删除ASIN提交失败", ex));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+13
-12
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.deletebrand.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import cn.hutool.core.io.FileUtil;
|
||||
import cn.hutool.core.util.IdUtil;
|
||||
import cn.hutool.json.JSONUtil;
|
||||
@@ -246,7 +247,7 @@ public class DeleteBrandRunService {
|
||||
item.setResultId(resultEntity.getId());
|
||||
} catch (Exception ex) {
|
||||
item.setSuccess(false);
|
||||
item.setError(ex.getMessage());
|
||||
item.setError(UserMessages.orFallback(ex.getMessage(), "这个文件解析失败,请检查内容后重新上传"));
|
||||
parsedFailedCount++;
|
||||
|
||||
FileResultEntity resultEntity = new FileResultEntity();
|
||||
@@ -255,7 +256,7 @@ public class DeleteBrandRunService {
|
||||
resultEntity.setSourceFilename(sourceFile.getOriginalFilename());
|
||||
resultEntity.setSourceFileUrl(sourceFile.getFileKey());
|
||||
resultEntity.setSuccess(0);
|
||||
resultEntity.setErrorMessage(ex.getMessage());
|
||||
resultEntity.setErrorMessage(UserMessages.orFallback(ex.getMessage(), "这个文件解析失败,请检查内容后重新上传"));
|
||||
resultEntity.setUserId(request.getUserId());
|
||||
resultEntity.setCreatedAt(LocalDateTime.now());
|
||||
fileResultMapper.insert(resultEntity);
|
||||
@@ -1345,18 +1346,18 @@ public class DeleteBrandRunService {
|
||||
@Transactional(propagation = org.springframework.transaction.annotation.Propagation.NEVER)
|
||||
public void submitResult(Long taskId, DeleteBrandSubmitResultRequest request) {
|
||||
if (taskId == null || taskId <= 0) {
|
||||
throw new BusinessException("taskId invalid");
|
||||
throw new BusinessException("任务 id 不合法");
|
||||
}
|
||||
try (TaskDistributedLockService.LockHandle ignored = acquireTaskLockOrThrow(taskId, TASK_LOCK_WAIT_MILLIS)) {
|
||||
log.info("[DeleteBrand] Received submitResult for taskId: {}, files count: {}", taskId, request == null || request.getFiles() == null ? 0 : request.getFiles().size());
|
||||
|
||||
if (request == null || request.getFiles() == null || request.getFiles().isEmpty()) {
|
||||
throw new BusinessException("files is empty");
|
||||
throw new BusinessException("文件列表为空");
|
||||
}
|
||||
|
||||
FileTaskEntity task = loadTaskForExecution(taskId);
|
||||
if (task == null || !MODULE_TYPE.equals(task.getModuleType())) {
|
||||
throw new BusinessException("task not found");
|
||||
throw new BusinessException("任务不存在");
|
||||
}
|
||||
if ("SUCCESS".equals(task.getStatus()) || "FAILED".equals(task.getStatus())) {
|
||||
log.warn("[DeleteBrand] submitResult rejected because task is terminal -> taskId: {}, status: {}, createdAt: {}, updatedAt: {}, finishedAt: {}, error: {}, sourceFiles: {}, successFiles: {}, failedFiles: {}",
|
||||
@@ -1369,12 +1370,12 @@ public class DeleteBrandRunService {
|
||||
task.getSourceFileCount(),
|
||||
task.getSuccessFileCount(),
|
||||
task.getFailedFileCount());
|
||||
throw new BusinessException("task already finished");
|
||||
throw new BusinessException("任务已结束");
|
||||
}
|
||||
|
||||
Map<String, DeleteBrandParsedFileCacheDto> parsedPayload = deleteBrandTaskStorageService.loadParsedPayload(taskId);
|
||||
if (parsedPayload == null || parsedPayload.isEmpty()) {
|
||||
throw new BusinessException("task parsed payload missing");
|
||||
throw new BusinessException("任务解析结果不存在");
|
||||
}
|
||||
|
||||
if (!"RUNNING".equals(task.getStatus())) {
|
||||
@@ -1397,12 +1398,12 @@ public class DeleteBrandRunService {
|
||||
|
||||
String fileIdentity = resolveFileIdentity(fileDto);
|
||||
if (fileIdentity.isBlank()) {
|
||||
throw new BusinessException("file identity is blank");
|
||||
throw new BusinessException("文件标识为空");
|
||||
}
|
||||
DeleteBrandParsedFileCacheDto parsedFile = parsedPayload.get(fileIdentity);
|
||||
if (parsedFile == null) {
|
||||
log.warn("[DeleteBrand] parsed payload not found for identity: {}", fileIdentity);
|
||||
throw new BusinessException("parsed file not found: " + fileIdentity);
|
||||
throw new BusinessException("找不到已解析文件: " + fileIdentity);
|
||||
}
|
||||
|
||||
validateChunk(fileDto, parsedFile);
|
||||
@@ -1562,7 +1563,7 @@ public class DeleteBrandRunService {
|
||||
log.info("[DeleteBrand] tryFinalizeTask calling finalizeTask -> finishedFiles: {}, expectedFiles: {}", finishedFiles, expectedFiles);
|
||||
finalizeTask(task, parsedPayload, mergedByFile);
|
||||
} catch (BusinessException ex) {
|
||||
if (ex.getMessage() != null && ex.getMessage().contains("task lock is busy")) {
|
||||
if (ex.getMessage() != null && ex.getMessage().contains("任务正被占用,请稍后重试")) {
|
||||
log.info("[DeleteBrand] tryFinalizeTask skipped because task lock is busy taskId={} fromCompensation={}", taskId, fromCompensation);
|
||||
return;
|
||||
}
|
||||
@@ -1842,7 +1843,7 @@ public class DeleteBrandRunService {
|
||||
cleanupCompletedTaskDataIfNoPendingFileJobs(task.getId());
|
||||
} catch (Exception ex) {
|
||||
task.setStatus("FAILED");
|
||||
task.setErrorMessage(ex.getMessage());
|
||||
task.setErrorMessage(UserMessages.orFallback(ex.getMessage(), "删除ASIN任务执行失败"));
|
||||
task.setUpdatedAt(LocalDateTime.now());
|
||||
task.setFinishedAt(LocalDateTime.now());
|
||||
fileTaskMapper.updateById(task);
|
||||
@@ -2250,7 +2251,7 @@ public class DeleteBrandRunService {
|
||||
private TaskDistributedLockService.LockHandle acquireTaskLockOrThrow(Long taskId, long waitMillis) {
|
||||
TaskDistributedLockService.LockHandle lockHandle = acquireTaskLock(taskId, waitMillis);
|
||||
if (lockHandle == null) {
|
||||
throw new BusinessException("task lock is busy");
|
||||
throw new BusinessException("任务正被占用,请稍后重试");
|
||||
}
|
||||
return lockHandle;
|
||||
}
|
||||
|
||||
+9
-9
@@ -54,7 +54,7 @@ public class DeleteBrandTaskStorageService {
|
||||
}
|
||||
String scopeHash = hash(scopeKey);
|
||||
TaskScopeStateEntity existing = existingByHash.get(scopeHash);
|
||||
String payloadJson = writeJson(entry.getValue(), "failed to save delete-brand parsed payload");
|
||||
String payloadJson = writeJson(entry.getValue(), "保存删品牌任务解析结果失败");
|
||||
String parsedPayloadPointer = storeParsedPayload(taskId, scopeHash, payloadJson);
|
||||
if (existing == null) {
|
||||
TaskScopeStateEntity entity = new TaskScopeStateEntity();
|
||||
@@ -80,7 +80,7 @@ public class DeleteBrandTaskStorageService {
|
||||
}
|
||||
}
|
||||
if (existing == null) {
|
||||
throw new BusinessException("failed to save delete-brand parsed payload");
|
||||
throw new BusinessException("保存删品牌任务解析结果失败");
|
||||
}
|
||||
transientPayloadStorageService.deleteReplacedPayloadIfNeeded(existing.getParsedPayloadJson(), parsedPayloadPointer);
|
||||
taskScopeStateMapper.update(null, new LambdaUpdateWrapper<TaskScopeStateEntity>()
|
||||
@@ -115,7 +115,7 @@ public class DeleteBrandTaskStorageService {
|
||||
try {
|
||||
result.put(state.getScopeKey(), objectMapper.readValue(payloadJson, DeleteBrandParsedFileCacheDto.class));
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("failed to load delete-brand parsed payload");
|
||||
throw new BusinessException("读取删品牌任务解析结果失败");
|
||||
}
|
||||
}
|
||||
return result;
|
||||
@@ -146,14 +146,14 @@ public class DeleteBrandTaskStorageService {
|
||||
@Transactional
|
||||
public boolean storeResultChunkIfChanged(Long taskId, String scopeKey, Integer chunkIndex, DeleteBrandResultFileDto chunk) {
|
||||
if (taskId == null || taskId <= 0) {
|
||||
throw new BusinessException("taskId is invalid");
|
||||
throw new BusinessException("任务 id 不合法");
|
||||
}
|
||||
if (chunkIndex == null || chunkIndex <= 0) {
|
||||
throw new BusinessException("chunkIndex is invalid");
|
||||
throw new BusinessException("分片序号不合法");
|
||||
}
|
||||
String normalizedScopeKey = normalizeScopeKey(scopeKey);
|
||||
if (normalizedScopeKey.isBlank()) {
|
||||
throw new BusinessException("scopeKey must not be blank");
|
||||
throw new BusinessException("范围标识不能为空");
|
||||
}
|
||||
String scopeHash = hash(normalizedScopeKey);
|
||||
String payloadJson = writeJson(chunk, "failed to save delete-brand result chunk");
|
||||
@@ -244,7 +244,7 @@ public class DeleteBrandTaskStorageService {
|
||||
} catch (Exception ex) {
|
||||
log.warn("[delete-brand-storage] failed to load result chunk taskId={} scopeKey={} chunkIndex={} payload={}",
|
||||
taskId, entity.getScopeKey(), entity.getChunkIndex(), entity.getPayloadJson(), ex);
|
||||
throw new BusinessException("failed to load delete-brand result chunks: taskId="
|
||||
throw new BusinessException("读取删品牌任务结果分片失败: taskId="
|
||||
+ taskId + ", scopeKey=" + entity.getScopeKey() + ", chunkIndex=" + entity.getChunkIndex());
|
||||
}
|
||||
}
|
||||
@@ -417,9 +417,9 @@ public class DeleteBrandTaskStorageService {
|
||||
|
||||
private String resolveParsedPayload(String value) {
|
||||
try {
|
||||
return transientPayloadStorageService.resolvePayload(value, "failed to load delete-brand parsed payload");
|
||||
return transientPayloadStorageService.resolvePayload(value, "读取删品牌任务解析结果失败");
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("failed to load delete-brand parsed payload");
|
||||
throw new BusinessException("读取删品牌任务解析结果失败");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+3
-2
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.digitalhuman.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
@@ -96,7 +97,7 @@ public class DigitalHumanVersionService {
|
||||
return toVo(entity);
|
||||
} catch (IOException e) {
|
||||
log.error("上传数字人版本失败", e);
|
||||
throw new BusinessException("文件处理失败:" + e.getMessage());
|
||||
throw new BusinessException(UserMessages.with("文件处理失败", e));
|
||||
} catch (RuntimeException e) {
|
||||
log.error("[digital-human-version] upload failed version={} filename={} elapsedMs={} err={}",
|
||||
version, originalFilename, elapsedMs(startedAt), e.getMessage(), e);
|
||||
@@ -277,7 +278,7 @@ public class DigitalHumanVersionService {
|
||||
BigInteger bigInt = new BigInteger(1, digest);
|
||||
return bigInt.toString(16).toLowerCase();
|
||||
} catch (Exception e) {
|
||||
throw new BusinessException("计算 MD5 失败:" + e.getMessage());
|
||||
throw new BusinessException(UserMessages.with("计算 MD5 失败", e));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.imagevideo.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
@@ -204,7 +205,7 @@ public class ImageVideoAdminTaskService {
|
||||
deleteQuietly(zipFile);
|
||||
throw ex instanceof BusinessException business
|
||||
? business
|
||||
: new BusinessException("批量打包失败: " + messageOf(ex), ex);
|
||||
: new BusinessException(UserMessages.with("批量打包失败", ex), ex);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+9
-9
@@ -124,7 +124,7 @@ public class ImageVideoAsyncTaskService {
|
||||
.eq(ImageVideoAsyncTaskEntity::getId, taskId)
|
||||
.eq(ImageVideoAsyncTaskEntity::getUserId, userId));
|
||||
if (task == null) {
|
||||
throw new BusinessException("Image video task not found");
|
||||
throw new BusinessException("图像视频任务不存在");
|
||||
}
|
||||
ensureTaskOwnedByCurrentInstance(task, "query async task");
|
||||
task = recoverFalseFailedTask(task);
|
||||
@@ -260,7 +260,7 @@ public class ImageVideoAsyncTaskService {
|
||||
|
||||
private ImageVideoAsyncTaskVo submit(TaskType type, Long userId, Object payload) {
|
||||
if (userId == null || userId <= 0) {
|
||||
throw new BusinessException("userId is required");
|
||||
throw new BusinessException("缺少用户 id");
|
||||
}
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
ImageVideoAsyncTaskEntity task = new ImageVideoAsyncTaskEntity();
|
||||
@@ -330,7 +330,7 @@ public class ImageVideoAsyncTaskService {
|
||||
task.setResultJson(writeJson(result));
|
||||
String businessError = resolveCozeBusinessError(result);
|
||||
failTask(task, new BusinessException(businessError.isBlank()
|
||||
? "Coze workflow finished with status " + cozeStatus
|
||||
? "Coze 工作流已结束,状态 " + cozeStatus
|
||||
: businessError));
|
||||
} else {
|
||||
completeTask(task, transformResult(type, result), cozeStatus);
|
||||
@@ -338,7 +338,7 @@ public class ImageVideoAsyncTaskService {
|
||||
return;
|
||||
}
|
||||
if (pollingDeadlineExceeded(task)) {
|
||||
failTask(task, new BusinessException("Coze task exceeded the one-hour polling limit"));
|
||||
failTask(task, new BusinessException("Coze 任务轮询已超过一小时上限"));
|
||||
return;
|
||||
}
|
||||
task.setStatus(TaskStatus.WAITING.name());
|
||||
@@ -348,7 +348,7 @@ public class ImageVideoAsyncTaskService {
|
||||
} catch (Exception ex) {
|
||||
// Coze history calls are retried by the next polling cycle until the task's overall deadline.
|
||||
if (pollingDeadlineExceeded(task)) {
|
||||
failTask(task, new BusinessException("Coze task exceeded the one-hour polling limit", ex));
|
||||
failTask(task, new BusinessException("Coze 任务轮询已超过一小时上限", ex));
|
||||
return;
|
||||
}
|
||||
task.setStatus(TaskStatus.WAITING.name());
|
||||
@@ -423,7 +423,7 @@ public class ImageVideoAsyncTaskService {
|
||||
if (requiresVideoResult(task) && !hasFinalVideoUrl(result)) {
|
||||
task.setCozeStatus(normalizeStatus(cozeStatus));
|
||||
task.setResultJson(writeJson(result));
|
||||
failTask(task, new BusinessException("Coze workflow succeeded but video_url is empty"));
|
||||
failTask(task, new BusinessException("Coze 工作流成功但没有返回视频地址"));
|
||||
return;
|
||||
}
|
||||
task.setStatus(TaskStatus.SUCCESS.name());
|
||||
@@ -458,7 +458,7 @@ public class ImageVideoAsyncTaskService {
|
||||
return task;
|
||||
}
|
||||
String errorMessage = task.getErrorMessage() == null ? "" : task.getErrorMessage();
|
||||
if (!errorMessage.startsWith("Coze workflow finished with status ")) {
|
||||
if (!errorMessage.startsWith("Coze 工作流已结束,状态 ")) {
|
||||
return task;
|
||||
}
|
||||
task.setStatus(TaskStatus.WAITING.name());
|
||||
@@ -490,7 +490,7 @@ public class ImageVideoAsyncTaskService {
|
||||
try {
|
||||
return objectMapper.readValue(json, type);
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("Image video task payload is invalid", ex);
|
||||
throw new BusinessException("图像视频任务参数不合法", ex);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -509,7 +509,7 @@ public class ImageVideoAsyncTaskService {
|
||||
try {
|
||||
return objectMapper.writeValueAsString(value);
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("Image video task serialization failed", ex);
|
||||
throw new BusinessException("图像视频任务序列化失败", ex);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+9
-8
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.imagevideo.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
@@ -209,7 +210,7 @@ public class ImageVideoCozeService {
|
||||
public Map<String, Object> getWorkflowResult(Long userId, String workflowId, String executeId) {
|
||||
String resolvedExecuteId = firstNonBlank(executeId);
|
||||
if (!hasText(resolvedExecuteId)) {
|
||||
throw new BusinessException("execute_id cannot be blank");
|
||||
throw new BusinessException("任务执行 id 不能为空");
|
||||
}
|
||||
ImageVideoSecretService.ResolvedSecret secret = secretService.requireValid(userId);
|
||||
String cozeToken = firstNonBlank(secret.cozeToken());
|
||||
@@ -255,7 +256,7 @@ public class ImageVideoCozeService {
|
||||
vo.setMediaType(mediaType);
|
||||
return vo;
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("媒体上传失败: " + ex.getMessage(), ex);
|
||||
throw new BusinessException(UserMessages.with("媒体上传失败", ex), ex);
|
||||
} finally {
|
||||
if (tempFile != null && tempFile.exists() && !tempFile.delete()) {
|
||||
log.warn("[image-video] temp media delete failed path={}", tempFile.getAbsolutePath());
|
||||
@@ -314,7 +315,7 @@ public class ImageVideoCozeService {
|
||||
String resolvedT8Key = firstNonBlank(t8Key);
|
||||
String cozeToken = firstNonBlank(token);
|
||||
if (!hasText(resolvedT8Key)) {
|
||||
throw new BusinessException("image-video douyin copy t8_key not configured");
|
||||
throw new BusinessException("未配置抖音文案密钥 t8_key");
|
||||
}
|
||||
if (!hasText(resolvedApiKey)) {
|
||||
throw new BusinessException("图生视频抖音文案 api_key 未配置");
|
||||
@@ -408,7 +409,7 @@ public class ImageVideoCozeService {
|
||||
} catch (BusinessException ex) {
|
||||
throw ex;
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("Coze 返回解析失败: " + ex.getMessage());
|
||||
throw new BusinessException(UserMessages.with("Coze 返回解析失败", ex));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -453,7 +454,7 @@ public class ImageVideoCozeService {
|
||||
} catch (Exception ex) {
|
||||
log.warn("[image-video] parse douyin copy response failed bodyPreview={}",
|
||||
responsePreview(responseText), ex);
|
||||
throw new BusinessException("Coze 返回解析失败: " + ex.getMessage());
|
||||
throw new BusinessException(UserMessages.with("Coze 返回解析失败", ex));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -463,7 +464,7 @@ public class ImageVideoCozeService {
|
||||
} catch (BusinessException ex) {
|
||||
throw ex;
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("Coze response parse failed: " + ex.getMessage(), ex);
|
||||
throw new BusinessException(UserMessages.with("解析 Coze 响应失败", ex), ex);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -609,7 +610,7 @@ public class ImageVideoCozeService {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new BusinessException("Coze 调用被中断", ex);
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("Coze 调用失败: " + ex.getMessage(), ex);
|
||||
throw new BusinessException(UserMessages.with("Coze 调用失败", ex), ex);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -639,7 +640,7 @@ public class ImageVideoCozeService {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new BusinessException("Coze 调用被中断", ex);
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("Coze 调用失败: " + ex.getMessage(), ex);
|
||||
throw new BusinessException(UserMessages.with("Coze 调用失败", ex), ex);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.patroldelete.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.util.SxssfWorkbookWriter;
|
||||
import com.nanri.aiimage.modules.patroldelete.model.dto.PatrolDeleteCartRatioDto;
|
||||
@@ -83,7 +84,7 @@ public class PatrolDeleteExcelAssemblyService {
|
||||
writer.write(outputXlsx);
|
||||
} catch (Exception ex) {
|
||||
log.warn("[patrol-delete] write workbook failed: {}", ex.getMessage());
|
||||
throw new BusinessException("generate patrol-delete excel failed: " + ex.getMessage());
|
||||
throw new BusinessException(UserMessages.with("生成巡店删除 Excel 失败", ex));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+3
-2
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.patroldelete.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.modules.patroldelete.mapper.PatrolDeleteConditionMapper;
|
||||
@@ -232,11 +233,11 @@ public class PatrolDeleteResolveService {
|
||||
} catch (BusinessException ex) {
|
||||
item.setMatched(false);
|
||||
item.setMatchStatus("PENDING");
|
||||
item.setMatchMessage(ex.getMessage());
|
||||
item.setMatchMessage(UserMessages.orFallback(ex.getMessage(), "该行匹配失败,请稍后重试"));
|
||||
} catch (Exception ex) {
|
||||
item.setMatched(false);
|
||||
item.setMatchStatus("PENDING");
|
||||
item.setMatchMessage(Objects.toString(ex.getMessage(), "匹配异常"));
|
||||
item.setMatchMessage(UserMessages.orFallback(ex.getMessage(), "匹配异常"));
|
||||
}
|
||||
return item;
|
||||
}
|
||||
|
||||
+1
-1
@@ -491,7 +491,7 @@ public class PatrolDeleteTaskService {
|
||||
inNewTransaction(() -> {
|
||||
FileResultEntity latestEntity = fileResultMapper.selectById(resultId);
|
||||
if (latestEntity == null || !MODULE_TYPE.equals(latestEntity.getModuleType()) || !userId.equals(latestEntity.getUserId())) {
|
||||
throw new BusinessException("record not found");
|
||||
throw new BusinessException("没有找到对应记录");
|
||||
}
|
||||
fileResultMapper.deleteById(resultId);
|
||||
cleanupResultAuxiliaryDataFast(taskId, resultId);
|
||||
|
||||
+2
-2
@@ -643,7 +643,7 @@ public class PermissionMenuService {
|
||||
.filter(user -> user.getId() != null && !isSuperAdmin(user))
|
||||
.collect(Collectors.toMap(AdminUserEntity::getId, Function.identity(), (left, right) -> left));
|
||||
if (requestedIds.stream().anyMatch(id -> !grantableUsers.containsKey(id))) {
|
||||
throw new BusinessException("contains unknown or non-grantable user");
|
||||
throw new BusinessException("包含不存在或不可授权的用户");
|
||||
}
|
||||
userColumnPermissionMapper.deleteByColumnId(dataPermission.getId());
|
||||
for (Long userId : requestedIds) {
|
||||
@@ -698,7 +698,7 @@ public class PermissionMenuService {
|
||||
.filter(user -> user.getId() != null && !isSuperAdmin(user))
|
||||
.collect(Collectors.toMap(AdminUserEntity::getId, Function.identity(), (left, right) -> left));
|
||||
if (requestedIds.stream().anyMatch(id -> !grantableUsers.containsKey(id))) {
|
||||
throw new BusinessException("contains unknown or non-grantable user");
|
||||
throw new BusinessException("包含不存在或不可授权的用户");
|
||||
}
|
||||
userColumnPermissionMapper.deleteByColumnId(dataPermission.getId());
|
||||
for (Long userId : requestedIds) {
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.pricetrack.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.util.SxssfWorkbookWriter;
|
||||
import com.nanri.aiimage.modules.pricetrack.model.dto.PriceTrackSubmitResultRequest;
|
||||
@@ -71,7 +72,7 @@ public class PriceTrackExcelAssemblyService {
|
||||
writer.write(outputXlsx);
|
||||
} catch (Exception ex) {
|
||||
log.warn("[price-track] write workbook failed: {}", ex.getMessage());
|
||||
throw new BusinessException("generate price-track excel failed: " + ex.getMessage());
|
||||
throw new BusinessException(UserMessages.with("生成跟价 Excel 失败", ex));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+3
-2
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.pricetrack.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
@@ -238,11 +239,11 @@ public class PriceTrackService {
|
||||
} catch (BusinessException ex) {
|
||||
item.setMatched(false);
|
||||
item.setMatchStatus("PENDING");
|
||||
item.setMatchMessage(ex.getMessage());
|
||||
item.setMatchMessage(UserMessages.orFallback(ex.getMessage(), "该行匹配失败,请稍后重试"));
|
||||
} catch (Exception ex) {
|
||||
item.setMatched(false);
|
||||
item.setMatchStatus("PENDING");
|
||||
item.setMatchMessage(Objects.toString(ex.getMessage(), "匹配异常"));
|
||||
item.setMatchMessage(UserMessages.orFallback(ex.getMessage(), "匹配异常"));
|
||||
}
|
||||
return item;
|
||||
}
|
||||
|
||||
+7
-6
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.pricetrack.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
@@ -240,7 +241,7 @@ public class PriceTrackTaskService {
|
||||
inNewTransaction(() -> {
|
||||
FileResultEntity latestEntity = fileResultMapper.selectById(resultId);
|
||||
if (latestEntity == null || !MODULE_TYPE.equals(latestEntity.getModuleType()) || !userId.equals(latestEntity.getUserId())) {
|
||||
throw new BusinessException("record not found");
|
||||
throw new BusinessException("没有找到对应记录");
|
||||
}
|
||||
fileResultMapper.deleteById(resultId);
|
||||
reconcileTaskAfterResultRemoval(taskId);
|
||||
@@ -1245,7 +1246,7 @@ public class PriceTrackTaskService {
|
||||
} catch (BusinessException ex) {
|
||||
throw ex;
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("任务请求参数解析失败: " + ex.getMessage());
|
||||
throw new BusinessException(UserMessages.with("任务请求参数解析失败", ex));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1569,7 +1570,7 @@ public class PriceTrackTaskService {
|
||||
mergeCountryRows(merged, parseWorkbookAsinRows(file, countryCodes));
|
||||
continue;
|
||||
}
|
||||
throw new BusinessException("Unsupported ASIN file type: " + file.getName());
|
||||
throw new BusinessException("不支持的 ASIN 文件类型: " + file.getName());
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
@@ -1626,14 +1627,14 @@ public class PriceTrackTaskService {
|
||||
} catch (BusinessException ex) {
|
||||
throw ex;
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("Failed to parse ASIN workbook");
|
||||
throw new BusinessException("解析 ASIN 表格失败");
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private Map<String, List<Map<String, String>>> parseCsvAsinRows(File file, List<String> countryCodes) {
|
||||
if (countryCodes == null || countryCodes.size() != 1) {
|
||||
throw new BusinessException("CSV ASIN file requires exactly one selected country");
|
||||
throw new BusinessException("CSV 格式的 ASIN 文件只能选择一个国家");
|
||||
}
|
||||
Map<String, List<Map<String, String>>> out = new LinkedHashMap<>();
|
||||
List<Map<String, String>> rows = out.computeIfAbsent(countryCodes.get(0), key -> new ArrayList<>());
|
||||
@@ -1655,7 +1656,7 @@ public class PriceTrackTaskService {
|
||||
} catch (BusinessException ex) {
|
||||
throw ex;
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("Failed to parse ASIN csv");
|
||||
throw new BusinessException("解析 ASIN CSV 失败");
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.productrisk.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.util.SxssfWorkbookWriter;
|
||||
import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskRowDto;
|
||||
@@ -90,7 +91,7 @@ public class ProductRiskExcelAssemblyService {
|
||||
throw ex;
|
||||
} catch (Exception ex) {
|
||||
log.warn("[product-risk] write workbook failed: {}", ex.getMessage());
|
||||
throw new BusinessException("generate product-risk excel failed: " + ex.getMessage());
|
||||
throw new BusinessException(UserMessages.with("生成产品风险 Excel 失败", ex));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+3
-2
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.productrisk.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
@@ -273,11 +274,11 @@ public class ProductRiskResolveService {
|
||||
} catch (BusinessException ex) {
|
||||
item.setMatched(false);
|
||||
item.setMatchStatus("PENDING");
|
||||
item.setMatchMessage(ex.getMessage());
|
||||
item.setMatchMessage(UserMessages.orFallback(ex.getMessage(), "该行匹配失败,请稍后重试"));
|
||||
} catch (Exception ex) {
|
||||
item.setMatched(false);
|
||||
item.setMatchStatus("PENDING");
|
||||
item.setMatchMessage(Objects.toString(ex.getMessage(), "匹配异常"));
|
||||
item.setMatchMessage(UserMessages.orFallback(ex.getMessage(), "匹配异常"));
|
||||
}
|
||||
return item;
|
||||
}
|
||||
|
||||
+1
-1
@@ -232,7 +232,7 @@ public class ProductRiskTaskService {
|
||||
inNewTransaction(() -> {
|
||||
FileResultEntity latestEntity = fileResultMapper.selectById(resultId);
|
||||
if (latestEntity == null || !MODULE_TYPE.equals(latestEntity.getModuleType()) || !userId.equals(latestEntity.getUserId())) {
|
||||
throw new BusinessException("record not found");
|
||||
throw new BusinessException("没有找到对应记录");
|
||||
}
|
||||
taskFileJobService.deleteResultJobs(latestEntity.getTaskId(), MODULE_TYPE, latestEntity.getId());
|
||||
fileResultMapper.deleteById(resultId);
|
||||
|
||||
+7
-7
@@ -320,7 +320,7 @@ public class PublishTaskService {
|
||||
|
||||
public void submitResult(Long taskId, PublishSubmitResultRequest request) {
|
||||
if (request == null || request.getFiles() == null || request.getFiles().isEmpty()) {
|
||||
throw new BusinessException("files cannot be empty");
|
||||
throw new BusinessException("文件列表不能为空");
|
||||
}
|
||||
if (request.getUserId() != null && request.getUserId() <= 0) {
|
||||
throw new BusinessException("user_id 不合法");
|
||||
@@ -328,7 +328,7 @@ public class PublishTaskService {
|
||||
try (TaskDistributedLockService.LockHandle lock =
|
||||
taskDistributedLockService.acquire(MODULE_TYPE, taskId)) {
|
||||
if (lock == null) {
|
||||
throw new BusinessException("task lock is busy");
|
||||
throw new BusinessException("任务正被占用,请稍后重试");
|
||||
}
|
||||
List<String> uploadedPayloads = new ArrayList<>();
|
||||
PreparedResultSubmission prepared;
|
||||
@@ -534,17 +534,17 @@ public class PublishTaskService {
|
||||
|
||||
public void processResultFileJob(TaskFileJobEntity job) {
|
||||
if (job == null || job.getTaskId() == null || job.getResultId() == null) {
|
||||
throw new BusinessException("result file job arguments are incomplete");
|
||||
throw new BusinessException("结果文件作业参数不完整");
|
||||
}
|
||||
FileTaskEntity task = fileTaskMapper.selectById(job.getTaskId());
|
||||
if (task == null || !MODULE_TYPE.equals(task.getModuleType())) {
|
||||
throw new BusinessException("task not found");
|
||||
throw new BusinessException("任务不存在");
|
||||
}
|
||||
ensureTaskOwnedByCurrentInstance(task, "process publish result file");
|
||||
FileResultEntity result = fileResultMapper.selectById(job.getResultId());
|
||||
if (result == null || !MODULE_TYPE.equals(result.getModuleType())
|
||||
|| !task.getId().equals(result.getTaskId())) {
|
||||
throw new BusinessException("result record not found");
|
||||
throw new BusinessException("结果记录不存在");
|
||||
}
|
||||
|
||||
File workDirectory = FileUtil.mkdir(FileUtil.file(System.getProperty("java.io.tmpdir"),
|
||||
@@ -556,7 +556,7 @@ public class PublishTaskService {
|
||||
.toList();
|
||||
if (successfulFiles.isEmpty()) {
|
||||
markTaskAndResultFailed(task, result, "没有成功文件,无法生成结果");
|
||||
throw new BusinessException("no successful publish files");
|
||||
throw new BusinessException("没有发布成功的文件");
|
||||
}
|
||||
|
||||
TaskOptions options = readTaskOptions(task);
|
||||
@@ -1334,7 +1334,7 @@ public class PublishTaskService {
|
||||
throw new BusinessException("请先上传 Excel 文件");
|
||||
}
|
||||
if (request.getPublishCountry() == null || request.getPublishCountry().isBlank()) {
|
||||
throw new BusinessException("publish_country cannot be blank");
|
||||
throw new BusinessException("发布国家不能为空");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.queryasin.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.util.SxssfWorkbookWriter;
|
||||
import com.nanri.aiimage.modules.queryasin.model.dto.QueryAsinAsinStatusDto;
|
||||
@@ -68,7 +69,7 @@ public class QueryAsinExcelAssemblyService {
|
||||
writer.write(outputXlsx);
|
||||
} catch (Exception ex) {
|
||||
log.warn("[query-asin] write workbook failed: {}", ex.getMessage());
|
||||
throw new BusinessException("生成查询 ASIN Excel 失败: " + ex.getMessage());
|
||||
throw new BusinessException(UserMessages.with("生成查询 ASIN Excel 失败", ex));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+3
-2
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.queryasin.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskCandidateAddRequest;
|
||||
@@ -211,11 +212,11 @@ public class QueryAsinResolveService {
|
||||
} catch (BusinessException ex) {
|
||||
item.setMatched(false);
|
||||
item.setMatchStatus("PENDING");
|
||||
item.setMatchMessage(ex.getMessage());
|
||||
item.setMatchMessage(UserMessages.orFallback(ex.getMessage(), "该行匹配失败,请稍后重试"));
|
||||
} catch (Exception ex) {
|
||||
item.setMatched(false);
|
||||
item.setMatchStatus("PENDING");
|
||||
item.setMatchMessage(Objects.toString(ex.getMessage(), "匹配异常"));
|
||||
item.setMatchMessage(UserMessages.orFallback(ex.getMessage(), "匹配异常"));
|
||||
}
|
||||
return item;
|
||||
}
|
||||
|
||||
+1
-1
@@ -479,7 +479,7 @@ public class QueryAsinTaskService {
|
||||
inNewTransaction(() -> {
|
||||
FileResultEntity latestEntity = fileResultMapper.selectById(resultId);
|
||||
if (latestEntity == null || !MODULE_TYPE.equals(latestEntity.getModuleType()) || !userId.equals(latestEntity.getUserId())) {
|
||||
throw new BusinessException("record not found");
|
||||
throw new BusinessException("没有找到对应记录");
|
||||
}
|
||||
fileResultMapper.deleteById(resultId);
|
||||
reconcileTaskAfterResultRemoval(taskId);
|
||||
|
||||
+4
-3
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.shopdatacrawl.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.modules.shopdatacrawl.model.dto.ShopDataCrawlRowDto;
|
||||
import com.nanri.aiimage.modules.shopdatacrawl.model.vo.ShopDataCrawlResultItemVo;
|
||||
@@ -111,7 +112,7 @@ public class ShopDataCrawlExcelAssemblyService {
|
||||
} catch (BusinessException ex) {
|
||||
throw ex;
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("生成店铺数据抓取 Excel 失败: " + ex.getMessage());
|
||||
throw new BusinessException(UserMessages.with("生成店铺数据抓取 Excel 失败", ex));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -146,7 +147,7 @@ public class ShopDataCrawlExcelAssemblyService {
|
||||
} catch (BusinessException ex) {
|
||||
throw ex;
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("店铺数据抓取累计 Excel 按国家替换失败: " + ex.getMessage());
|
||||
throw new BusinessException(UserMessages.with("店铺数据抓取累计 Excel 按国家替换失败", ex));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -184,7 +185,7 @@ public class ShopDataCrawlExcelAssemblyService {
|
||||
} catch (BusinessException ex) {
|
||||
throw ex;
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("生成店铺数据抓取流式 Excel 失败: " + ex.getMessage());
|
||||
throw new BusinessException(UserMessages.with("生成店铺数据抓取流式 Excel 失败", ex));
|
||||
} finally {
|
||||
workbook.dispose();
|
||||
}
|
||||
|
||||
+3
-2
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.shopdatacrawl.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
@@ -302,11 +303,11 @@ public class ShopDataCrawlResolveService {
|
||||
} catch (BusinessException ex) {
|
||||
item.setMatched(false);
|
||||
item.setMatchStatus("PENDING");
|
||||
item.setMatchMessage(ex.getMessage());
|
||||
item.setMatchMessage(UserMessages.orFallback(ex.getMessage(), "该行匹配失败,请稍后重试"));
|
||||
} catch (Exception ex) {
|
||||
item.setMatched(false);
|
||||
item.setMatchStatus("PENDING");
|
||||
item.setMatchMessage(Objects.toString(ex.getMessage(), "匹配异常"));
|
||||
item.setMatchMessage(UserMessages.orFallback(ex.getMessage(), "匹配异常"));
|
||||
}
|
||||
return item;
|
||||
}
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.shopduplicatecheck.controller;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.util.DownloadHeaderUtil;
|
||||
@@ -272,7 +273,7 @@ public class AdminShopDataDuplicateCheckController {
|
||||
throw ex;
|
||||
} catch (Exception ex) {
|
||||
log.error("[shop-duplicate-check-import] 导入端点异常 operator_id={}", operator.id(), ex);
|
||||
throw new BusinessException(500, "导入失败:" + (ex.getMessage() == null ? "未知错误" : ex.getMessage()));
|
||||
throw new BusinessException(500, UserMessages.with("导入失败", ex));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.shopduplicatecheck.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.service.DistributedJobLockService;
|
||||
@@ -73,7 +74,7 @@ public class ShopDataDuplicateCheckImportService {
|
||||
rows = DuplicateCheckWorkbookParser.parse(bytes);
|
||||
} catch (Exception ex) {
|
||||
log.warn("[shop-duplicate-check-import] 解析导入 Excel 失败 shop={} msg={}", name, ex.getMessage());
|
||||
throw new BusinessException(400, "Excel 解析失败:" + (ex.getMessage() == null ? "格式错误" : ex.getMessage()));
|
||||
throw new BusinessException(400, UserMessages.with("Excel 解析失败", ex));
|
||||
}
|
||||
if (rows.isEmpty()) {
|
||||
throw new BusinessException(400, "Excel 中未读取到 ASIN 数据(需包含 ASIN 列)");
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.shopduplicatecheck.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
@@ -223,7 +224,7 @@ public class ShopDataDuplicateCheckScanService implements DuplicateCheckRefreshP
|
||||
row.setSummaryJson(objectMapper.writeValueAsString(aggregate.summary()));
|
||||
row.setPayloadJson(objectMapper.writeValueAsString(aggregate.payload()));
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("扫描结果序列化失败: " + ex.getMessage(), ex);
|
||||
throw new BusinessException(UserMessages.with("扫描结果序列化失败", ex), ex);
|
||||
}
|
||||
scanMapper.insert(row);
|
||||
log.info("[shop-duplicate-check] 扫描完成 落库行 id={} 店铺数={} ASIN数={} 记录数={}",
|
||||
|
||||
+3
-2
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.shopkey.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
|
||||
import cn.hutool.core.util.IdUtil;
|
||||
@@ -443,8 +444,8 @@ public class QueryAsinService {
|
||||
progress.setStatus("success");
|
||||
} catch (Exception ex) {
|
||||
progress.setStatus("failed");
|
||||
progress.setErrorMessage(ex instanceof BusinessException ? ex.getMessage()
|
||||
: (deleteMode ? "导入删除 Excel 失败" : "导入添加 Excel 失败"));
|
||||
progress.setErrorMessage(UserMessages.orFallback(ex.getMessage(),
|
||||
deleteMode ? "导入删除 Excel 失败" : "导入添加 Excel 失败"));
|
||||
} finally {
|
||||
deleteQuietly(tempFile);
|
||||
completedImportAtMap.put(importId, System.currentTimeMillis());
|
||||
|
||||
+4
-3
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.shopkey.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
@@ -522,8 +523,8 @@ public class SkipPriceAsinService {
|
||||
log.warn("[skip-price-asin-import] failed importId={} deleteMode={} msg={}",
|
||||
importId, deleteMode, ex.getMessage());
|
||||
progress.setStatus("failed");
|
||||
progress.setErrorMessage(ex instanceof BusinessException ? ex.getMessage()
|
||||
: (deleteMode ? "导入删除 Excel 失败" : "导入新增 Excel 失败"));
|
||||
progress.setErrorMessage(UserMessages.orFallback(ex.getMessage(),
|
||||
deleteMode ? "导入删除 Excel 失败" : "导入新增 Excel 失败"));
|
||||
} finally {
|
||||
deleteQuietly(tempFile);
|
||||
completedImportAtMap.put(importId, System.currentTimeMillis());
|
||||
@@ -1414,7 +1415,7 @@ public class SkipPriceAsinService {
|
||||
case "ES" -> query.select(SkipPriceAsinEntity::getId, SkipPriceAsinEntity::getAsinEs,
|
||||
SkipPriceAsinEntity::getMinimumPriceEs)
|
||||
.eq(SkipPriceAsinEntity::getAsinEs, asin);
|
||||
default -> throw new BusinessException("unsupported country: " + country);
|
||||
default -> throw new BusinessException("不支持的国家: " + country);
|
||||
}
|
||||
return skipPriceAsinMapper.selectOne(query.last("LIMIT 1"));
|
||||
}
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.shopmatch.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.util.SxssfWorkbookWriter;
|
||||
import com.nanri.aiimage.modules.productrisk.model.enums.ProductRiskCountryCode;
|
||||
@@ -39,7 +40,7 @@ public class ShopMatchExcelAssemblyService {
|
||||
writer.write(outputXlsx);
|
||||
} catch (Exception ex) {
|
||||
log.warn("[shop-match] write workbook failed: {}", ex.getMessage());
|
||||
throw new BusinessException("generate shop-match excel failed: " + ex.getMessage());
|
||||
throw new BusinessException(UserMessages.with("生成店铺匹配 Excel 失败", ex));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+3
-2
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.shopmatch.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
@@ -211,11 +212,11 @@ public class ShopMatchResolveService {
|
||||
} catch (BusinessException ex) {
|
||||
item.setMatched(false);
|
||||
item.setMatchStatus("PENDING");
|
||||
item.setMatchMessage(ex.getMessage());
|
||||
item.setMatchMessage(UserMessages.orFallback(ex.getMessage(), "该行匹配失败,请稍后重试"));
|
||||
} catch (Exception ex) {
|
||||
item.setMatched(false);
|
||||
item.setMatchStatus("PENDING");
|
||||
item.setMatchMessage(Objects.toString(ex.getMessage(), "匹配异常"));
|
||||
item.setMatchMessage(UserMessages.orFallback(ex.getMessage(), "匹配异常"));
|
||||
}
|
||||
return item;
|
||||
}
|
||||
|
||||
+1
-1
@@ -307,7 +307,7 @@ public class ShopMatchTaskService {
|
||||
inNewTransaction(() -> {
|
||||
FileResultEntity latestEntity = fileResultMapper.selectById(resultId);
|
||||
if (latestEntity == null || !MODULE_TYPE.equals(latestEntity.getModuleType()) || !userId.equals(latestEntity.getUserId())) {
|
||||
throw new BusinessException("record not found");
|
||||
throw new BusinessException("没有找到对应记录");
|
||||
}
|
||||
fileResultMapper.deleteById(resultId);
|
||||
reconcileTaskAfterResultRemoval(taskId);
|
||||
|
||||
+5
-5
@@ -1519,12 +1519,12 @@ public class SimilarAsinTaskService implements SimilarAsinPipelineHost {
|
||||
int totalProgressUnits,
|
||||
int llmWorkUnits) {
|
||||
if (pipelineSupport().countPendingLlmStates(task.getId()) > 0) {
|
||||
throw new BusinessException("LLM result is still processing, cannot generate result file yet");
|
||||
throw new BusinessException("LLM 检测还没全部回流,暂时不能生成结果文件");
|
||||
}
|
||||
int assembleProgress = Math.max(1, Math.min(totalProgressUnits - 2, llmWorkUnits));
|
||||
progressSupport().saveFileBuildProgress(task, job, totalProgressUnits, assembleProgress, "Assembling xlsx");
|
||||
progressSupport().saveFileBuildProgress(task, job, totalProgressUnits, assembleProgress, "正在生成结果文件");
|
||||
resultAssembler().assembleResultWorkbook(task, result);
|
||||
progressSupport().saveFileBuildProgress(task, job, totalProgressUnits, totalProgressUnits - 1, "Uploading result file");
|
||||
progressSupport().saveFileBuildProgress(task, job, totalProgressUnits, totalProgressUnits - 1, "正在上传结果文件");
|
||||
fileResultMapper.updateById(result);
|
||||
boolean taskAlreadyFailed = STATUS_FAILED.equals(task.getStatus())
|
||||
|| (task.getErrorMessage() != null && !task.getErrorMessage().isBlank());
|
||||
@@ -1537,7 +1537,7 @@ public class SimilarAsinTaskService implements SimilarAsinPipelineHost {
|
||||
task.setFinishedAt(LocalDateTime.now());
|
||||
fileTaskMapper.updateById(task);
|
||||
taskCacheService.deleteTaskCache(task.getId());
|
||||
progressSupport().saveFileBuildProgress(task, job, totalProgressUnits, totalProgressUnits, "Result file generated");
|
||||
progressSupport().saveFileBuildProgress(task, job, totalProgressUnits, totalProgressUnits, "结果文件已生成");
|
||||
// P1-1:异步 assemble 完成 → task 进入 SUCCESS/FAILED 终态,清理滑窗记录避免内存泄漏。
|
||||
poisonTracker.clear(task.getId());
|
||||
}
|
||||
@@ -1638,7 +1638,7 @@ public class SimilarAsinTaskService implements SimilarAsinPipelineHost {
|
||||
throw new BusinessException(FailedStatusRowFilter.noMatchedRowsMessage());
|
||||
}
|
||||
if (allRows.isEmpty()) {
|
||||
throw new BusinessException("no valid similar ASIN rows");
|
||||
throw new BusinessException("没有解析到可检测的货源行,请检查表格的 id / ASIN / 国家 列");
|
||||
}
|
||||
return new ParsedWorkbook(total, dropped, headers, allRows, categoryRetryRequired);
|
||||
} catch (BusinessException ex) {
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.similarasin.service.support;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.modules.similarasin.model.dto.SimilarAsinResultRowDto;
|
||||
@@ -126,7 +127,7 @@ public final class SimilarAsinChunkMergeSupport {
|
||||
.orderByAsc("id")
|
||||
.last("limit " + batch));
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("chunk keyset 分页查询失败: " + ex.getMessage(), ex);
|
||||
throw new BusinessException(UserMessages.with("分片键集 分页查询失败", ex), ex);
|
||||
}
|
||||
if (page == null || page.isEmpty()) {
|
||||
break;
|
||||
|
||||
+19
-3
@@ -1,5 +1,7 @@
|
||||
package com.nanri.aiimage.modules.similarasin.service.support;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import cn.hutool.crypto.digest.DigestUtil;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
@@ -99,8 +101,8 @@ public class SimilarAsinChunkPayloadSupport {
|
||||
log.warn("[similar-asin] read chunk payload failed taskId={} chunk={} crossInstance={} err={}",
|
||||
chunk.getTaskId(), chunk.getChunkIndex(), crossInstance, msg);
|
||||
recordChunkReadFailure(chunk, crossInstance, msg);
|
||||
throw new BusinessException("similar ASIN chunk payload read failed chunk="
|
||||
+ chunk.getChunkIndex() + ": " + msg, ex);
|
||||
throw new BusinessException(UserMessages.with("读取货源查询结果分片失败,分片="
|
||||
+ chunk.getChunkIndex(), msg), ex);
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
@@ -141,7 +143,21 @@ public class SimilarAsinChunkPayloadSupport {
|
||||
from = end + 1;
|
||||
}
|
||||
}
|
||||
return String.join(", ", tags);
|
||||
if (tags.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
List<String> readable = new ArrayList<>();
|
||||
for (String tag : tags) {
|
||||
int open = tag.indexOf('[');
|
||||
String body = open < 0 ? tag : tag.substring(open + 1, tag.length() - 1);
|
||||
boolean cross = body.endsWith("@cross-instance");
|
||||
if (cross) {
|
||||
body = body.substring(0, body.length() - "@cross-instance".length());
|
||||
}
|
||||
readable.add(cross ? "第 " + body + " 分片跨实例读取失败"
|
||||
: "第 " + body + " 分片读取失败");
|
||||
}
|
||||
return String.join(";", readable);
|
||||
} catch (Exception ex) {
|
||||
log.warn("[similar-asin] collect chunk-read-failure summary failed taskId={} err={}", taskId, ex.getMessage());
|
||||
return "";
|
||||
|
||||
+4
-3
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.similarasin.service.support;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
@@ -197,7 +198,7 @@ public class SimilarAsinHistoryAssembler {
|
||||
vo.setFileProgressCurrent(current);
|
||||
vo.setFileProgressTotal(total);
|
||||
vo.setFileProgressPercent(percent);
|
||||
vo.setFileProgressMessage(snapshot.getMessage());
|
||||
vo.setFileProgressMessage(UserMessages.orFallback(snapshot.getMessage(), ""));
|
||||
}
|
||||
|
||||
private void attachLlmProgress(SimilarAsinHistoryItemVo vo,
|
||||
@@ -412,8 +413,8 @@ public class SimilarAsinHistoryAssembler {
|
||||
log.warn("[similar-asin] read chunk payload failed taskId={} chunk={} crossInstance={} err={}",
|
||||
chunk.getTaskId(), chunk.getChunkIndex(), crossInstance, msg);
|
||||
recordChunkReadFailure(chunk, crossInstance, msg);
|
||||
throw new BusinessException("similar ASIN chunk payload read failed chunk="
|
||||
+ chunk.getChunkIndex() + ": " + msg, ex);
|
||||
throw new BusinessException(UserMessages.with("读取货源查询结果分片失败,分片="
|
||||
+ chunk.getChunkIndex(), msg), ex);
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
+3
-2
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.similarasin.service.support;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import cn.hutool.crypto.digest.DigestUtil;
|
||||
import com.nanri.aiimage.modules.similarasin.model.dto.SimilarAsinParsedPayloadDto;
|
||||
import com.nanri.aiimage.modules.similarasin.model.dto.SimilarAsinResultGroupDto;
|
||||
@@ -1490,9 +1491,9 @@ public class SimilarAsinPipelineSupport {
|
||||
} catch (Exception ex) {
|
||||
TaskFileJobEntity job = taskFileJobService.findAssembleJob(taskId, MODULE_TYPE, context.resultId());
|
||||
if (job != null) {
|
||||
taskFileJobService.markFailed(job, firstNonBlank(ex.getMessage(), "相似ASIN结果文件生成失败"));
|
||||
taskFileJobService.markFailed(job, UserMessages.orFallback(ex.getMessage(), "相似ASIN结果文件生成失败"));
|
||||
if (taskFileJobService.isRetryExhausted(job.getId())) {
|
||||
host.finalizeExhaustedResultFileJob(job, ex.getMessage());
|
||||
host.finalizeExhaustedResultFileJob(job, UserMessages.orFallback(ex.getMessage(), "相似ASIN结果文件生成失败"));
|
||||
}
|
||||
}
|
||||
log.warn("[相似ASIN] LLM 异步收尾失败 任务ID={} 结果ID={} 错误={}",
|
||||
|
||||
+9
-9
@@ -141,12 +141,12 @@ public class SimilarAsinResultWorkbookAssembler {
|
||||
List<SourceRows> sourceRows = splitRowsBySourceFile(
|
||||
parsed, parsedRows, result.getSourceFilename());
|
||||
if (sourceRows.isEmpty()) {
|
||||
throw new BusinessException("Similar ASIN result rows are empty");
|
||||
throw new BusinessException("这份文件没有解析到可导出的行,请稍后重试生成结果文件");
|
||||
}
|
||||
|
||||
File outputDir = new File(storageProperties.getLocalTempDir(), "similar-asin-result");
|
||||
if (!outputDir.exists() && !outputDir.mkdirs()) {
|
||||
throw new BusinessException("failed to create result directory");
|
||||
throw new BusinessException("创建结果目录失败");
|
||||
}
|
||||
List<SourceResultWorkbook> workbooks = new ArrayList<>();
|
||||
List<File> workbookFiles = new ArrayList<>(sourceRows.size());
|
||||
@@ -207,20 +207,20 @@ public class SimilarAsinResultWorkbookAssembler {
|
||||
} catch (InterruptedException ex) {
|
||||
cancelResultAssemblyFutures(futures);
|
||||
Thread.currentThread().interrupt();
|
||||
throw new BusinessException("result workbook assembly interrupted", ex);
|
||||
throw new BusinessException("生成相似ASIN检测结果中断", ex);
|
||||
} catch (TimeoutException ex) {
|
||||
cancelResultAssemblyFutures(futures);
|
||||
throw new BusinessException("result workbook assembly timed out", ex);
|
||||
throw new BusinessException("生成相似ASIN检测结果超时(" + timeoutMinutes + " 分钟)", ex);
|
||||
} catch (CancellationException ex) {
|
||||
cancelResultAssemblyFutures(futures);
|
||||
throw new BusinessException("result workbook assembly cancelled", ex);
|
||||
throw new BusinessException("生成相似ASIN检测结果已取消", ex);
|
||||
} catch (ExecutionException ex) {
|
||||
cancelResultAssemblyFutures(futures);
|
||||
Throwable cause = ex.getCause();
|
||||
if (cause instanceof BusinessException businessException) {
|
||||
throw businessException;
|
||||
}
|
||||
throw new BusinessException("result workbook assembly failed", cause == null ? ex : cause);
|
||||
throw new BusinessException("生成相似ASIN检测结果失败", cause == null ? ex : cause);
|
||||
}
|
||||
|
||||
int persistedResultRows = workbooks.stream()
|
||||
@@ -242,8 +242,8 @@ public class SimilarAsinResultWorkbookAssembler {
|
||||
if (resultRows == 0) {
|
||||
String failureSummary = chunkPayloadSupport.collectChunkReadFailureSummary(task.getId());
|
||||
throw new BusinessException(failureSummary.isBlank()
|
||||
? "Similar ASIN result rows are empty; please retry result generation"
|
||||
: "Similar ASIN result rows are empty (" + failureSummary + ")");
|
||||
? "相似ASIN检测结果为空,请稍后重试生成结果文件"
|
||||
: "相似ASIN检测结果为空(" + failureSummary + "),请稍后重试生成结果文件");
|
||||
}
|
||||
|
||||
taskImageCache.clear();
|
||||
@@ -941,7 +941,7 @@ public class SimilarAsinResultWorkbookAssembler {
|
||||
return new SimilarAsinImageEmbedder.ImageSpool(
|
||||
Files.createTempDirectory(outputDir.toPath(), "similar-asin-images-"));
|
||||
} catch (IOException ex) {
|
||||
throw new BusinessException("create Similar ASIN image spool failed", ex);
|
||||
throw new BusinessException("创建相似ASIN图片临时目录失败", ex);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -74,7 +74,7 @@ public class SimilarAsinTaskOwnershipSupport {
|
||||
public TaskDistributedLockService.LockHandle requireTaskLock(Long taskId, long waitMillis) {
|
||||
TaskDistributedLockService.LockHandle lockHandle = acquireTaskLock(taskId, waitMillis);
|
||||
if (lockHandle == null) {
|
||||
throw new BusinessException(40902, "Task is busy, please retry later");
|
||||
throw new BusinessException(40902, "任务正被占用,请稍后重试");
|
||||
}
|
||||
return lockHandle;
|
||||
}
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.softwareversion.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.modules.file.service.oss.OssStorageService;
|
||||
@@ -207,7 +208,7 @@ public class SoftwareVersionService {
|
||||
} catch (IOException e) {
|
||||
log.error("[software-version] 上传客户端软件版本文件处理失败 version={} filename={} err={}",
|
||||
normalizedVersion, originalFilename, e.getMessage(), e);
|
||||
throw new BusinessException("文件处理失败:" + e.getMessage());
|
||||
throw new BusinessException(UserMessages.with("文件处理失败", e));
|
||||
} catch (RuntimeException e) {
|
||||
log.error("[software-version] 上传客户端软件版本失败 version={} filename={} elapsedMs={} err={}",
|
||||
normalizedVersion, originalFilename, elapsedMs(startedAt), e.getMessage(), e);
|
||||
|
||||
+16
-15
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.split.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import cn.hutool.core.io.FileUtil;
|
||||
import cn.hutool.core.util.IdUtil;
|
||||
import cn.hutool.json.JSONUtil;
|
||||
@@ -81,7 +82,7 @@ public class SplitRunService {
|
||||
try {
|
||||
File inputFile = findLocalSourceFile(sourceFile.getFileKey());
|
||||
if (inputFile == null || !inputFile.exists()) {
|
||||
throw new BusinessException("Uploaded source file does not exist, please upload again.");
|
||||
throw new BusinessException("上传的源文件不存在,请重新上传。");
|
||||
}
|
||||
|
||||
String inputName = sourceFile.getOriginalFilename() == null
|
||||
@@ -97,7 +98,7 @@ public class SplitRunService {
|
||||
SplitResultItemVo item = new SplitResultItemVo();
|
||||
item.setSourceFilename(sourceFile.getOriginalFilename());
|
||||
item.setSuccess(false);
|
||||
item.setError(ex.getMessage());
|
||||
item.setError(UserMessages.orFallback(ex.getMessage(), "这个文件拆分失败,请检查内容后重新上传"));
|
||||
item.setEntries(new ArrayList<>());
|
||||
item.setEntryCount(0);
|
||||
items.add(item);
|
||||
@@ -108,7 +109,7 @@ public class SplitRunService {
|
||||
resultEntity.setModuleType(MODULE_TYPE);
|
||||
resultEntity.setSourceFilename(sourceFile.getOriginalFilename());
|
||||
resultEntity.setSuccess(0);
|
||||
resultEntity.setErrorMessage(ex.getMessage());
|
||||
resultEntity.setErrorMessage(UserMessages.orFallback(ex.getMessage(), "这个文件拆分失败,请检查内容后重新上传"));
|
||||
resultEntity.setUserId(request.getUserId());
|
||||
resultEntity.setCreatedAt(LocalDateTime.now());
|
||||
fileResultMapper.insert(resultEntity);
|
||||
@@ -224,7 +225,7 @@ public class SplitRunService {
|
||||
public void deleteHistory(Long resultId, Long userId) {
|
||||
FileResultEntity entity = fileResultMapper.selectById(resultId);
|
||||
if (entity == null || !MODULE_TYPE.equals(entity.getModuleType()) || !userId.equals(entity.getUserId())) {
|
||||
throw new BusinessException("Split result record does not exist.");
|
||||
throw new BusinessException("没有这条拆分结果。");
|
||||
}
|
||||
fileResultMapper.deleteById(resultId);
|
||||
}
|
||||
@@ -232,7 +233,7 @@ public class SplitRunService {
|
||||
public String getResultDownloadUrl(Long resultId, Long userId) {
|
||||
FileResultEntity entity = fileResultMapper.selectById(resultId);
|
||||
if (entity == null || entity.getResultFileUrl() == null || !MODULE_TYPE.equals(entity.getModuleType()) || !userId.equals(entity.getUserId())) {
|
||||
throw new BusinessException("Split result file does not exist.");
|
||||
throw new BusinessException("拆分结果文件不存在。");
|
||||
}
|
||||
return ossStorageService.generateFreshDownloadUrl(entity.getResultFileUrl());
|
||||
}
|
||||
@@ -244,7 +245,7 @@ public class SplitRunService {
|
||||
) throws Exception {
|
||||
CountResult countResult = countSplitRows(inputFile, request.getSelectedColumns());
|
||||
if (countResult.rowCount() <= 0) {
|
||||
throw new BusinessException("No data rows available for splitting.");
|
||||
throw new BusinessException("没有可拆分的数据行。");
|
||||
}
|
||||
|
||||
List<Integer> chunkSizes = buildChunkSizes(countResult.rowCount(), request);
|
||||
@@ -270,7 +271,7 @@ public class SplitRunService {
|
||||
.filter(column -> !resolvedHeaderMap.containsKey(column))
|
||||
.toList();
|
||||
if (!missing.isEmpty()) {
|
||||
throw new BusinessException("Missing required columns: " + String.join(", ", missing));
|
||||
throw new BusinessException("缺少必需列: " + String.join(", ", missing));
|
||||
}
|
||||
headerMapHolder.set(resolvedHeaderMap);
|
||||
}
|
||||
@@ -282,7 +283,7 @@ public class SplitRunService {
|
||||
}
|
||||
Map<String, Integer> resolvedHeaderMap = headerMapHolder.get();
|
||||
if (resolvedHeaderMap == null) {
|
||||
throw new BusinessException("Excel header row is empty.");
|
||||
throw new BusinessException("Excel 表头行为空。");
|
||||
}
|
||||
List<String> projected = new ArrayList<>();
|
||||
for (String column : request.getSelectedColumns()) {
|
||||
@@ -327,7 +328,7 @@ public class SplitRunService {
|
||||
.filter(column -> !resolvedHeaderMap.containsKey(column))
|
||||
.toList();
|
||||
if (!missing.isEmpty()) {
|
||||
throw new BusinessException("Missing required columns: " + String.join(", ", missing));
|
||||
throw new BusinessException("缺少必需列: " + String.join(", ", missing));
|
||||
}
|
||||
sheetName[0] = currentSheetName == null || currentSheetName.isBlank() ? "Sheet1" : currentSheetName;
|
||||
headerRead[0] = true;
|
||||
@@ -336,13 +337,13 @@ public class SplitRunService {
|
||||
@Override
|
||||
public void onRow(String currentSheetName, Integer sheetNo, int rowIndex, Map<Integer, String> headerMap, Map<Integer, String> rowMap) {
|
||||
if (!headerRead[0]) {
|
||||
throw new BusinessException("Excel header row is empty.");
|
||||
throw new BusinessException("Excel 表头行为空。");
|
||||
}
|
||||
rowCount[0]++;
|
||||
}
|
||||
});
|
||||
if (!headerRead[0]) {
|
||||
throw new BusinessException("Excel header row is empty.");
|
||||
throw new BusinessException("Excel 表头行为空。");
|
||||
}
|
||||
return new CountResult(rowCount[0], sheetName[0]);
|
||||
}
|
||||
@@ -384,15 +385,15 @@ public class SplitRunService {
|
||||
|
||||
private void validateRequest(SplitRunRequest request) {
|
||||
if (!List.of(SPLIT_MODE_ROWS_PER_FILE, SPLIT_MODE_PARTS).contains(request.getSplitMode())) {
|
||||
throw new BusinessException("Invalid split mode.");
|
||||
throw new BusinessException("拆分方式不合法。");
|
||||
}
|
||||
if (SPLIT_MODE_ROWS_PER_FILE.equals(request.getSplitMode())
|
||||
&& (request.getRowsPerFile() == null || request.getRowsPerFile() <= 0)) {
|
||||
throw new BusinessException("Invalid rowsPerFile value.");
|
||||
throw new BusinessException("每个文件行数不合法。");
|
||||
}
|
||||
if (SPLIT_MODE_PARTS.equals(request.getSplitMode())
|
||||
&& (request.getParts() == null || request.getParts() <= 0)) {
|
||||
throw new BusinessException("Invalid parts value.");
|
||||
throw new BusinessException("拆分份数不合法。");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -446,7 +447,7 @@ public class SplitRunService {
|
||||
zos.closeEntry();
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("拆分结果打包失败:" + ex.getMessage());
|
||||
throw new BusinessException(UserMessages.with("拆分结果打包失败", ex));
|
||||
}
|
||||
return zipFile;
|
||||
}
|
||||
|
||||
+51
-35
@@ -47,16 +47,25 @@ public class TaskFileJobLocalDispatcher {
|
||||
/**
|
||||
* 调用方已把 job claim 成 RUNNING 时使用:复用同样的背压/去重/异步执行,
|
||||
* 但落到 worker.processClaimed,避免二次 claimRunning 失败导致 job 被静默丢弃。
|
||||
* <p>传的是 claim 那一刻的行快照,执行前不再回读数据库:回读拿到的 {@code updated_at}
|
||||
* 就是当前值,{@code activateRunningClaim} 的 CAS 于是恒真,排队排久了的旧派发会冒充成
|
||||
* 新持有者,撞锁后再用 {@code deferRunning} 把真持有者正在跑的行翻回 PENDING,
|
||||
* 那次执行的 {@code markSuccess} 随即静默 0 行更新、成功状态丢失
|
||||
* (2026-10-09 任务 30456:结果文件可下载,作业行却是 FAILED)。
|
||||
*/
|
||||
public boolean dispatchClaimed(Long jobId, Long taskId, String moduleType) {
|
||||
return submit(jobId, taskId, moduleType, false, true);
|
||||
public boolean dispatchClaimed(TaskFileJobEntity claim) {
|
||||
if (claim == null || claim.getId() == null || claim.getId() <= 0) {
|
||||
return false;
|
||||
}
|
||||
return accept(claim.getId(), claim.getTaskId(), claim.getModuleType(), false,
|
||||
() -> runClaimed(claim));
|
||||
}
|
||||
|
||||
public boolean dispatch(Long jobId, Long taskId, String moduleType, boolean force) {
|
||||
return submit(jobId, taskId, moduleType, force, false);
|
||||
return accept(jobId, taskId, moduleType, force, () -> processLocally(jobId, taskId, moduleType));
|
||||
}
|
||||
|
||||
private boolean submit(Long jobId, Long taskId, String moduleType, boolean force, boolean alreadyClaimed) {
|
||||
private boolean accept(Long jobId, Long taskId, String moduleType, boolean force, Runnable body) {
|
||||
if (jobId == null || jobId <= 0) {
|
||||
return false;
|
||||
}
|
||||
@@ -85,20 +94,28 @@ public class TaskFileJobLocalDispatcher {
|
||||
jobId, taskId, moduleType);
|
||||
return true;
|
||||
}
|
||||
// 守卫只写一处:两条 body(已 claim / 未 claim)共用同一个"记日志 + 放名额"的包装,
|
||||
// 免得拆方法时一人一份 catch,把 catch-静默棘轮的总数悄悄抬上去。
|
||||
Runnable guarded = () -> {
|
||||
try {
|
||||
body.run();
|
||||
} catch (Exception ex) {
|
||||
log.warn("[task-file-job] local dispatch failed jobId={} taskId={} moduleType={} msg={}",
|
||||
jobId, taskId, moduleType, ex.getMessage(), ex);
|
||||
} finally {
|
||||
removeInflight(jobId);
|
||||
}
|
||||
};
|
||||
try {
|
||||
taskFileJobDispatchExecutor.execute(() -> processLocally(jobId, taskId, moduleType, alreadyClaimed));
|
||||
taskFileJobDispatchExecutor.execute(guarded);
|
||||
return true;
|
||||
} catch (RuntimeException ex) {
|
||||
removeInflight(jobId);
|
||||
log.warn("[task-file-job] local dispatch executor rejected jobId={} taskId={} moduleType={} msg={}",
|
||||
jobId, taskId, moduleType, ex.getMessage(), ex);
|
||||
if (force) {
|
||||
try {
|
||||
processLocally(jobId, taskId, moduleType, alreadyClaimed);
|
||||
return true;
|
||||
} finally {
|
||||
removeInflight(jobId);
|
||||
}
|
||||
guarded.run();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -113,30 +130,29 @@ public class TaskFileJobLocalDispatcher {
|
||||
}
|
||||
}
|
||||
|
||||
private void processLocally(Long jobId, Long taskId, String moduleType, boolean alreadyClaimed) {
|
||||
try {
|
||||
TaskFileJobEntity job = taskFileJobMapper.selectById(jobId);
|
||||
if (job == null) {
|
||||
log.warn("[task-file-job] local dispatch ignored, job not found jobId={} taskId={} moduleType={}",
|
||||
jobId, taskId, moduleType);
|
||||
return;
|
||||
}
|
||||
TaskResultFileJobWorker taskResultFileJobWorker = taskResultFileJobWorkerProvider.getIfAvailable();
|
||||
if (taskResultFileJobWorker == null) {
|
||||
log.warn("[task-file-job] local dispatch ignored, worker unavailable jobId={} taskId={} moduleType={}",
|
||||
jobId, taskId, moduleType);
|
||||
return;
|
||||
}
|
||||
if (alreadyClaimed) {
|
||||
taskResultFileJobWorker.processClaimed(job);
|
||||
} else {
|
||||
taskResultFileJobWorker.process(job);
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
log.warn("[task-file-job] local dispatch failed jobId={} taskId={} moduleType={} msg={}",
|
||||
jobId, taskId, moduleType, ex.getMessage(), ex);
|
||||
} finally {
|
||||
removeInflight(jobId);
|
||||
private void runClaimed(TaskFileJobEntity claim) {
|
||||
TaskResultFileJobWorker taskResultFileJobWorker = taskResultFileJobWorkerProvider.getIfAvailable();
|
||||
if (taskResultFileJobWorker == null) {
|
||||
log.warn("[task-file-job] local dispatch ignored, worker unavailable jobId={} taskId={} moduleType={}",
|
||||
claim.getId(), claim.getTaskId(), claim.getModuleType());
|
||||
return;
|
||||
}
|
||||
taskResultFileJobWorker.processClaimed(claim);
|
||||
}
|
||||
|
||||
private void processLocally(Long jobId, Long taskId, String moduleType) {
|
||||
TaskFileJobEntity job = taskFileJobMapper.selectById(jobId);
|
||||
if (job == null) {
|
||||
log.warn("[task-file-job] local dispatch ignored, job not found jobId={} taskId={} moduleType={}",
|
||||
jobId, taskId, moduleType);
|
||||
return;
|
||||
}
|
||||
TaskResultFileJobWorker taskResultFileJobWorker = taskResultFileJobWorkerProvider.getIfAvailable();
|
||||
if (taskResultFileJobWorker == null) {
|
||||
log.warn("[task-file-job] local dispatch ignored, worker unavailable jobId={} taskId={} moduleType={}",
|
||||
jobId, taskId, moduleType);
|
||||
return;
|
||||
}
|
||||
taskResultFileJobWorker.process(job);
|
||||
}
|
||||
}
|
||||
|
||||
+11
-4
@@ -638,12 +638,19 @@ public class TaskFileJobService {
|
||||
return true;
|
||||
}
|
||||
|
||||
public void markSuccess(TaskFileJobEntity job, String resultFileUrl) {
|
||||
/**
|
||||
* 只有行还归本次执行(状态仍是 RUNNING)时才落 SUCCESS。
|
||||
*
|
||||
* @return 是否真的写进去了。false 意味着这一行的状态已被别人翻走(见
|
||||
* {@link #deferRunning}),成功状态丢失——调用方必须打日志,否则线上只会看到
|
||||
* "结果文件明明可下载、作业行却是 FAILED"(2026-10-09 任务 30456)。
|
||||
*/
|
||||
public boolean markSuccess(TaskFileJobEntity job, String resultFileUrl) {
|
||||
if (job == null || job.getId() == null) {
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
taskFileJobMapper.update(null, new LambdaUpdateWrapper<TaskFileJobEntity>()
|
||||
return taskFileJobMapper.update(null, new LambdaUpdateWrapper<TaskFileJobEntity>()
|
||||
.eq(TaskFileJobEntity::getId, job.getId())
|
||||
.eq(TaskFileJobEntity::getStatus, "RUNNING")
|
||||
.set(TaskFileJobEntity::getStatus, "SUCCESS")
|
||||
@@ -651,7 +658,7 @@ public class TaskFileJobService {
|
||||
.set(TaskFileJobEntity::getResultFileUrl, resultFileUrl)
|
||||
.set(TaskFileJobEntity::getUpdatedAt, now)
|
||||
.set(TaskFileJobEntity::getFinishedAt, now)
|
||||
.set(TaskFileJobEntity::getTerminalCallbackAt, now));
|
||||
.set(TaskFileJobEntity::getTerminalCallbackAt, now)) > 0;
|
||||
}
|
||||
|
||||
public TaskFileJobEntity findById(Long jobId) {
|
||||
|
||||
+13
-9
@@ -81,11 +81,7 @@ public class TaskResultFileJobWorker {
|
||||
// claimRunnableJobsForOwner 已把 job 原子翻转成 RUNNING,这里必须走"已 claim"
|
||||
// 通道:若再走 process() 的 claimRunning,条件 UPDATE 会因状态已是 RUNNING 而
|
||||
// 失败,job 被静默丢弃并挂到 stuck 扫描才回收,定时兜底等于失效。
|
||||
boolean dispatched = taskFileJobLocalDispatcher.dispatchClaimed(
|
||||
job.getId(),
|
||||
job.getTaskId(),
|
||||
job.getModuleType()
|
||||
);
|
||||
boolean dispatched = taskFileJobLocalDispatcher.dispatchClaimed(job);
|
||||
if (!dispatched) {
|
||||
processClaimed(job);
|
||||
}
|
||||
@@ -274,11 +270,19 @@ public class TaskResultFileJobWorker {
|
||||
return;
|
||||
}
|
||||
String resultFileUrl = resolveResultFileUrl(job);
|
||||
taskFileJobService.markSuccess(job, resultFileUrl);
|
||||
boolean successMarked = taskFileJobService.markSuccess(job, resultFileUrl);
|
||||
cleanupAfterSuccess(job);
|
||||
log.info("[task-file-job] process success jobId={} taskId={} moduleType={} resultId={} elapsedMs={} resultFileUrl={} stage=SUCCESS",
|
||||
job.getId(), job.getTaskId(), job.getModuleType(), job.getResultId(),
|
||||
System.currentTimeMillis() - startedAt, resultFileUrl);
|
||||
if (!successMarked) {
|
||||
// 结果文件已经生成、可下载,但作业行不在这次执行手里了(成功状态丢失)。
|
||||
// 不翻 FAILED:那会让界面把一次成功的任务显示成"结果生成失败"。
|
||||
log.warn("[task-file-job] process succeeded but job row is no longer RUNNING for this run jobId={} taskId={} moduleType={} resultId={} elapsedMs={} resultFileUrl={} stage=SUCCESS_LOST",
|
||||
job.getId(), job.getTaskId(), job.getModuleType(), job.getResultId(),
|
||||
System.currentTimeMillis() - startedAt, resultFileUrl);
|
||||
} else {
|
||||
log.info("[task-file-job] process success jobId={} taskId={} moduleType={} resultId={} elapsedMs={} resultFileUrl={} stage=SUCCESS",
|
||||
job.getId(), job.getTaskId(), job.getModuleType(), job.getResultId(),
|
||||
System.currentTimeMillis() - startedAt, resultFileUrl);
|
||||
}
|
||||
}
|
||||
// 成功后回调解耦(原 WITHDRAW 特判):时机与历史一致——锁已释放、markSuccess 之后;
|
||||
// 各模块需要"任务收尾"时实现 ResultFileJobHandler.onSuccess,task 侧不再 import 业务模块
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.taskcenter.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.nanri.aiimage.common.module.TaskModuleRegistry;
|
||||
import com.nanri.aiimage.modules.taskcenter.mapper.TaskCenterQueryMapper;
|
||||
import com.nanri.aiimage.modules.taskcenter.model.dto.TaskCenterCollectStatsRow;
|
||||
@@ -403,7 +404,7 @@ public class TaskCenterQueryService {
|
||||
vo.setProgressSuccess(nullToZero(snapshot.getSuccessCount()));
|
||||
vo.setProgressFailed(nullToZero(snapshot.getFailedCount()));
|
||||
vo.setCurrentScope(snapshot.getCurrentScopeKey());
|
||||
vo.setMessage(snapshot.getMessage());
|
||||
vo.setMessage(UserMessages.orFallback(snapshot.getMessage(), ""));
|
||||
} else {
|
||||
fillFallbackProgress(vo, row, collectStats.get(row.getId()));
|
||||
}
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.usersecret.client;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.nanri.aiimage.common.util.SecretMasking;
|
||||
@@ -137,7 +138,7 @@ public class JikipProxyClient {
|
||||
} catch (Exception ex) {
|
||||
log.warn("[user-secret][proxy] 余量查询失败 err={}", ex.getMessage());
|
||||
vo.setAvailable(false);
|
||||
vo.setMessage("余量查询失败:" + ex.getMessage());
|
||||
vo.setMessage(UserMessages.with("余量查询失败", ex));
|
||||
}
|
||||
return vo;
|
||||
}
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.withdraw.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.util.SxssfWorkbookWriter;
|
||||
import com.nanri.aiimage.modules.withdraw.model.dto.WithdrawRowDto;
|
||||
@@ -83,7 +84,7 @@ public class WithdrawExcelAssemblyService {
|
||||
writer.write(outputXlsx);
|
||||
} catch (Exception ex) {
|
||||
log.warn("[withdraw] write workbook failed: {}", ex.getMessage());
|
||||
throw new BusinessException("生成取款 Excel 失败: " + ex.getMessage());
|
||||
throw new BusinessException(UserMessages.with("生成取款 Excel 失败", ex));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+3
-2
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.withdraw.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.modules.productrisk.model.dto.ProductRiskCandidateAddRequest;
|
||||
@@ -160,11 +161,11 @@ public class WithdrawResolveService {
|
||||
} catch (BusinessException ex) {
|
||||
item.setMatched(false);
|
||||
item.setMatchStatus("PENDING");
|
||||
item.setMatchMessage(ex.getMessage());
|
||||
item.setMatchMessage(UserMessages.orFallback(ex.getMessage(), "该行匹配失败,请稍后重试"));
|
||||
} catch (Exception ex) {
|
||||
item.setMatched(false);
|
||||
item.setMatchStatus("PENDING");
|
||||
item.setMatchMessage(Objects.toString(ex.getMessage(), "匹配异常"));
|
||||
item.setMatchMessage(UserMessages.orFallback(ex.getMessage(), "匹配异常"));
|
||||
}
|
||||
return item;
|
||||
}
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.ziniao.service;
|
||||
|
||||
import com.nanri.aiimage.common.util.UserMessages;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.config.ZiniaoProperties;
|
||||
@@ -427,7 +428,7 @@ public class ZiniaoShopIndexService {
|
||||
whitelistSkippedApiKeyCount, nextOffset);
|
||||
} catch (Exception ex) {
|
||||
cursor.setStatus("FAILED");
|
||||
cursor.setMessage(ex.getMessage());
|
||||
cursor.setMessage(UserMessages.orFallback(ex.getMessage(), "店铺列表获取失败,请稍后重试"));
|
||||
cursor.setLastFinishedAt(now);
|
||||
if (isIpWhitelistRefreshFailure(ex)) {
|
||||
log.warn("[ziniao-index] refresh blocked reason={} existing shop index rows left untouched",
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
package com.nanri.aiimage;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* 全仓尺子:用户可见文案出口不许把底层异常原文直接拼进去。
|
||||
*
|
||||
* <p>起因是 2026-10-09 那张货源查询截图:卡片上那句英文不是写错的文案,而是
|
||||
* {@code biz_task_file_job.error_message} 里存的异常原文。普查数出 61 处出口
|
||||
* ({@code new BusinessException("中文: " + ex.getMessage())}、
|
||||
* {@code setErrorMessage(ex.getMessage())}、{@code ApiResponse.fail(ex.getMessage())} 这类)
|
||||
* 把 Java 栈名、Coze/MinIO 报错原样交给界面——逐条翻译追不上新增速度,所以把规矩做进代码:
|
||||
* 出口只接受 {@link com.nanri.aiimage.common.util.UserMessages} 把关后的串。
|
||||
*
|
||||
* <p>判据按行匹配(与同目录 {@code UserFacingMessageChineseGuardTest} 的括号配平法互补):
|
||||
* 一行里既有文案出口、又出现 {@code getMessage()/messageOf()},却没有 {@code UserMessages.}
|
||||
* 也没有 {@code log.},就是违例。日志行不算——日志正是留着英文原文查根因的地方。
|
||||
*
|
||||
* <p>分母硬钉:扫到的出口行数低于下限,说明正则或目录树坏了,那时的"零违例"不作数。
|
||||
*/
|
||||
class RawExceptionMessageSinkGuardTest {
|
||||
|
||||
/** 本轮实测 1595 行出口,下限取 1500:明显缩水即判抽取器失效。 */
|
||||
private static final int MIN_SINK_LINES = 1500;
|
||||
|
||||
/**
|
||||
* 逐条点名的豁免:格式 {@code 文件后缀 :: 语句}(空白归一后整句比对,行号会漂所以不进键)。
|
||||
* 数字人任务把 Coze 返回的业务错原文留在 error_message 里,是给支持同学对着
|
||||
* ImageVideoAsyncTaskServiceTest 那三条钉子查根因用的;界面上的中文由前端
|
||||
* {@code userNotice} 兜住,所以这里放行、不再要求写侧把关。
|
||||
*/
|
||||
private static final List<String> EXEMPTIONS = List.of(
|
||||
"modules/imagevideo/service/ImageVideoAsyncTaskService.java::"
|
||||
+ "task.setErrorMessage(truncate(messageOf(ex)));");
|
||||
|
||||
private static final Pattern SINK = Pattern.compile(
|
||||
"new BusinessException\\(|ApiResponse\\.fail\\(|set(?:ErrorMessage|Error|MatchMessage|FileError"
|
||||
+ "|Message|FailureReason)\\(|markFailed|markFailureFinalized|saveBrandProgressSnapshot"
|
||||
+ "|saveFileBuildProgress");
|
||||
|
||||
private static final Pattern RAW_EXCEPTION_TEXT = Pattern.compile("\\.getMessage\\(\\)|messageOf\\(");
|
||||
|
||||
private static final Pattern GUARDED = Pattern.compile("UserMessages\\.|\\blog\\.\\w+\\(");
|
||||
|
||||
@Test
|
||||
void userVisibleSinksNeverEmbedRawExceptionText() throws IOException {
|
||||
List<String> offenders = new ArrayList<>();
|
||||
Set<String> usedExemptions = new LinkedHashSet<>();
|
||||
int sinkLines = 0;
|
||||
for (Path file : mainSources()) {
|
||||
String relative = relativeName(file);
|
||||
List<String> lines = Files.readAllLines(file, StandardCharsets.UTF_8);
|
||||
for (int i = 0; i < lines.size(); i++) {
|
||||
String line = lines.get(i).strip();
|
||||
if (line.startsWith("//") || line.startsWith("*") || line.startsWith("/*")) {
|
||||
continue;
|
||||
}
|
||||
if (!SINK.matcher(line).find()) {
|
||||
continue;
|
||||
}
|
||||
sinkLines++;
|
||||
if (RAW_EXCEPTION_TEXT.matcher(line).find() && !GUARDED.matcher(line).find()) {
|
||||
String key = relative + "::" + line;
|
||||
if (EXEMPTIONS.contains(key)) {
|
||||
usedExemptions.add(key);
|
||||
continue;
|
||||
}
|
||||
offenders.add(relative + ":" + (i + 1) + " " + shorten(line));
|
||||
}
|
||||
}
|
||||
}
|
||||
assertTrue(sinkLines >= MIN_SINK_LINES,
|
||||
"只扫到 " + sinkLines + " 行文案出口(下限 " + MIN_SINK_LINES + ")——正则或源码树坏了,"
|
||||
+ "此刻的\"零违例\"不作数");
|
||||
if (!offenders.isEmpty()) {
|
||||
fail("这些出口把底层异常原文交给了界面,必须走 UserMessages.with/orFallback:\n "
|
||||
+ String.join("\n ", offenders));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 自证:把一条违例样本喂给同一套判据,必须被抓住。
|
||||
* 判据抓不到自己造的违例,就说明它是个恒绿的空壳。
|
||||
*/
|
||||
@Test
|
||||
void detectorCatchesAPlantedViolation() {
|
||||
String planted = "throw new BusinessException(\"生成结果失败: \" + ex.getMessage());";
|
||||
assertTrue(SINK.matcher(planted).find(), "样本没被认成文案出口,抽取器对这类写法失明");
|
||||
assertTrue(RAW_EXCEPTION_TEXT.matcher(planted).find(), "样本没被认出异常原文");
|
||||
assertTrue(!GUARDED.matcher(planted).find(), "样本不该算已把关");
|
||||
|
||||
String guarded = "throw new BusinessException(UserMessages.with(\"生成结果失败\", ex));";
|
||||
assertTrue(SINK.matcher(guarded).find());
|
||||
assertTrue(GUARDED.matcher(guarded).find(), "把关写法被误判成违例");
|
||||
|
||||
String logged = "log.warn(\"assemble failed msg={}\", ex.getMessage());";
|
||||
assertTrue(GUARDED.matcher(logged).find(), "日志行不该进违例");
|
||||
}
|
||||
|
||||
private static String shorten(String line) {
|
||||
return line.length() <= 140 ? line : line.substring(0, 140) + "...";
|
||||
}
|
||||
|
||||
private static String relativeName(Path file) {
|
||||
String path = file.toString().replace('\\', '/');
|
||||
int cut = path.indexOf("/com/nanri/aiimage/");
|
||||
return cut < 0 ? path : path.substring(cut + "/com/nanri/aiimage/".length());
|
||||
}
|
||||
|
||||
private static List<Path> mainSources() throws IOException {
|
||||
Path root = moduleRoot().resolve("src/main/java");
|
||||
if (!Files.isDirectory(root)) {
|
||||
fail("找不到源码目录:" + root);
|
||||
}
|
||||
try (Stream<Path> stream = Files.walk(root)) {
|
||||
return stream.filter(p -> p.toString().endsWith(".java")).sorted().toList();
|
||||
}
|
||||
}
|
||||
|
||||
private static Path moduleRoot() {
|
||||
Path here = Path.of("").toAbsolutePath();
|
||||
return here.getFileName().toString().equals("backend-java") ? here : here.getParent();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
package com.nanri.aiimage;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* 全仓尺子:凡是会进用户界面的文案出口({@code new BusinessException(...)} 与
|
||||
* {@code saveFileBuildProgress(...)}),首段必须是中文。
|
||||
*
|
||||
* <p>起因是 2026-10-09 一张货源查询任务截图:同一个卡片上既有中文"仅完成 102/112 行",
|
||||
* 又有一句英文 "Similar ASIN result rows are empty; please retry result generation"。
|
||||
* 那次拆分只翻译了 legacy 装配路径,bounded 路径的 8 句英文异常原样进了
|
||||
* {@code biz_task_file_job.error_message},前端 {@code pendingResultHint} 又不加转换地渲染。
|
||||
* 全仓普查当时数出 1,213 个带字面量的出口、其中 112 个首段没有中文。
|
||||
*
|
||||
* <p>判据是"首段字面量含中文",不是"每段都含中文":拼接里的单位片段
|
||||
* ({@code " bytes"}、{@code " 分钟)"})本就不该有中文。
|
||||
*
|
||||
* <p>豁免表必须条条被用到——用不到的豁免就是常开的洞,所以 {@link #noDeadExemptions} 专门反查。
|
||||
*/
|
||||
class UserFacingMessageChineseGuardTest {
|
||||
|
||||
/** 扫描到的出口总数下限:低于此值说明抽取器什么都没抓到,那时的"零违规"是假的。 */
|
||||
private static final int MIN_OUTLETS_SCANNED = 1200;
|
||||
|
||||
/**
|
||||
* 逐条点名豁免,格式 {@code 文件后缀 :: 首段字面量}。
|
||||
* 每一条都要在下面写清为什么可以留英文,以及什么时候该摘掉。
|
||||
*/
|
||||
private static final List<String> EXEMPTIONS = List.of(
|
||||
// JSON 键名,不是消息:真正的兜底文案在同一个参数列表的最后一段,已是中文
|
||||
"modules/imagevideo/service/ImageVideoCozeService.java::msg");
|
||||
|
||||
@Test
|
||||
void everyUserFacingMessageOutletStartsWithChinese() throws IOException {
|
||||
List<String> offenders = new ArrayList<>();
|
||||
Set<String> usedExemptions = new LinkedHashSet<>();
|
||||
int scanned = 0;
|
||||
for (Path file : mainSources()) {
|
||||
String source = read(file);
|
||||
String relative = relativeName(file);
|
||||
for (String arguments : messageArguments(source)) {
|
||||
String first = firstLiteral(arguments);
|
||||
if (first.isBlank()) {
|
||||
continue;
|
||||
}
|
||||
scanned++;
|
||||
if (containsChinese(first)) {
|
||||
continue;
|
||||
}
|
||||
String key = relative + "::" + first;
|
||||
if (EXEMPTIONS.contains(key)) {
|
||||
usedExemptions.add(key);
|
||||
continue;
|
||||
}
|
||||
offenders.add(relative + " -> \"" + first + "\"");
|
||||
}
|
||||
}
|
||||
assertThatListIsEmpty(offenders, "这些文案出口的首段不是中文,会原样出现在用户界面上");
|
||||
assertTrue(scanned >= MIN_OUTLETS_SCANNED,
|
||||
"只扫到 " + scanned + " 个带字面量的出口(下限 " + MIN_OUTLETS_SCANNED
|
||||
+ ")——抽取器失效了,此刻的\"零违规\"不作数");
|
||||
}
|
||||
|
||||
/** 用不到的豁免要摘掉,否则它会慢慢变成一个"谁都能往里塞一条"的常开门。 */
|
||||
@Test
|
||||
void noDeadExemptions() throws IOException {
|
||||
Set<String> seen = new LinkedHashSet<>();
|
||||
for (Path file : mainSources()) {
|
||||
String relative = relativeName(file);
|
||||
for (String arguments : messageArguments(read(file))) {
|
||||
String first = firstLiteral(arguments);
|
||||
if (!first.isBlank()) {
|
||||
seen.add(relative + "::" + first);
|
||||
}
|
||||
}
|
||||
}
|
||||
List<String> dead = EXEMPTIONS.stream().filter(key -> !seen.contains(key)).toList();
|
||||
assertThatListIsEmpty(dead, "这些豁免已经没有对应的英文出口了,请从 EXEMPTIONS 里删掉");
|
||||
}
|
||||
|
||||
private static void assertThatListIsEmpty(List<String> items, String message) {
|
||||
if (!items.isEmpty()) {
|
||||
fail(message + ":\n " + String.join("\n ", items));
|
||||
}
|
||||
}
|
||||
|
||||
private static final List<String> MARKERS = List.of("new BusinessException(", "saveFileBuildProgress(");
|
||||
|
||||
/** 每个标记后面那段配平的括号内容,就是文案所在的地方。 */
|
||||
private static List<String> messageArguments(String source) {
|
||||
List<String> arguments = new ArrayList<>();
|
||||
for (String marker : MARKERS) {
|
||||
int from = 0;
|
||||
while (true) {
|
||||
int at = source.indexOf(marker, from);
|
||||
if (at < 0) {
|
||||
break;
|
||||
}
|
||||
from = at + marker.length();
|
||||
int open = source.indexOf('(', at);
|
||||
String body = balancedArguments(source, open);
|
||||
if (body == null) {
|
||||
fail("括号没配平,扫描器会在 " + marker + " 处漏判(offset=" + at + ")");
|
||||
}
|
||||
arguments.add(body);
|
||||
}
|
||||
}
|
||||
return arguments;
|
||||
}
|
||||
|
||||
private static String balancedArguments(String source, int openParen) {
|
||||
int depth = 0;
|
||||
boolean inString = false;
|
||||
for (int i = openParen; i < source.length(); i++) {
|
||||
char c = source.charAt(i);
|
||||
if (inString) {
|
||||
if (c == '\\') {
|
||||
i++;
|
||||
} else if (c == '"') {
|
||||
inString = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (c == '"') {
|
||||
inString = true;
|
||||
} else if (c == '(') {
|
||||
depth++;
|
||||
} else if (c == ')') {
|
||||
depth--;
|
||||
if (depth == 0) {
|
||||
return source.substring(openParen + 1, i);
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static String firstLiteral(String arguments) {
|
||||
int start = -1;
|
||||
boolean inString = false;
|
||||
for (int i = 0; i < arguments.length(); i++) {
|
||||
char c = arguments.charAt(i);
|
||||
if (inString) {
|
||||
if (c == '\\') {
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (c == '"') {
|
||||
return arguments.substring(start + 1, i);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (c == '"') {
|
||||
inString = true;
|
||||
start = i;
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
private static boolean containsChinese(String text) {
|
||||
for (int i = 0; i < text.length(); i++) {
|
||||
char c = text.charAt(i);
|
||||
if (c >= 0x4E00 && c <= 0x9FFF) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** 相对 src/main/java/com/nanri/aiimage 的路径,豁免表用它点名,行号会漂所以不进键。 */
|
||||
private static String relativeName(Path file) {
|
||||
String path = file.toString().replace('\\', '/');
|
||||
int cut = path.indexOf("/com/nanri/aiimage/");
|
||||
return cut < 0 ? path : path.substring(cut + "/com/nanri/aiimage/".length());
|
||||
}
|
||||
|
||||
private static List<Path> mainSources() throws IOException {
|
||||
Path root = moduleRoot().resolve("src/main/java");
|
||||
if (!Files.isDirectory(root)) {
|
||||
fail("找不到 " + root + " —— 用例依赖以 backend-java 为工作目录运行,别让守卫静默通过");
|
||||
}
|
||||
try (Stream<Path> walk = Files.walk(root)) {
|
||||
return walk.filter(Files::isRegularFile)
|
||||
.filter(p -> p.getFileName().toString().endsWith(".java"))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
}
|
||||
|
||||
/** surefire 的工作目录是模块目录;从仓库根或 IDE 跑时退到 backend-java/。 */
|
||||
private static Path moduleRoot() {
|
||||
Path here = Path.of("").toAbsolutePath();
|
||||
if (Files.isDirectory(here.resolve("src/main/java"))) {
|
||||
return here;
|
||||
}
|
||||
Path nested = here.resolve("backend-java");
|
||||
if (Files.isDirectory(nested.resolve("src/main/java"))) {
|
||||
return nested;
|
||||
}
|
||||
throw new IllegalStateException("无法定位 backend-java 模块目录(cwd=" + here + ")");
|
||||
}
|
||||
|
||||
private static String read(Path file) {
|
||||
try {
|
||||
return Files.readString(file, StandardCharsets.UTF_8);
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException("读取 " + file + " 失败", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.nanri.aiimage.common.util;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* 文案把关工具的行为钉子:中文照原样过、英文换兜底句、详情只在中文时才拼接。
|
||||
*/
|
||||
class UserMessagesTest {
|
||||
|
||||
@Test
|
||||
void chineseMessagePassesThroughUntouched() {
|
||||
assertEquals("这份文件没有解析到可导出的行",
|
||||
UserMessages.orFallback("这份文件没有解析到可导出的行", "操作未能完成"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void englishAndBlankFallBackToChinese() {
|
||||
assertEquals("操作未能完成",
|
||||
UserMessages.orFallback("Similar ASIN result rows are empty", "操作未能完成"));
|
||||
assertEquals("操作未能完成", UserMessages.orFallback(null, "操作未能完成"));
|
||||
assertEquals("操作未能完成", UserMessages.orFallback(" ", "操作未能完成"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void chineseDetailIsAppendedAndEnglishDetailIsDropped() {
|
||||
assertEquals("转换结果打包失败:临时目录已满",
|
||||
UserMessages.with("转换结果打包失败", new RuntimeException("临时目录已满")));
|
||||
assertEquals("转换结果打包失败",
|
||||
UserMessages.with("转换结果打包失败", new RuntimeException("No space left on device")));
|
||||
assertEquals("转换结果打包失败", UserMessages.with("转换结果打包失败", (String) null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void headlineKeepsItsOwnColonWhenDetailIsGone() {
|
||||
String text = UserMessages.with("去重结果打包失败: ", new IllegalStateException("boom"));
|
||||
assertEquals("去重结果打包失败", text);
|
||||
assertFalse(text.endsWith(":"), "尾巴被丢掉后不该留下悬空冒号");
|
||||
}
|
||||
|
||||
@Test
|
||||
void onlyHanCharactersCountAsChinese() {
|
||||
assertTrue(UserMessages.hasChinese("401 未登录"));
|
||||
assertFalse(UserMessages.hasChinese("TASK_LOCK_BUSY"));
|
||||
assertFalse(UserMessages.hasChinese(":()—"), "全角标点不等于中文文案");
|
||||
assertFalse(UserMessages.hasChinese(null));
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -99,8 +99,9 @@ class TaskResultFileJobWorkerLogAuditTest {
|
||||
assertFalse(l.contains("module="), "不应使用 module= 漂移字段: " + l.trim());
|
||||
}
|
||||
// 阶段字面量来自允许集合(防新增阶段拼写漂移)
|
||||
// SUCCESS_LOST:结果文件已生成但作业行不在本次执行手里(2026-10-09 任务 30456 的静默丢失)
|
||||
List<String> allowed = List.of("SKIP_OWNER", "REQUEUE", "WAIT_LLM", "DEFER", "SUCCESS",
|
||||
"ORPHAN", "FAILED", "FINALIZE", "HEARTBEAT", "FALLBACK");
|
||||
"SUCCESS_LOST", "ORPHAN", "FAILED", "FINALIZE", "HEARTBEAT", "FALLBACK");
|
||||
for (String l : perJob) {
|
||||
if (l.contains("stage=")) {
|
||||
int idx = l.indexOf("stage=");
|
||||
|
||||
+2
-2
@@ -207,7 +207,7 @@ class ImageVideoAsyncTaskServiceTest {
|
||||
ImageVideoAsyncTaskEntity task = waitingWorkflowTask();
|
||||
task.setStatus("FAILED");
|
||||
task.setCozeStatus("RUNNING");
|
||||
task.setErrorMessage("Coze workflow finished with status RUNNING");
|
||||
task.setErrorMessage("Coze 工作流已结束,状态 RUNNING");
|
||||
when(taskMapper.selectOne(any())).thenReturn(task);
|
||||
|
||||
var result = service.getTask(98L, 1L);
|
||||
@@ -367,7 +367,7 @@ class ImageVideoAsyncTaskServiceTest {
|
||||
|
||||
assertEquals("FAILED", task.getStatus());
|
||||
assertEquals("SUCCESS", task.getCozeStatus());
|
||||
assertEquals("Coze workflow succeeded but video_url is empty", task.getErrorMessage());
|
||||
assertEquals("Coze 工作流成功但没有返回视频地址", task.getErrorMessage());
|
||||
assertNotNull(task.getCompletedAt());
|
||||
assertTrue(task.getResultJson().contains("video_url"));
|
||||
verify(archiveService, never()).enrichCompletedTask(any(), any());
|
||||
|
||||
+2
-2
@@ -174,7 +174,7 @@ class SimilarAsinTaskServiceChunkKeysetTest {
|
||||
when(taskChunkMapper.selectList(any())).thenThrow(new IllegalStateException("db down"));
|
||||
BusinessException ex = assertThrows(BusinessException.class,
|
||||
() -> SimilarAsinChunkMergeSupport.loadChunksKeyset(taskChunkMapper, 7004L, MODULE, 500));
|
||||
assertTrue(ex.getMessage() != null && ex.getMessage().contains("chunk"),
|
||||
assertTrue(ex.getMessage() != null && ex.getMessage().contains("分片"),
|
||||
"异常消息必须可识别,实际: " + ex.getMessage());
|
||||
}
|
||||
|
||||
@@ -194,7 +194,7 @@ class SimilarAsinTaskServiceChunkKeysetTest {
|
||||
}).when(taskChunkMapper).selectList(any());
|
||||
BusinessException ex = assertThrows(BusinessException.class,
|
||||
() -> SimilarAsinChunkMergeSupport.loadChunksKeyset(taskChunkMapper, 7004L, MODULE, 3));
|
||||
assertTrue(ex.getMessage() != null && ex.getMessage().contains("chunk"),
|
||||
assertTrue(ex.getMessage() != null && ex.getMessage().contains("分片"),
|
||||
"异常消息必须可识别,实际: " + ex.getMessage());
|
||||
// 恢复后重试成功:5 个 chunk 全部取回
|
||||
stubKeysetPages(all, 3);
|
||||
|
||||
+1
-1
@@ -357,7 +357,7 @@ class SimilarAsinTaskServiceChunkMergeLimitTest {
|
||||
}
|
||||
});
|
||||
assertNotNull(ex.getMessage());
|
||||
assertTrue(ex.getMessage().contains("chunk"),
|
||||
assertTrue(ex.getMessage().contains("分片"),
|
||||
"chunk 读取失败消息必须可识别,实际: " + ex.getMessage());
|
||||
verify(transientPayloadStorageService, times(0)).storeChunkPayloadVersioned(anyString(), any(), anyString(), any(), anyString());
|
||||
verify(taskScopeStateMapper, times(0)).insert(any(TaskScopeStateEntity.class));
|
||||
|
||||
+1
-1
@@ -309,7 +309,7 @@ class SimilarAsinTaskServiceRowKeyDedupeTest {
|
||||
throw e.getCause();
|
||||
}
|
||||
});
|
||||
assertTrue(ex.getMessage() != null && ex.getMessage().contains("chunk"),
|
||||
assertTrue(ex.getMessage() != null && ex.getMessage().contains("分片"),
|
||||
"chunk 读取失败消息必须可识别,实际: " + ex.getMessage());
|
||||
verify(transientPayloadStorageService, times(0)).storeChunkPayloadVersioned(anyString(), any(), anyString(), any(), anyString());
|
||||
// 恢复后重试成功:只写一次,无重复记录
|
||||
|
||||
+1
-1
@@ -359,7 +359,7 @@ class SimilarAsinTaskServiceRowKeyIndexTest {
|
||||
throw e.getCause();
|
||||
}
|
||||
});
|
||||
assertTrue(ex.getMessage() != null && ex.getMessage().contains("chunk"),
|
||||
assertTrue(ex.getMessage() != null && ex.getMessage().contains("分片"),
|
||||
"chunk 读取失败消息必须可识别,实际: " + ex.getMessage());
|
||||
verify(transientPayloadStorageService, times(0)).storeChunkPayloadVersioned(anyString(), any(), anyString(), any(), anyString());
|
||||
// 恢复后重试成功:行合并到正确 chunk
|
||||
|
||||
+222
@@ -0,0 +1,222 @@
|
||||
package com.nanri.aiimage.modules.similarasin.service.support;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.fail;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* 货源查询(SIMILAR_ASIN)结果出口的提示语必须是中文。
|
||||
*
|
||||
* <p>线上任务 30456 的界面同时出现"仅完成 102/112 行"和一句英文
|
||||
* "Similar ASIN result rows are empty; please retry result generation":前者是 legacy 装配路径写的,
|
||||
* 后者是 bounded 装配路径写的。两条路径是同一次拆分(9d92fb4a)时只翻译了 legacy 那一半,
|
||||
* bounded 那一半的 8 句英文异常原样进了 {@code biz_task_file_job.error_message},
|
||||
* 前端 {@code pendingResultHint} 又把这一列不加转换地渲染出来。
|
||||
*
|
||||
* <p>所以这里钉两件事:
|
||||
* <ol>
|
||||
* <li>那 8 句英文不许回来(排他断言,逐句点名);</li>
|
||||
* <li>两个文件里每个 {@code new BusinessException(...)} / {@code saveFileBuildProgress(...)}
|
||||
* 出口的第一段文案必须含中文——新增出口自动受约束。</li>
|
||||
* </ol>
|
||||
*
|
||||
* <p>第二条的判据是"首段字面量含中文",不是"每段都含中文":拼接里的单位片段
|
||||
* ({@code " bytes"}、{@code " 分钟)"})本就不该有中文,2026-10-09 用两个文件的全部
|
||||
* 62 个出口校准过这个口径。分母自证用例防止扫描器一旦抓不到就恒绿。
|
||||
*/
|
||||
class SimilarAsinChineseMessageGuardTest {
|
||||
|
||||
private static final List<String> SCANNED_FILES = List.of(
|
||||
"modules/similarasin/service/SimilarAsinTaskService.java",
|
||||
"modules/similarasin/service/support/SimilarAsinResultWorkbookAssembler.java");
|
||||
|
||||
/** 2026-10-09 实测:TaskService 42 个出口 + Assembler 20 个出口。新增/删除出口要同步改这里。 */
|
||||
private static final int SCANNED_SITE_COUNT = 62;
|
||||
|
||||
/** 文案来自变量、字面量判据覆盖不到的出口,按构造点名(行号会漂)。 */
|
||||
private static final List<String> VARIABLE_FED_OUTLETS = List.of(
|
||||
"task, job, 1, 1, failureMessage",
|
||||
"FailedStatusRowFilter.noMatchedRowsMessage()",
|
||||
"message");
|
||||
|
||||
private static final List<String> ENGLISH_LEAKS = List.of(
|
||||
"Similar ASIN result rows are empty",
|
||||
"failed to create result directory",
|
||||
"result workbook assembly interrupted",
|
||||
"result workbook assembly timed out",
|
||||
"result workbook assembly cancelled",
|
||||
"result workbook assembly failed",
|
||||
"create Similar ASIN image spool failed",
|
||||
"no valid similar ASIN rows",
|
||||
"Assembling xlsx",
|
||||
"Uploading result file",
|
||||
"Result file generated",
|
||||
"LLM result is still processing");
|
||||
|
||||
@Test
|
||||
void theEnglishMessagesThatReachedTheUiAreGone() throws IOException {
|
||||
for (String fragment : ENGLISH_LEAKS) {
|
||||
for (String file : SCANNED_FILES) {
|
||||
assertThat(readSource(file))
|
||||
.as("%s 里不许出现以 \"%s\" 开头的用户可见文案,改成中文", file, fragment)
|
||||
.doesNotContain(fragment);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyMessageOutletStartsWithChinese() throws IOException {
|
||||
List<String> offenders = new ArrayList<>();
|
||||
List<String> variableFed = new ArrayList<>();
|
||||
int scanned = 0;
|
||||
for (String file : SCANNED_FILES) {
|
||||
String source = readSource(file);
|
||||
for (Outlet outlet : outlets(source)) {
|
||||
scanned++;
|
||||
if (!outlet.hasFirstLiteral()) {
|
||||
variableFed.add(outlet.arguments().trim());
|
||||
continue;
|
||||
}
|
||||
if (!containsChinese(outlet.firstLiteral())) {
|
||||
offenders.add(file + ":" + outlet.line() + " -> \"" + outlet.firstLiteral() + "\"");
|
||||
}
|
||||
}
|
||||
}
|
||||
assertThat(offenders)
|
||||
.as("这些出口的首段文案没有中文,会原样出现在用户界面上")
|
||||
.isEmpty();
|
||||
// 分母自证:扫描器一旦什么都抓不到,上面的断言就恒绿,等于没有护栏。
|
||||
// 新增出口要同时改这个数字;文案来自变量时也要确认变量本身是中文。
|
||||
assertThat(scanned)
|
||||
.as("两个文件里 new BusinessException(...) 与 saveFileBuildProgress(...) 的出口总数")
|
||||
.isEqualTo(SCANNED_SITE_COUNT);
|
||||
assertThat(variableFed)
|
||||
.as("文案来自变量、本用例判不了的出口——改动这几处时要自己确认落到界面上是中文")
|
||||
.containsExactlyInAnyOrderElementsOf(VARIABLE_FED_OUTLETS);
|
||||
}
|
||||
|
||||
private record Outlet(int line, String arguments) {
|
||||
boolean hasFirstLiteral() {
|
||||
return !firstLiteral().isEmpty();
|
||||
}
|
||||
|
||||
String firstLiteral() {
|
||||
int start = -1;
|
||||
boolean inString = false;
|
||||
for (int i = 0; i < arguments.length(); i++) {
|
||||
char c = arguments.charAt(i);
|
||||
if (inString) {
|
||||
if (c == '\\') {
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (c == '"') {
|
||||
return arguments.substring(start + 1, i);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (c == '"') {
|
||||
inString = true;
|
||||
start = i;
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
private static List<Outlet> outlets(String source) {
|
||||
List<Outlet> outlets = new ArrayList<>();
|
||||
for (String marker : List.of("new BusinessException(", "saveFileBuildProgress(")) {
|
||||
int from = 0;
|
||||
while (true) {
|
||||
int at = source.indexOf(marker, from);
|
||||
if (at < 0) {
|
||||
break;
|
||||
}
|
||||
from = at + marker.length();
|
||||
int open = source.indexOf('(', at);
|
||||
String arguments = balancedArguments(source, open);
|
||||
if (arguments == null) {
|
||||
fail("括号没配平,扫描器会在 " + marker + " 处漏判(offset=" + at + ")");
|
||||
}
|
||||
outlets.add(new Outlet(lineOf(source, at), arguments));
|
||||
}
|
||||
}
|
||||
return outlets;
|
||||
}
|
||||
|
||||
private static int lineOf(String source, int offset) {
|
||||
int line = 1;
|
||||
for (int i = 0; i < offset; i++) {
|
||||
if (source.charAt(i) == '\n') {
|
||||
line++;
|
||||
}
|
||||
}
|
||||
return line;
|
||||
}
|
||||
|
||||
private static String balancedArguments(String source, int openParen) {
|
||||
int depth = 0;
|
||||
boolean inString = false;
|
||||
for (int i = openParen; i < source.length(); i++) {
|
||||
char c = source.charAt(i);
|
||||
if (inString) {
|
||||
if (c == '\\') {
|
||||
i++;
|
||||
} else if (c == '"') {
|
||||
inString = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (c == '"') {
|
||||
inString = true;
|
||||
} else if (c == '(') {
|
||||
depth++;
|
||||
} else if (c == ')') {
|
||||
depth--;
|
||||
if (depth == 0) {
|
||||
return source.substring(openParen + 1, i);
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static boolean containsChinese(String text) {
|
||||
for (int i = 0; i < text.length(); i++) {
|
||||
char c = text.charAt(i);
|
||||
if (c >= 0x4E00 && c <= 0x9FFF) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static String readSource(String moduleRelativePath) throws IOException {
|
||||
Path file = mainJavaRoot().resolve("com/nanri/aiimage/" + moduleRelativePath);
|
||||
if (!Files.isRegularFile(file)) {
|
||||
fail("找不到 " + file + " —— 用例依赖以 backend-java 为工作目录运行,别让守卫静默通过");
|
||||
}
|
||||
return Files.readString(file, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
/** surefire 的工作目录是模块目录;从仓库根或 IDE 跑时退到 backend-java/。 */
|
||||
private static Path mainJavaRoot() {
|
||||
Path here = Path.of("").toAbsolutePath();
|
||||
if (Files.isDirectory(here.resolve("src/main/java"))) {
|
||||
return here.resolve("src/main/java");
|
||||
}
|
||||
Path nested = here.resolve("backend-java");
|
||||
if (Files.isDirectory(nested.resolve("src/main/java"))) {
|
||||
return nested.resolve("src/main/java");
|
||||
}
|
||||
throw new IllegalStateException("无法定位 backend-java 模块目录(cwd=" + here + ")");
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -370,7 +370,7 @@ class SimilarAsinHistoryAssemblerTest {
|
||||
|
||||
BusinessException thrown = assertThrows(BusinessException.class,
|
||||
() -> assembler.buildHistoryItems(List.of(row), Map.of(10L, task(10L, "RUNNING", null)), jobMap()));
|
||||
assertTrue(thrown.getMessage().contains("chunk=2"), "异常附带 chunk 索引,实际: " + thrown.getMessage());
|
||||
assertTrue(thrown.getMessage().contains("分片=2"), "异常附带分片索引,实际: " + thrown.getMessage());
|
||||
|
||||
ArgumentCaptor<LambdaUpdateWrapper<TaskScopeStateEntity>> captor =
|
||||
ArgumentCaptor.forClass(LambdaUpdateWrapper.class);
|
||||
|
||||
+28
@@ -4,6 +4,7 @@ import com.nanri.aiimage.modules.task.mapper.TaskFileJobMapper;
|
||||
import com.nanri.aiimage.modules.task.model.entity.TaskFileJobEntity;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.core.task.TaskExecutor;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
@@ -13,6 +14,7 @@ import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
@@ -86,6 +88,32 @@ class TaskFileJobLocalDispatcherTest {
|
||||
verify(executor, times(1)).execute(any(Runnable.class));
|
||||
}
|
||||
|
||||
/**
|
||||
* 已 claim 的派发必须把 claim 那一刻的行快照原样带到执行处,且这条路径一次都不回读数据库。
|
||||
*
|
||||
* <p>线上任务 30456(2026-10-09)的反例:执行前 {@code selectById} 重读,读到的
|
||||
* {@code updated_at} 就是当前值,{@code activateRunningClaim} 的 CAS 于是恒真 ——
|
||||
* 排队排久了的旧派发能冒充成新持有者,撞锁后再用 {@code deferRunning} 把真持有者
|
||||
* 正在跑的行翻回 PENDING,那次的 {@code markSuccess} 静默 0 行更新、成功丢失。
|
||||
*/
|
||||
@Test
|
||||
void claimedDispatchCarriesTheSnapshotInsteadOfReReadingTheRow() {
|
||||
TaskFileJobEntity claim = job(7L);
|
||||
claim.setStatus("RUNNING");
|
||||
TaskFileJobEntity rowChangedAfterTheClaim = job(7L);
|
||||
rowChangedAfterTheClaim.setStatus("PENDING");
|
||||
when(taskFileJobMapper.selectById(7L)).thenReturn(rowChangedAfterTheClaim);
|
||||
|
||||
List<Runnable> captured = captureRunnables();
|
||||
assertTrue(dispatcher.dispatchClaimed(claim));
|
||||
captured.forEach(Runnable::run);
|
||||
|
||||
ArgumentCaptor<TaskFileJobEntity> passed = ArgumentCaptor.forClass(TaskFileJobEntity.class);
|
||||
verify(worker).processClaimed(passed.capture());
|
||||
assertSame(claim, passed.getValue(), "必须用 claim 快照,重读就等于没有围栏");
|
||||
verify(taskFileJobMapper, never()).selectById(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void test_task_073_dispatch_normal_multiple_items() throws Exception {
|
||||
// 批量场景:多个不同 jobId 依次 dispatch,互不冲突,全部受理。
|
||||
|
||||
+18
@@ -176,6 +176,24 @@ class TaskFileJobServiceTest {
|
||||
assertTrue(update.getValue().getParamNameValuePairs().containsValue("RUNNING"));
|
||||
}
|
||||
|
||||
/**
|
||||
* 围栏写没命中必须让调用方知道。2026-10-09 任务 30456 就是这里静默 0 行更新:
|
||||
* 结果文件已生成、可下载,作业行却被别人翻回了 PENDING,最后被重试打满判成 FAILED,
|
||||
* 界面上一个成功的任务显示成"结果生成失败"。
|
||||
*/
|
||||
@Test
|
||||
void markSuccessReportsWhetherTheFencedWriteLanded() {
|
||||
TaskFileJobEntity job = runningJob(109L, 1, LocalDateTime.now());
|
||||
TaskFileJobService service = new TaskFileJobService(taskFileJobMapper, applicationEventPublisher);
|
||||
|
||||
when(taskFileJobMapper.update(isNull(), any(LambdaUpdateWrapper.class))).thenReturn(0);
|
||||
assertFalse(service.markSuccess(job, "result.xlsx"),
|
||||
"行已不在本次执行手里时必须报未落库,不能静默");
|
||||
|
||||
when(taskFileJobMapper.update(isNull(), any(LambdaUpdateWrapper.class))).thenReturn(1);
|
||||
assertTrue(service.markSuccess(job, "result.xlsx"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void similarAsinHeartbeatOnlyTouchesStaleRunningAssembleJobs() {
|
||||
TaskFileJobService service = new TaskFileJobService(taskFileJobMapper, applicationEventPublisher);
|
||||
|
||||
+30
@@ -158,6 +158,36 @@ class TaskResultFileJobWorkerOrphanTest {
|
||||
verify(taskFileJobService).markFailedPermanent(job, "result record not found");
|
||||
}
|
||||
|
||||
/**
|
||||
* 2026-10-09 把各模块的"任务不存在/结果记录不存在"从英文换成中文后,孤儿判据必须照样命中:
|
||||
* 这两句是 {@code isOrphanJobFailure} 的匹配串,漏了这些作业就会对着已经不存在的任务白重试 5 次。
|
||||
*/
|
||||
@Test
|
||||
void orphanTaskNotFoundChineseMessage() throws Exception {
|
||||
TaskResultFileJobWorker worker = buildWorker();
|
||||
TaskFileJobEntity job = job("SHOP_MATCH", 3L, 13L);
|
||||
allowClaim(job);
|
||||
allowLock(job.getModuleType(), job.getTaskId());
|
||||
doThrow(new BusinessException("任务不存在")).when(shopMatch).processResultFileJob(job);
|
||||
|
||||
worker.process(job);
|
||||
|
||||
verify(taskFileJobService).markFailedPermanent(job, "任务不存在");
|
||||
}
|
||||
|
||||
@Test
|
||||
void orphanResultRecordNotFoundChineseMessage() throws Exception {
|
||||
TaskResultFileJobWorker worker = buildWorker();
|
||||
TaskFileJobEntity job = job("SHOP_MATCH", 4L, 14L);
|
||||
allowClaim(job);
|
||||
allowLock(job.getModuleType(), job.getTaskId());
|
||||
doThrow(new BusinessException("结果记录不存在")).when(shopMatch).processResultFileJob(job);
|
||||
|
||||
worker.process(job);
|
||||
|
||||
verify(taskFileJobService).markFailedPermanent(job, "结果记录不存在");
|
||||
}
|
||||
|
||||
@Test
|
||||
void orphanChineseMessages() throws Exception {
|
||||
TaskResultFileJobWorker worker = buildWorker();
|
||||
|
||||
+3
-3
@@ -125,7 +125,7 @@ class TaskResultFileJobWorkerOwnerRoutingTest {
|
||||
TaskFileJobEntity claim = claimedJob(PublishTaskService.MODULE_TYPE, 18524L, 26402L, "task:26402:owner:instance-a");
|
||||
when(taskFileJobService.claimRunnableJobsForOwner(20, "instance-a")).thenReturn(List.of(claim));
|
||||
when(taskFileJobService.activateRunningClaim(claim)).thenReturn(true);
|
||||
when(localDispatcher.dispatchClaimed(claim.getId(), claim.getTaskId(), claim.getModuleType())).thenReturn(false);
|
||||
when(localDispatcher.dispatchClaimed(claim)).thenReturn(false);
|
||||
when(taskDistributedLockService.acquire(PublishTaskService.MODULE_TYPE, claim.getTaskId(),
|
||||
TaskDistributedLockService.DEFAULT_WAIT_MILLIS)).thenReturn(lock);
|
||||
|
||||
@@ -142,11 +142,11 @@ class TaskResultFileJobWorkerOwnerRoutingTest {
|
||||
when(instanceMetadata.getInstanceId()).thenReturn("instance-a");
|
||||
TaskFileJobEntity claim = claimedJob(PublishTaskService.MODULE_TYPE, 18525L, 26403L, "task:26403:owner:instance-a");
|
||||
when(taskFileJobService.claimRunnableJobsForOwner(20, "instance-a")).thenReturn(List.of(claim));
|
||||
when(localDispatcher.dispatchClaimed(claim.getId(), claim.getTaskId(), claim.getModuleType())).thenReturn(true);
|
||||
when(localDispatcher.dispatchClaimed(claim)).thenReturn(true);
|
||||
|
||||
worker.runPendingJobs();
|
||||
|
||||
verify(localDispatcher).dispatchClaimed(claim.getId(), claim.getTaskId(), claim.getModuleType());
|
||||
verify(localDispatcher).dispatchClaimed(claim);
|
||||
verify(localDispatcher, never()).dispatch(anyLong(), anyLong(), any());
|
||||
verify(taskFileJobService, never()).claimRunning(anyLong());
|
||||
verify(publish, never()).processResultFileJob(any());
|
||||
|
||||
Reference in New Issue
Block a user