feat(jd-publish): 目标品牌建单+校验失败整单判死+改品牌原位重试(桌面协议 v3 服务端半边)
- 建单必填目标品牌(1–120 字符单行),走 /tasks/target-brand 独占路径,旧后端不会静默丢参数
- 激活与明细下发带 jdPublishProtocol,协议 <3 直接 409 要求升级客户端;明细 VO 下发 targetBrandName
- 预检失败回执(SOURCE/BRAND)必须带一条失败明细,整单判 FAILED 并落分类前缀;通用重试/继续对品牌失败任务拒绝
- 新增 /tasks/{taskId}/retry-brand:只允许无成功、无待确认记录的品牌失败任务改品牌后原位重试(世代+1、明细复位、回执直推本机队列)
- 兜底拉取按协议过滤带 targetBrandName 的 JD 上架任务,认领 CAS 带 resumeAttempt 防跨代误领
- 用户端:目标品牌必填输入、协议探测挡旧客户端、品牌失败弹窗与「修改品牌并重试」按钮
This commit is contained in:
@@ -0,0 +1,20 @@
|
||||
package com.nanri.aiimage.common.task;
|
||||
|
||||
/** Desktop contract shared by the JD publisher and the generic pull/retry routes. */
|
||||
public final class JdPublishProtocol {
|
||||
public static final int LEGACY = 2;
|
||||
public static final int TARGET_BRAND = 3;
|
||||
public static final String BRAND_FAILURE = "目标品牌校验失败:";
|
||||
public static final String SOURCE_FAILURE = "本店源商品校验失败:";
|
||||
|
||||
private JdPublishProtocol() {
|
||||
}
|
||||
|
||||
public static boolean supportsTargetBrand(Integer protocol) {
|
||||
return Integer.valueOf(TARGET_BRAND).equals(protocol);
|
||||
}
|
||||
|
||||
public static boolean needsBrandCorrection(String message) {
|
||||
return message != null && message.startsWith(BRAND_FAILURE);
|
||||
}
|
||||
}
|
||||
+16
-3
@@ -60,7 +60,7 @@ public class JdPublishController {
|
||||
private final TaskProgressOwnershipSupport progressOwnershipSupport;
|
||||
private final AdminAuthSupport adminAuthSupport;
|
||||
|
||||
@PostMapping("/tasks")
|
||||
@PostMapping({"/tasks", "/tasks/target-brand"})
|
||||
@Operation(summary = "创建京东商品上架任务", description = "勾选京东数据库商品(归属校验)+可选统一改价规则建单;"
|
||||
+ "任务落 PENDING、执行通道显式 LOCAL(本机已登录京麦的 Chrome 执行)、明细快照行随建单落库。"
|
||||
+ "响应体带 queuePayload(type=jd-product-publish-run),页面原样投 api.enqueue_json。")
|
||||
@@ -72,13 +72,25 @@ public class JdPublishController {
|
||||
adminAuthSupport.currentDeviceId(httpRequest)));
|
||||
}
|
||||
|
||||
@PostMapping("/tasks/{taskId}/retry-brand")
|
||||
public ApiResponse<JdPublishTaskVo> retryBrand(@PathVariable Long taskId,
|
||||
@Valid @RequestBody BrandRetryRequest request, HttpServletRequest httpRequest) {
|
||||
return ApiResponse.success(publishTaskService.retryWithBrand(taskId,
|
||||
adminAuthSupport.requireSessionOwnerUserId(httpRequest, null),
|
||||
request.resumeAttempt(), request.targetBrandName()));
|
||||
}
|
||||
|
||||
public record BrandRetryRequest(@jakarta.validation.constraints.NotNull Integer resumeAttempt, String targetBrandName) {}
|
||||
|
||||
@PostMapping("/tasks/{taskId}/activate")
|
||||
@Operation(summary = "认领当前代次的京东上架任务")
|
||||
public ApiResponse<Void> activate(@PathVariable Long taskId,
|
||||
@RequestParam("resumeAttempt") int resumeAttempt,
|
||||
@RequestParam(value = "jdPublishProtocol", required = false) Integer protocol,
|
||||
@RequestParam(value = "user_id", required = false) Long userId,
|
||||
HttpServletRequest httpRequest) {
|
||||
publishTaskService.activateTask(taskId, adminAuthSupport.requireSessionOwnerUserId(httpRequest, userId), resumeAttempt);
|
||||
publishTaskService.activateTask(taskId, adminAuthSupport.requireSessionOwnerUserId(httpRequest, userId),
|
||||
resumeAttempt, protocol);
|
||||
return ApiResponse.success(null);
|
||||
}
|
||||
|
||||
@@ -96,9 +108,10 @@ public class JdPublishController {
|
||||
@Parameter(description = "任务所属用户 ID;省略时取当前登录身份", required = false, example = "1")
|
||||
@RequestParam(value = "user_id", required = false) Long userId,
|
||||
@RequestParam("resumeAttempt") int resumeAttempt,
|
||||
@RequestParam(value = "jdPublishProtocol", required = false) Integer protocol,
|
||||
HttpServletRequest httpRequest) {
|
||||
return ApiResponse.success(publishTaskService.pullItems(taskId,
|
||||
adminAuthSupport.requireSessionOwnerUserId(httpRequest, userId), resumeAttempt, cursor, limit));
|
||||
adminAuthSupport.requireSessionOwnerUserId(httpRequest, userId), resumeAttempt, cursor, limit, protocol));
|
||||
}
|
||||
|
||||
@GetMapping("/tasks/{taskId}/progress")
|
||||
|
||||
+5
@@ -35,6 +35,11 @@ public class JdPublishChunkRequest {
|
||||
*/
|
||||
private String error;
|
||||
|
||||
/** 提交前明确阻断:SOURCE(源商品/店铺)或 BRAND(目标品牌)。 */
|
||||
private PreflightFailure preflightFailure;
|
||||
|
||||
public enum PreflightFailure { SOURCE, BRAND }
|
||||
|
||||
/** 单行回传结果。 */
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
|
||||
+3
@@ -27,6 +27,9 @@ public class JdPublishTaskCreateRequest {
|
||||
/** 统一改价规则(可选;null=按原价,mode=none)。 */
|
||||
private PriceRule priceRule;
|
||||
|
||||
/** 本次任务统一使用的目标品牌名,不回写商品库。 */
|
||||
private String targetBrandName;
|
||||
|
||||
/** 统一改价规则:none 原价 / percent 加价百分比(value=百分数) / fixed 固定加价(value=金额)。 */
|
||||
@Data
|
||||
public static class PriceRule {
|
||||
|
||||
+3
@@ -15,6 +15,9 @@ import java.util.List;
|
||||
public class JdPublishItemsPageVo {
|
||||
|
||||
private Long taskId;
|
||||
|
||||
/** 旧任务为空,沿用京麦预填。 */
|
||||
private String targetBrandName;
|
||||
private int resumeAttempt;
|
||||
|
||||
/** 本页明细行。 */
|
||||
|
||||
+31
@@ -3,10 +3,12 @@ package com.nanri.aiimage.modules.jd.service;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.task.JdPublishProtocol;
|
||||
import com.nanri.aiimage.common.task.TaskStatuses;
|
||||
import com.nanri.aiimage.modules.jd.mapper.JdPublishItemMapper;
|
||||
import com.nanri.aiimage.modules.jd.model.dto.JdPublishChunkRequest;
|
||||
import com.nanri.aiimage.modules.jd.model.dto.JdPublishChunkRequest.ItemResult;
|
||||
import com.nanri.aiimage.modules.jd.model.dto.JdPublishChunkRequest.PreflightFailure;
|
||||
import com.nanri.aiimage.modules.jd.model.entity.JdPublishItemEntity;
|
||||
import com.nanri.aiimage.modules.jd.model.vo.JdPublishChunkVo;
|
||||
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
|
||||
@@ -66,6 +68,7 @@ public class JdPublishIngestService {
|
||||
throw new BusinessException(409, "任务不在运行中,请先激活任务再回传");
|
||||
}
|
||||
|
||||
String preflightMessage = preflightMessage(request, items);
|
||||
int accepted = 0;
|
||||
String newlyFailedReason = null;
|
||||
Set<Long> seen = new HashSet<>();
|
||||
@@ -91,6 +94,8 @@ public class JdPublishIngestService {
|
||||
vo.setNeedsReview(Boolean.TRUE.equals(request.getIsEnd()) && vo.getPublishingCount() > 0);
|
||||
if (terminal) {
|
||||
vo.setTaskStatus(task.getStatus());
|
||||
} else if (preflightMessage != null && accepted == 1) {
|
||||
vo.setTaskStatus(finish(task, counts, TaskStatuses.FileTask.FAILED, preflightMessage));
|
||||
} else if (newlyFailedReason != null && staleTaskService.terminalizeOnJdLoginFatal(task, newlyFailedReason)) {
|
||||
vo.setTaskStatus(TaskStatuses.FileTask.FAILED);
|
||||
} else if (Boolean.TRUE.equals(request.getIsEnd())) {
|
||||
@@ -149,6 +154,12 @@ public class JdPublishIngestService {
|
||||
}
|
||||
String status = failed > 0 ? TaskStatuses.FileTask.FAILED : TaskStatuses.FileTask.SUCCESS;
|
||||
String message = failed > 0 ? "发布完成:成功 " + success + " 行,失败 " + failed + " 行" : null;
|
||||
return finish(task, counts, status, message);
|
||||
}
|
||||
|
||||
private String finish(FileTaskEntity task, Map<String, Long> counts, String status, String message) {
|
||||
long success = counts.getOrDefault(ITEM_SUCCESS, 0L);
|
||||
long failed = counts.getOrDefault(ITEM_FAILED, 0L);
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
int updated = fileTaskMapper.update(null, new LambdaUpdateWrapper<FileTaskEntity>()
|
||||
.eq(FileTaskEntity::getId, task.getId())
|
||||
@@ -169,6 +180,26 @@ public class JdPublishIngestService {
|
||||
return RUNNING;
|
||||
}
|
||||
|
||||
private static String preflightMessage(JdPublishChunkRequest request, List<ItemResult> items) {
|
||||
if (request.getPreflightFailure() == null) {
|
||||
return null;
|
||||
}
|
||||
if (items.size() != 1 || items.getFirst() == null
|
||||
|| !ITEM_FAILED.equals(normalizeStatus(items.getFirst().getPublishStatus()))) {
|
||||
throw new BusinessException(400, "上架校验阻断须同时回传一条失败明细");
|
||||
}
|
||||
String error = truncate(items.getFirst().getPublishError());
|
||||
if (error == null || error.isEmpty()) {
|
||||
throw new BusinessException(400, "上架校验阻断须同时回传失败原因");
|
||||
}
|
||||
String prefix = request.getPreflightFailure() == PreflightFailure.BRAND
|
||||
? JdPublishProtocol.BRAND_FAILURE : JdPublishProtocol.SOURCE_FAILURE;
|
||||
String message = prefix + error;
|
||||
// biz_file_task.error_message 比发布明细的 publish_error 短。
|
||||
int end = message.offsetByCodePoints(0, Math.min(1000, message.codePointCount(0, message.length())));
|
||||
return message.substring(0, end);
|
||||
}
|
||||
|
||||
private Map<String, Long> statusCounts(Long taskId) {
|
||||
Map<String, Long> counts = new HashMap<>();
|
||||
for (Map<String, Object> row : jdPublishItemMapper.countByPublishStatus(taskId)) {
|
||||
|
||||
+89
-8
@@ -8,7 +8,9 @@ import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.mapper.AdminUserMapper;
|
||||
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.common.task.JdPublishProtocol;
|
||||
import com.nanri.aiimage.common.task.TaskStatuses;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.nanri.aiimage.config.CollectRoutingProperties;
|
||||
import com.nanri.aiimage.modules.file.service.oss.OssStorageService;
|
||||
import com.nanri.aiimage.modules.jd.mapper.JdProductImageMapper;
|
||||
@@ -106,6 +108,7 @@ public class JdPublishTaskService {
|
||||
private final ObjectMapper objectMapper;
|
||||
private final TaskHeartbeatService taskHeartbeatService;
|
||||
private final TaskHeartbeatPositionService taskHeartbeatPositionService;
|
||||
private final JdPublishTaskItemsResetSpiImpl itemsReset;
|
||||
|
||||
/** 下发批大小出厂值(aiimage.jd.publish.items-batch-size,服务侧钳制上限 100)。 */
|
||||
@Value("${aiimage.jd.publish.items-batch-size:20}")
|
||||
@@ -150,12 +153,8 @@ public class JdPublishTaskService {
|
||||
task.setDeviceId(AdminAuthSupport.normalizeDeviceId(deviceId));
|
||||
task.setCreatedAt(now);
|
||||
task.setUpdatedAt(now);
|
||||
try {
|
||||
task.setRequestJson(objectMapper.writeValueAsString(request));
|
||||
task.setResultJson("{}");
|
||||
} catch (Exception ex) {
|
||||
throw new BusinessException("序列化建单载荷失败", ex);
|
||||
}
|
||||
task.setRequestJson(writeCreateRequest(request));
|
||||
task.setResultJson("{}");
|
||||
fileTaskMapper.insert(task);
|
||||
|
||||
// 建单即落明细快照行(蓝图 §3):标题/类目/价格折算/库存/店铺/编码随行固化,
|
||||
@@ -178,9 +177,10 @@ public class JdPublishTaskService {
|
||||
}
|
||||
|
||||
/** 仅当前代次的 PENDING 任务能被页面队列中的桌面执行器认领。 */
|
||||
public void activateTask(Long taskId, Long userId, int attempt) {
|
||||
public void activateTask(Long taskId, Long userId, int attempt, Integer protocol) {
|
||||
FileTaskEntity task = requireOwnedTask(taskId, userId);
|
||||
requireAttempt(task, attempt);
|
||||
targetBrandForClient(task, protocol);
|
||||
int updated = fileTaskMapper.update(null, new LambdaUpdateWrapper<FileTaskEntity>()
|
||||
.eq(FileTaskEntity::getId, taskId)
|
||||
.eq(FileTaskEntity::getUserId, userId)
|
||||
@@ -198,9 +198,11 @@ public class JdPublishTaskService {
|
||||
* 重连 cursor 归零也不会重发已发布商品,AC-4 服务端半边);SKU 价按改价规则折算;
|
||||
* 图片发 jd-products 桶预签名 GET URL(蓝图 §3)。
|
||||
*/
|
||||
public JdPublishItemsPageVo pullItems(Long taskId, Long userId, int attempt, Long cursor, Integer limit) {
|
||||
public JdPublishItemsPageVo pullItems(Long taskId, Long userId, int attempt, Long cursor, Integer limit,
|
||||
Integer protocol) {
|
||||
FileTaskEntity task = requireOwnedTask(taskId, userId);
|
||||
requireAttempt(task, attempt);
|
||||
String targetBrand = targetBrandForClient(task, protocol);
|
||||
if (!STATUS_RUNNING.equals(task.getStatus())) {
|
||||
throw new BusinessException(409, "任务未在运行,不能下发发布明细");
|
||||
}
|
||||
@@ -216,6 +218,7 @@ public class JdPublishTaskService {
|
||||
JdPublishItemsPageVo vo = new JdPublishItemsPageVo();
|
||||
vo.setTaskId(taskId);
|
||||
vo.setResumeAttempt(attempt);
|
||||
vo.setTargetBrandName(targetBrand);
|
||||
vo.setItems(rows.isEmpty() ? List.of() : rows.stream()
|
||||
.map(row -> buildItemPayload(row, productsByPid.get(row.getProductId())))
|
||||
.toList());
|
||||
@@ -265,6 +268,9 @@ public class JdPublishTaskService {
|
||||
Map<String, Object> data = new LinkedHashMap<>();
|
||||
data.put("taskId", task.getId());
|
||||
data.put("resumeAttempt", resumeAttempt(task));
|
||||
if (create.getTargetBrandName() != null) {
|
||||
data.put("targetBrandRequired", true);
|
||||
}
|
||||
data.put("priceRule", create.getPriceRule() == null ? Map.of("mode", "none") : create.getPriceRule());
|
||||
return Map.of("type", JdPublishTaskPullSpiImpl.QUEUE_TYPE, "data", data);
|
||||
}
|
||||
@@ -337,9 +343,84 @@ public class JdPublishTaskService {
|
||||
throw new BusinessException("单次上架最多选 " + MAX_PRODUCT_IDS + " 个商品,当前 "
|
||||
+ request.getProductIds().size() + " 个");
|
||||
}
|
||||
request.setTargetBrandName(requireTargetBrand(request.getTargetBrandName()));
|
||||
normalizePriceRule(request);
|
||||
}
|
||||
|
||||
private static String requireTargetBrand(String value) {
|
||||
String brand = value == null ? "" : value.strip();
|
||||
if (brand.isEmpty()) {
|
||||
throw new BusinessException(400, "请填写目标品牌");
|
||||
}
|
||||
if (brand.length() > 120 || brand.codePoints().anyMatch(Character::isISOControl)) {
|
||||
throw new BusinessException(400, "目标品牌须为不超过 120 个字符的单行名称");
|
||||
}
|
||||
return brand;
|
||||
}
|
||||
|
||||
private String writeCreateRequest(JdPublishTaskCreateRequest request) {
|
||||
try {
|
||||
return objectMapper.writeValueAsString(request);
|
||||
} catch (JsonProcessingException ex) {
|
||||
throw new BusinessException("序列化建单载荷失败", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private String targetBrandForClient(FileTaskEntity task, Integer protocol) {
|
||||
String brand = readCreateRequest(task).getTargetBrandName();
|
||||
if (brand != null && !JdPublishProtocol.supportsTargetBrand(protocol)) {
|
||||
throw new BusinessException(409, "请升级数富客户端后再执行目标品牌上架任务");
|
||||
}
|
||||
return brand;
|
||||
}
|
||||
|
||||
/** 与发布回执锁同一条父任务,品牌修正和换代必须一起提交。 */
|
||||
@Transactional
|
||||
public JdPublishTaskVo retryWithBrand(Long taskId, Long userId, int attempt, String rawBrand) {
|
||||
String brand = requireTargetBrand(rawBrand);
|
||||
FileTaskEntity task = assertOwnedTask(fileTaskMapper.selectByIdForUpdate(taskId), userId);
|
||||
requireAttempt(task, attempt);
|
||||
if (!TaskStatuses.FileTask.FAILED.equals(task.getStatus())
|
||||
|| !JdPublishProtocol.needsBrandCorrection(task.getErrorMessage())) {
|
||||
throw new BusinessException(409, "只有目标品牌校验失败的任务才能修改品牌后重试");
|
||||
}
|
||||
Map<String, Long> counts = aggregateStatusCounts(taskId);
|
||||
if (counts.getOrDefault(ITEM_SUCCESS, 0L) > 0 || counts.getOrDefault(ITEM_PUBLISHING, 0L) > 0) {
|
||||
throw new BusinessException(409, "已有发布成功或待确认记录,不能修改本任务品牌;请先在京麦核对");
|
||||
}
|
||||
JdPublishTaskCreateRequest create = readCreateRequest(task);
|
||||
if (Objects.equals(brand, create.getTargetBrandName())) {
|
||||
throw new BusinessException(400, "请输入正确的目标品牌,不能原样重试");
|
||||
}
|
||||
create.setTargetBrandName(brand);
|
||||
String requestJson = writeCreateRequest(create);
|
||||
int updated = fileTaskMapper.update(null, new LambdaUpdateWrapper<FileTaskEntity>()
|
||||
.eq(FileTaskEntity::getId, taskId)
|
||||
.eq(FileTaskEntity::getStatus, TaskStatuses.FileTask.FAILED)
|
||||
.eq(FileTaskEntity::getResumeAttempt, attempt)
|
||||
.set(FileTaskEntity::getRequestJson, requestJson)
|
||||
.set(FileTaskEntity::getResumeAttempt, attempt + 1)
|
||||
.set(FileTaskEntity::getStatus, STATUS_PENDING)
|
||||
.set(FileTaskEntity::getSuccessFileCount, 0)
|
||||
.set(FileTaskEntity::getFailedFileCount, 0)
|
||||
.set(FileTaskEntity::getErrorMessage, null)
|
||||
.set(FileTaskEntity::getFailureCategory, null)
|
||||
.set(FileTaskEntity::getFinishedAt, null)
|
||||
.set(FileTaskEntity::getUpdatedAt, LocalDateTime.now()));
|
||||
if (updated != 1) {
|
||||
throw new BusinessException(409, "任务状态已变化,请刷新后再试");
|
||||
}
|
||||
itemsReset.resetForRetry(taskId);
|
||||
task.setRequestJson(requestJson);
|
||||
task.setResumeAttempt(attempt + 1);
|
||||
JdPublishTaskVo vo = new JdPublishTaskVo();
|
||||
vo.setTaskId(taskId);
|
||||
vo.setTaskNo(task.getTaskNo());
|
||||
vo.setCollectChannel(task.getCollectChannel());
|
||||
vo.setQueuePayload(buildQueuePayload(task));
|
||||
return vo;
|
||||
}
|
||||
|
||||
/** 改价规则归一化写回请求体:request_json 里的值必须就是闸门认可的值(铁律 27a 同源)。 */
|
||||
private void normalizePriceRule(JdPublishTaskCreateRequest request) {
|
||||
PriceRule rule = request.getPriceRule();
|
||||
|
||||
+1
-4
@@ -28,8 +28,6 @@ import java.util.List;
|
||||
@Tag(name = "任务兜底拉取", description = "供桌面客户端领取页面未推送成功的待执行任务")
|
||||
public class TaskClientPullController {
|
||||
|
||||
private static final Integer JD_PUBLISH_PROTOCOL = 2;
|
||||
|
||||
private final TaskClientPullService taskClientPullService;
|
||||
private final AdminAuthSupport adminAuthSupport;
|
||||
|
||||
@@ -41,7 +39,6 @@ public class TaskClientPullController {
|
||||
public ApiResponse<List<TaskClientPullVo>> pullPending(HttpServletRequest request,
|
||||
@RequestParam(name = "jdPublishProtocol", required = false) Integer jdPublishProtocol) {
|
||||
AdminUserEntity me = adminAuthSupport.requireUser(request);
|
||||
return ApiResponse.success(taskClientPullService.pullPendingTasks(me.getId(),
|
||||
JD_PUBLISH_PROTOCOL.equals(jdPublishProtocol)));
|
||||
return ApiResponse.success(taskClientPullService.pullPendingTasks(me.getId(), jdPublishProtocol));
|
||||
}
|
||||
}
|
||||
|
||||
+2
-1
@@ -44,7 +44,8 @@ public interface FileTaskMapper extends BaseMapper<FileTaskEntity> {
|
||||
@Param("moduleTypes") List<String> moduleTypes,
|
||||
@Param("localDefaultModules") List<String> localDefaultModules,
|
||||
@Param("cutoff") LocalDateTime cutoff,
|
||||
@Param("limit") int limit);
|
||||
@Param("limit") int limit,
|
||||
@Param("supportsTargetBrand") boolean supportsTargetBrand);
|
||||
|
||||
/**
|
||||
* 服务端内部认领候选(Linux 后台 worker):指定状态 + 白名单模块 + 创建早于 cutoff,
|
||||
|
||||
+11
-7
@@ -1,6 +1,7 @@
|
||||
package com.nanri.aiimage.modules.task.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.nanri.aiimage.common.task.JdPublishProtocol;
|
||||
import com.nanri.aiimage.config.CollectRoutingProperties;
|
||||
import com.nanri.aiimage.config.InstanceMetadata;
|
||||
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
|
||||
@@ -128,10 +129,10 @@ public class TaskClientPullService {
|
||||
|
||||
/** 拉取并认领该用户"长期未被领取"的任务,按创建时间升序返回,最多 limit 条。 */
|
||||
public List<TaskClientPullVo> pullPendingTasks(Long userId) {
|
||||
return pullPendingTasks(userId, false);
|
||||
return pullPendingTasks(userId, null);
|
||||
}
|
||||
|
||||
public List<TaskClientPullVo> pullPendingTasks(Long userId, boolean jdPublishV2) {
|
||||
public List<TaskClientPullVo> pullPendingTasks(Long userId, Integer jdPublishProtocol) {
|
||||
if (!enabled) {
|
||||
return List.of();
|
||||
}
|
||||
@@ -139,7 +140,8 @@ public class TaskClientPullService {
|
||||
return List.of();
|
||||
}
|
||||
List<String> types = resolveModuleTypes();
|
||||
if (!jdPublishV2) {
|
||||
boolean supportsTargetBrand = JdPublishProtocol.supportsTargetBrand(jdPublishProtocol);
|
||||
if (!supportsTargetBrand && !Integer.valueOf(JdPublishProtocol.LEGACY).equals(jdPublishProtocol)) {
|
||||
types = withoutJdPublish(types);
|
||||
}
|
||||
if (types.isEmpty()) {
|
||||
@@ -153,7 +155,7 @@ public class TaskClientPullService {
|
||||
LocalDateTime cutoff = LocalDateTime.now(DB_ZONE).minusMinutes(Math.max(1L, minPendingMinutes));
|
||||
int safeLimit = Math.max(1, Math.min(limit, MAX_LIMIT));
|
||||
List<FileTaskEntity> candidates = fileTaskMapper.selectLocalChannelPendingTasks(
|
||||
userId, STATUS_PENDING, types, CollectChannel.localDefaultModuleTypes(), cutoff, safeLimit);
|
||||
userId, STATUS_PENDING, types, CollectChannel.localDefaultModuleTypes(), cutoff, safeLimit, supportsTargetBrand);
|
||||
if (candidates.isEmpty() && !types.isEmpty()) {
|
||||
log.info("[client-task-pull] 白名单内没有本机通道的排队任务,本次不拉取 userId={} moduleTypes={}",
|
||||
userId, moduleTypes);
|
||||
@@ -218,7 +220,7 @@ public class TaskClientPullService {
|
||||
candidate.getId(), candidate.getModuleType());
|
||||
continue;
|
||||
}
|
||||
if (!claim(candidate.getId())) {
|
||||
if (!claim(candidate)) {
|
||||
log.info("[client-task-pull] 任务已被页面领取或状态已变化,跳过 taskId={}", candidate.getId());
|
||||
continue;
|
||||
}
|
||||
@@ -279,10 +281,12 @@ public class TaskClientPullService {
|
||||
* (ensureTaskOwnedByCurrentInstance)会拒绝(2026-09-30 内部认领上线实测:
|
||||
* 任务 parse 落 server-110、认领在 server-121,组装载荷被拒并误标失败)。
|
||||
*/
|
||||
private boolean claim(Long taskId) {
|
||||
private boolean claim(FileTaskEntity candidate) {
|
||||
return fileTaskMapper.update(null, new LambdaUpdateWrapper<FileTaskEntity>()
|
||||
.eq(FileTaskEntity::getId, taskId)
|
||||
.eq(FileTaskEntity::getId, candidate.getId())
|
||||
.eq(FileTaskEntity::getStatus, STATUS_PENDING)
|
||||
.eq(CollectRoutingProperties.MODULE_JD_PUBLISH.equals(candidate.getModuleType()),
|
||||
FileTaskEntity::getResumeAttempt, candidate.getResumeAttempt())
|
||||
.set(FileTaskEntity::getStatus, STATUS_RUNNING)
|
||||
.set(FileTaskEntity::getUpdatedAt, LocalDateTime.now())
|
||||
.set(FileTaskEntity::getOwnerInstanceId, currentInstanceId())) > 0;
|
||||
|
||||
+11
@@ -2,6 +2,7 @@ package com.nanri.aiimage.modules.task.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.nanri.aiimage.common.task.JdPublishProtocol;
|
||||
import com.nanri.aiimage.common.task.TaskStatuses;
|
||||
import com.nanri.aiimage.modules.task.mapper.FileResultMapper;
|
||||
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
|
||||
@@ -80,6 +81,9 @@ public class TaskInPlaceRetryService {
|
||||
if (task == null || task.getId() == null) {
|
||||
return false;
|
||||
}
|
||||
if (requiresBrandCorrection(task)) {
|
||||
return false;
|
||||
}
|
||||
if (STATUS_CANCELLED.equals(task.getStatus())) {
|
||||
// 「继续」前先清模块补检预算:失败即中止(此刻任务一行未动,用户重按即可)。
|
||||
// 刻意不包 try/catch——本仓静默 catch 台账只许减,且放在 CAS 之前不会留下
|
||||
@@ -222,11 +226,18 @@ public class TaskInPlaceRetryService {
|
||||
if (!STATUS_FAILED.equals(task.getStatus()) && !STATUS_CANCELLED.equals(task.getStatus())) {
|
||||
throw new com.nanri.aiimage.common.exception.BusinessException("只有失败或已中断的任务可以继续");
|
||||
}
|
||||
if (requiresBrandCorrection(task)) {
|
||||
throw new com.nanri.aiimage.common.exception.BusinessException("请先修改目标品牌,再重试上架任务");
|
||||
}
|
||||
if (!retryInPlace(task)) {
|
||||
throw new com.nanri.aiimage.common.exception.BusinessException("任务状态已变化,请刷新后再试");
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean requiresBrandCorrection(FileTaskEntity task) {
|
||||
return "JD_PUBLISH".equals(task.getModuleType()) && JdPublishProtocol.needsBrandCorrection(task.getErrorMessage());
|
||||
}
|
||||
|
||||
/**
|
||||
* 模块侧明细行复位(AC-7 服务端半边):京东上架的行级真源在 biz_jd_publish_item,
|
||||
* 上一代的 FAILED/PUBLISHING 行不复位,重试后的明细分批下发(只出 PENDING 行)就是
|
||||
|
||||
@@ -30,7 +30,7 @@
|
||||
<!-- 客户端兜底拉取候选(P1-1):通道谓词与 status/模块/时间窗口同在 WHERE 里,LIMIT 之后不再有 Java 过滤。 -->
|
||||
<select id="selectLocalChannelPendingTasks"
|
||||
resultType="com.nanri.aiimage.modules.task.model.entity.FileTaskEntity">
|
||||
SELECT id, module_type, collect_channel, created_at
|
||||
SELECT id, module_type, collect_channel, created_at, resume_attempt
|
||||
FROM biz_file_task
|
||||
WHERE user_id = #{userId}
|
||||
AND status = #{status}
|
||||
@@ -38,6 +38,10 @@
|
||||
<foreach collection="moduleTypes" item="module" open="(" separator="," close=")">#{module}</foreach>
|
||||
AND created_at < #{cutoff}
|
||||
AND <include refid="resolvedChannelCase"/> = 'LOCAL'
|
||||
<if test="supportsTargetBrand == false">
|
||||
AND (module_type != 'JD_PUBLISH'
|
||||
OR COALESCE(JSON_TYPE(JSON_EXTRACT(request_json, '$.targetBrandName')), 'NULL') = 'NULL')
|
||||
</if>
|
||||
ORDER BY created_at ASC
|
||||
LIMIT #{limit}
|
||||
</select>
|
||||
|
||||
Reference in New Issue
Block a user