修改完善这个专利部分

This commit is contained in:
super
2026-05-15 16:06:12 +08:00
parent 8a450cf397
commit a1d658885f
44 changed files with 2841 additions and 2553 deletions
@@ -3,6 +3,7 @@ package com.nanri.aiimage.modules.similarasin.client;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.config.SimilarAsinProperties;
import com.nanri.aiimage.modules.coze.service.CozeCredentialPoolService;
import com.nanri.aiimage.modules.similarasin.model.dto.SimilarAsinResultRowDto;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@@ -19,22 +20,26 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
@Component
@RequiredArgsConstructor
@Slf4j
public class SimilarAsinCozeClient {
private static final String MODULE_TYPE = "SIMILAR_ASIN";
private static final MediaType APPLICATION_JSON_UTF8 = new MediaType("application", "json", StandardCharsets.UTF_8);
private final SimilarAsinProperties properties;
private final ObjectMapper objectMapper;
private final CozeCredentialPoolService cozeCredentialPoolService;
private final AtomicLong credentialCursor = new AtomicLong();
public List<SimilarAsinResultRowDto> inspect(List<SimilarAsinResultRowDto> rows, String prompt, String apiKey) {
if (rows == null || rows.isEmpty()) {
return List.of();
}
if (properties.getCozeToken() == null || properties.getCozeToken().isBlank()) {
if (!hasConfiguredCredential()) {
log.warn("[similar-asin] coze token not configured, keep raw rows size={}", rows.size());
return rows.stream().map(this::copy).toList();
}
@@ -48,17 +53,31 @@ public class SimilarAsinCozeClient {
}
public CozeSubmitResponse submitWorkflow(List<SimilarAsinResultRowDto> rows, String prompt, String apiKey) throws Exception {
JsonNode submitRoot = objectMapper.readTree(postWorkflow(rows, prompt, apiKey));
return submitWorkflow(rows, prompt, apiKey, nextCredential());
}
public CozeSubmitResponse submitWorkflow(List<SimilarAsinResultRowDto> rows,
String prompt,
String apiKey,
CozeCredentialRef credential) throws Exception {
CozeCredentialRef resolvedCredential = resolveCredential(credential);
JsonNode submitRoot = objectMapper.readTree(postWorkflow(rows, prompt, apiKey, resolvedCredential));
ensureSuccess(submitRoot);
return new CozeSubmitResponse(
extractExecuteId(submitRoot),
extractResultDataText(submitRoot),
writeJson(submitRoot)
writeJson(submitRoot),
resolvedCredential.name()
);
}
public CozePollResponse pollWorkflow(String executeId) throws Exception {
JsonNode pollRoot = objectMapper.readTree(getWorkflowHistory(executeId));
return pollWorkflow(executeId, null);
}
public CozePollResponse pollWorkflow(String executeId, CozeCredentialRef credential) throws Exception {
CozeCredentialRef resolvedCredential = resolveCredential(credential);
JsonNode pollRoot = objectMapper.readTree(getWorkflowHistory(executeId, resolvedCredential));
ensureSuccess(pollRoot);
String status = normalize(resolveWorkflowStatus(pollRoot)).toUpperCase(Locale.ROOT);
String dataText = extractResultDataText(pollRoot);
@@ -66,7 +85,8 @@ public class SimilarAsinCozeClient {
String failureMessage = isFailedWorkflowStatus(status)
? firstNonBlank(resolveFailureMessage(pollRoot), "Coze async workflow failed")
: "";
return new CozePollResponse(executeId, status, dataText, outputText, failureMessage, writeJson(pollRoot));
return new CozePollResponse(executeId, status, dataText, outputText, failureMessage, writeJson(pollRoot),
resolvedCredential.name());
}
public List<SimilarAsinResultRowDto> mergeRowsFromDataText(List<SimilarAsinResultRowDto> rows, String dataText) throws Exception {
@@ -161,7 +181,8 @@ public class SimilarAsinCozeClient {
}
private String runWorkflowAsyncAndWait(List<SimilarAsinResultRowDto> rows, String prompt, String apiKey) throws Exception {
JsonNode submitRoot = objectMapper.readTree(postWorkflow(rows, prompt, apiKey));
CozeCredentialRef credential = nextCredential();
JsonNode submitRoot = objectMapper.readTree(postWorkflow(rows, prompt, apiKey, credential));
ensureSuccess(submitRoot);
String immediateData = extractResultDataText(submitRoot);
@@ -177,7 +198,7 @@ public class SimilarAsinCozeClient {
long deadline = System.currentTimeMillis() + Math.max(10000, properties.getCozePollTimeoutMillis());
while (System.currentTimeMillis() < deadline) {
ensureNotInterrupted();
JsonNode pollRoot = objectMapper.readTree(getWorkflowHistory(executeId));
JsonNode pollRoot = objectMapper.readTree(getWorkflowHistory(executeId, credential));
ensureSuccess(pollRoot);
String dataText = extractResultDataText(pollRoot);
@@ -202,23 +223,27 @@ public class SimilarAsinCozeClient {
throw new IllegalStateException("Coze async workflow poll timeout");
}
private String postWorkflow(List<SimilarAsinResultRowDto> rows, String prompt, String apiKey) {
private String postWorkflow(List<SimilarAsinResultRowDto> rows,
String prompt,
String apiKey,
CozeCredentialRef credential) {
Map<String, Object> parameters = buildParameters(rows, prompt, apiKey);
Map<String, Object> body = new LinkedHashMap<>();
body.put("workflow_id", properties.getCozeWorkflowId());
body.put("workflow_id", credential.workflowId());
body.put("parameters", parameters);
if (apiKey != null && !apiKey.isBlank()) {
body.put("api_key", apiKey.trim());
}
body.put("is_async", Boolean.TRUE);
log.info("[similar-asin] coze request url={} body={}",
log.info("[similar-asin] coze request credential={} url={} body={}",
credential.name(),
joinUrl(properties.getCozeBaseUrl(), properties.getCozeWorkflowPath()),
writeJson(maskCozeRequestBody(body)));
RestClient.RequestBodySpec request = restClient().post()
.uri(joinUrl(properties.getCozeBaseUrl(), properties.getCozeWorkflowPath()))
.headers(headers -> {
headers.setBearerAuth(stripBearer(properties.getCozeToken()));
headers.setBearerAuth(stripBearer(credential.token()));
headers.setContentType(APPLICATION_JSON_UTF8);
headers.set(HttpHeaders.ACCEPT_CHARSET, StandardCharsets.UTF_8.name());
});
@@ -233,28 +258,98 @@ public class SimilarAsinCozeClient {
});
}
private String getWorkflowHistory(String executeId) {
private String getWorkflowHistory(String executeId, CozeCredentialRef credential) {
String path = properties.getCozeWorkflowHistoryPath()
.replace("{workflow_id}", properties.getCozeWorkflowId())
.replace("{workflow_id}", credential.workflowId())
.replace("{execute_id}", executeId);
return restClient().get()
.uri(joinUrl(properties.getCozeBaseUrl(), path))
.headers(headers -> {
headers.setBearerAuth(stripBearer(properties.getCozeToken()));
headers.setBearerAuth(stripBearer(credential.token()));
headers.setContentType(APPLICATION_JSON_UTF8);
headers.set(HttpHeaders.ACCEPT_CHARSET, StandardCharsets.UTF_8.name());
})
.exchange((clientRequest, clientResponse) -> {
byte[] responseBytes = StreamUtils.copyToByteArray(clientResponse.getBody());
String responseText = responseBytes.length == 0 ? "" : new String(responseBytes, StandardCharsets.UTF_8);
log.info("[similar-asin] coze history response executeId={} status={} body={}",
executeId,
log.info("[similar-asin] coze history response credential={} executeId={} status={} body={}",
credential.name(), executeId,
clientResponse.getStatusCode(),
responseText);
return responseText;
});
}
public CozeCredentialRef nextCredential() {
List<CozeCredentialPoolService.CozeCredential> pooledCredentials = cozeCredentialPoolService.listEnabled(MODULE_TYPE);
CozeCredentialPoolService.CozeCredential pooledCredential =
cozeCredentialPoolService.chooseRoundRobin(MODULE_TYPE, pooledCredentials, properties.getCozeCredentialStripeSize());
if (pooledCredential != null) {
return new CozeCredentialRef(pooledCredential.name(), pooledCredential.workflowId(), pooledCredential.token(),
pooledCredential.maxConcurrent());
}
List<CozeCredentialRef> credentials = configuredCredentials();
int stripeSize = Math.max(1, properties.getCozeCredentialStripeSize());
long cursor = Math.max(0L, credentialCursor.getAndIncrement());
int index = (int) ((cursor / stripeSize) % credentials.size());
return credentials.get(index);
}
public CozeCredentialRef credentialByName(String name) {
if (name == null || name.isBlank()) {
return nextCredential();
}
String normalizedName = normalize(name);
for (CozeCredentialRef credential : configuredCredentials()) {
if (normalize(credential.name()).equals(normalizedName)) {
return credential;
}
}
return nextCredential();
}
public boolean hasConfiguredCredential() {
return !configuredCredentials().isEmpty();
}
public int configuredCredentialCount() {
return configuredCredentials().size();
}
private CozeCredentialRef resolveCredential(CozeCredentialRef credential) {
return credential == null ? nextCredential() : credential;
}
private List<CozeCredentialRef> configuredCredentials() {
List<CozeCredentialRef> credentials = new ArrayList<>();
for (CozeCredentialPoolService.CozeCredential credential : cozeCredentialPoolService.listEnabled(MODULE_TYPE)) {
credentials.add(new CozeCredentialRef(credential.name(), credential.workflowId(), credential.token(),
credential.maxConcurrent()));
}
if (!credentials.isEmpty()) {
return credentials;
}
if (properties.getCozeCredentials() != null) {
int index = 1;
for (SimilarAsinProperties.CozeCredential credential : properties.getCozeCredentials()) {
if (credential == null
|| normalize(credential.getWorkflowId()).isBlank()
|| normalize(credential.getToken()).isBlank()) {
continue;
}
String name = firstNonBlank(credential.getName(), "credential-" + index);
credentials.add(new CozeCredentialRef(name, credential.getWorkflowId(), credential.getToken(), Integer.MAX_VALUE));
index++;
}
}
if (credentials.isEmpty()
&& properties.getCozeWorkflowId() != null && !properties.getCozeWorkflowId().isBlank()
&& properties.getCozeToken() != null && !properties.getCozeToken().isBlank()) {
credentials.add(new CozeCredentialRef("default", properties.getCozeWorkflowId(), properties.getCozeToken(), Integer.MAX_VALUE));
}
return credentials;
}
private Map<String, Object> buildParameters(List<SimilarAsinResultRowDto> rows, String prompt, String apiKey) {
List<String> asins = rows.stream().map(row -> nonBlank(row.getAsin(), "")).toList();
List<String> skus = rows.stream().map(row -> nonBlank(row.getSku(), "")).toList();
@@ -1045,7 +1140,8 @@ public class SimilarAsinCozeClient {
public record CozeSubmitResponse(
String executeId,
String immediateData,
String rawResponse
String rawResponse,
String credentialName
) {
}
@@ -1055,7 +1151,8 @@ public class SimilarAsinCozeClient {
String dataText,
String outputText,
String failureMessage,
String rawResponse
String rawResponse,
String credentialName
) {
public boolean hasPayload() {
return dataText != null && !dataText.isBlank() || outputText != null && !outputText.isBlank();
@@ -1081,6 +1178,14 @@ public class SimilarAsinCozeClient {
}
}
public record CozeCredentialRef(
String name,
String workflowId,
String token,
int maxConcurrent
) {
}
private static final class PartialCozeResultException extends RuntimeException {
private final int resolvedCount;
@@ -11,6 +11,7 @@ import com.nanri.aiimage.common.service.DistributedJobLockService;
import com.nanri.aiimage.config.InstanceMetadata;
import com.nanri.aiimage.config.SimilarAsinProperties;
import com.nanri.aiimage.config.StorageProperties;
import com.nanri.aiimage.modules.coze.service.CozeCredentialPoolService;
import com.nanri.aiimage.modules.similarasin.mapper.SimilarAsinFilterConditionMapper;
import com.nanri.aiimage.modules.similarasin.client.SimilarAsinCozeClient;
import com.nanri.aiimage.modules.similarasin.model.dto.SimilarAsinFilterConditionAddRequest;
@@ -72,6 +73,7 @@ import org.springframework.transaction.support.TransactionTemplate;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
@@ -86,6 +88,8 @@ import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.function.Supplier;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@Service
@RequiredArgsConstructor
@@ -102,12 +106,13 @@ public class SimilarAsinTaskService {
private static final String COZE_STATUS_DONE = "DONE";
private static final String COZE_STATUS_FAILED = "FAILED";
private static final String CONTENT_TYPE_XLSX = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
private static final String CONTENT_TYPE_ZIP = "application/zip";
private static final int RESULT_ROWS_READ_RETRY_LIMIT = 3;
private static final long RESULT_ROWS_READ_RETRY_DELAY_MS = 500L;
private static final Duration TASK_LOCK_TTL = Duration.ofMinutes(5);
private static final long TASK_LOCK_WAIT_MILLIS = 10000L;
private static final Duration COZE_SUBMIT_LOCK_TTL = Duration.ofMinutes(2);
private static final long COZE_SUBMIT_LOCK_WAIT_MILLIS = 180000L;
private static final long COZE_SUBMIT_LOCK_WAIT_MILLIS = 1000L;
private static final long COZE_SUBMIT_LOCK_RETRY_DELAY_MILLIS = 500L;
private static final long COZE_SUBMIT_MIN_INTERVAL_MILLIS = 30000L;
private static final int MAX_COZE_SUBMIT_RETRY_COUNT = 5;
@@ -122,7 +127,7 @@ public class SimilarAsinTaskService {
"是否符合类目",
"不符合理由",
"产品类目",
"status"
"状态"
);
private final LocalFileStorageService localFileStorageService;
@@ -144,6 +149,7 @@ public class SimilarAsinTaskService {
private final PlatformTransactionManager transactionManager;
private final DistributedJobLockService distributedJobLockService;
private final InstanceMetadata instanceMetadata;
private final CozeCredentialPoolService cozeCredentialPoolService;
@Autowired
@Qualifier("cozeTaskExecutor")
private TaskExecutor cozeTaskExecutor;
@@ -821,7 +827,7 @@ public class SimilarAsinTaskService {
touchJavaSideTaskActivity(task.getId());
} else if (isResultSubmissionComplete(task.getId())) {
maybeFinalizeCozeJobLocked(task.getId(), new CozeBatchContext(
job.getId(), result.getId(), context.scopeHash(), context.chunkIndex(), 1, 1, currentInstanceId(), 0));
job.getId(), result.getId(), context.scopeHash(), context.chunkIndex(), 1, 1, currentInstanceId(), 0, null));
}
}
@@ -1431,12 +1437,7 @@ public class SimilarAsinTaskService {
return;
}
try (lockHandle) {
List<TaskScopeStateEntity> states = taskScopeStateMapper.selectList(new LambdaQueryWrapper<TaskScopeStateEntity>()
.eq(TaskScopeStateEntity::getModuleType, MODULE_TYPE)
.in(TaskScopeStateEntity::getCozeStatus, List.of(COZE_STATUS_SUBMITTED, COZE_STATUS_RUNNING))
.isNotNull(TaskScopeStateEntity::getCozeExecuteId)
.orderByAsc(TaskScopeStateEntity::getUpdatedAt)
.last("limit 50"));
List<TaskScopeStateEntity> states = listOwnedPendingCozeStates();
if (states == null || states.isEmpty()) {
return;
}
@@ -1458,7 +1459,7 @@ public class SimilarAsinTaskService {
if (chunks == null || chunks.isEmpty()) {
return countPendingCozeStates(task.getId()) > 0;
}
if (properties.getCozeToken() == null || properties.getCozeToken().isBlank()) {
if (!cozeClient.hasConfiguredCredential()) {
log.warn("[similar-asin] coze token not configured, skip async coze taskId={} jobId={}",
task.getId(), job.getId());
return false;
@@ -1512,8 +1513,10 @@ public class SimilarAsinTaskService {
return COZE_STATUS_SUBMITTED.equals(existing.getCozeStatus())
|| COZE_STATUS_RUNNING.equals(existing.getCozeStatus());
}
SimilarAsinCozeClient.CozeCredentialRef credential = cozeClient.nextCredential();
try {
SimilarAsinCozeClient.CozeSubmitResponse submit = submitCozeWorkflowThrottled(batchRows, prompt, apiKey);
SimilarAsinCozeClient.CozeSubmitResponse submit = submitCozeWorkflowThrottled(
batchRows, prompt, apiKey, credential, true);
if (submit.immediateData() != null && !submit.immediateData().isBlank()) {
List<SimilarAsinResultRowDto> cozeRows = cozeClient.mergeRowsFromDataText(batchRows, submit.immediateData());
String emptyResultMessage = emptyCozeResultMessage(cozeRows, batchRows.size());
@@ -1532,14 +1535,22 @@ public class SimilarAsinTaskService {
return false;
}
saveCozeBatchState(task, result, job, chunk, batchRows, batchScopeKey, batchScopeHash,
batchIndex, batchTotal, submit.executeId());
log.info("[similar-asin] coze async submitted taskId={} jobId={} chunk={} batch={}/{} executeId={}",
task.getId(), job.getId(), chunk.getChunkIndex(), batchIndex, batchTotal, submit.executeId());
batchIndex, batchTotal, submit.executeId(), submit.credentialName());
log.info("[similar-asin] coze async submitted taskId={} jobId={} chunk={} batch={}/{} credential={} executeId={}",
task.getId(), job.getId(), chunk.getChunkIndex(), batchIndex, batchTotal,
submit.credentialName(), submit.executeId());
return true;
} catch (Exception ex) {
String message = firstNonBlank(ex.getMessage(), "Coze submit failed");
log.warn("[similar-asin] coze async submit failed taskId={} jobId={} chunk={} batch={}/{} err={}",
task.getId(), job.getId(), chunk.getChunkIndex(), batchIndex, batchTotal, message);
if (isCozeThrottleLockTimeout(message)) {
savePendingCozeBatchState(task, result, job, chunk, batchRows, batchScopeKey, batchScopeHash,
batchIndex, batchTotal, message, credential.name());
taskFileJobService.touchRunning(job.getId());
touchJavaSideTaskActivity(task.getId());
return true;
}
mergeCozeRowsIntoChunk(task,
chunk.getScopeHash(),
chunk.getChunkIndex(),
@@ -1549,6 +1560,65 @@ public class SimilarAsinTaskService {
}
}
private boolean isCozeThrottleLockTimeout(String message) {
return normalize(message).toLowerCase(Locale.ROOT).contains("coze submit throttle lock timeout");
}
private void savePendingCozeBatchState(FileTaskEntity task,
FileResultEntity result,
TaskFileJobEntity job,
TaskChunkEntity chunk,
List<SimilarAsinResultRowDto> batchRows,
String batchScopeKey,
String batchScopeHash,
int batchIndex,
int batchTotal,
String pendingReason,
String credentialName) {
LocalDateTime now = LocalDateTime.now();
CozeBatchContext context = new CozeBatchContext(
job.getId(),
result.getId(),
chunk.getScopeHash(),
chunk.getChunkIndex(),
batchIndex,
batchTotal,
currentInstanceId(),
0,
credentialName
);
String batchPayload = writeJson(batchRows, "serialize pending coze batch payload failed");
String storedBatchPayload = transientPayloadStorageService.storeParsedPayloadFast(
MODULE_TYPE, task.getId(), batchScopeHash, batchPayload, true);
TaskScopeStateEntity state = new TaskScopeStateEntity();
state.setTaskId(task.getId());
state.setModuleType(MODULE_TYPE);
state.setScopeKey(batchScopeKey);
state.setScopeHash(batchScopeHash);
state.setParsedPayloadJson(storedBatchPayload);
state.setStateJson(writeJson(context, "serialize pending coze batch context failed"));
state.setCozeStatus(COZE_STATUS_RUNNING);
state.setCozeSubmittedAt(now);
state.setCozeLastPolledAt(null);
state.setCozeAttemptCount(0);
state.setCozeError(firstNonBlank(pendingReason, "Coze submit queued by throttle"));
state.setChunkTotal(batchTotal);
state.setReceivedChunkCount(batchIndex);
state.setCompleted(0);
state.setCreatedAt(now);
state.setUpdatedAt(now);
try {
taskScopeStateMapper.insert(state);
touchJavaSideTaskActivity(task.getId());
log.info("[similar-asin] coze async submit queued by throttle taskId={} jobId={} chunk={} rows={} batch={}/{}",
task.getId(), job.getId(), chunk.getChunkIndex(), batchRows.size(), batchIndex, batchTotal);
} catch (DuplicateKeyException ex) {
transientPayloadStorageService.deletePayloadIfPresent(storedBatchPayload);
log.info("[similar-asin] duplicate pending coze batch state ignored taskId={} scope={}",
task.getId(), batchScopeKey);
}
}
private void saveCozeBatchState(FileTaskEntity task,
FileResultEntity result,
TaskFileJobEntity job,
@@ -1558,7 +1628,8 @@ public class SimilarAsinTaskService {
String batchScopeHash,
int batchIndex,
int batchTotal,
String executeId) {
String executeId,
String credentialName) {
LocalDateTime now = LocalDateTime.now();
CozeBatchContext context = new CozeBatchContext(
job.getId(),
@@ -1568,7 +1639,8 @@ public class SimilarAsinTaskService {
batchIndex,
batchTotal,
currentInstanceId(),
0
0,
credentialName
);
String batchPayload = writeJson(batchRows, "serialize coze batch payload failed");
String storedBatchPayload = transientPayloadStorageService.storeParsedPayloadFast(
@@ -1602,6 +1674,10 @@ public class SimilarAsinTaskService {
private void pollPendingCozeState(Long stateId) {
TaskScopeStateEntity lockState = taskScopeStateMapper.selectById(stateId);
if (lockState == null || lockState.getCozeExecuteId() == null || lockState.getCozeExecuteId().isBlank()) {
if (lockState != null && lockState.getCozeExecuteId() == null
&& (COZE_STATUS_SUBMITTED.equals(lockState.getCozeStatus()) || COZE_STATUS_RUNNING.equals(lockState.getCozeStatus()))) {
retryPendingCozeSubmitState(lockState);
}
return;
}
if (!isCozeStateOwnedByCurrentInstance(lockState)) {
@@ -1621,6 +1697,10 @@ public class SimilarAsinTaskService {
private void pollPendingCozeStateLocked(Long stateId) {
TaskScopeStateEntity state = taskScopeStateMapper.selectById(stateId);
if (state == null || state.getCozeExecuteId() == null || state.getCozeExecuteId().isBlank()) {
if (state != null && state.getCozeExecuteId() == null
&& (COZE_STATUS_SUBMITTED.equals(state.getCozeStatus()) || COZE_STATUS_RUNNING.equals(state.getCozeStatus()))) {
retryPendingCozeSubmitState(state);
}
return;
}
if (!(COZE_STATUS_SUBMITTED.equals(state.getCozeStatus()) || COZE_STATUS_RUNNING.equals(state.getCozeStatus()))) {
@@ -1644,7 +1724,9 @@ public class SimilarAsinTaskService {
}
taskFileJobService.touchRunning(context.jobId());
try {
SimilarAsinCozeClient.CozePollResponse poll = cozeClient.pollWorkflow(state.getCozeExecuteId());
SimilarAsinCozeClient.CozePollResponse poll = cozeClient.pollWorkflow(
state.getCozeExecuteId(),
cozeClient.credentialByName(context.credentialName()));
if (!poll.hasPayload() && !poll.isFinished() && !isCozeStateTimedOut(state)) {
updateCozeStateRunning(state, null);
return;
@@ -1725,7 +1807,8 @@ public class SimilarAsinTaskService {
}
try {
SimilarAsinCozeClient.CozeSubmitResponse submit =
submitCozeWorkflowThrottled(batchRows, readAiPrompt(task), readApiKey(task));
submitCozeWorkflowThrottled(batchRows, readAiPrompt(task), readApiKey(task),
cozeClient.credentialByName(context.credentialName()), false);
Map<String, List<SimilarAsinParsedRowVo>> allRowsByBaseId = loadAllRowsByBaseId(task);
if (submit.immediateData() != null && !submit.immediateData().isBlank()) {
List<SimilarAsinResultRowDto> cozeRows =
@@ -1774,23 +1857,54 @@ public class SimilarAsinTaskService {
private SimilarAsinCozeClient.CozeSubmitResponse submitCozeWorkflowThrottled(
List<SimilarAsinResultRowDto> rows,
String prompt,
String apiKey) throws Exception {
DistributedJobLockService.LockHandle lockHandle = acquireCozeSubmitLock();
if (lockHandle == null) {
throw new IllegalStateException("Coze submit throttle lock timeout");
}
try (lockHandle) {
SimilarAsinCozeClient.CozeSubmitResponse response = cozeClient.submitWorkflow(rows, prompt, apiKey);
sleepQuietly(COZE_SUBMIT_MIN_INTERVAL_MILLIS);
return response;
String apiKey,
SimilarAsinCozeClient.CozeCredentialRef credential,
boolean allowCredentialFallback) throws Exception {
int attempts = allowCredentialFallback ? Math.max(1, cozeClient.configuredCredentialCount()) : 1;
SimilarAsinCozeClient.CozeCredentialRef currentCredential =
credential == null ? cozeClient.nextCredential() : credential;
Exception lastFailure = null;
for (int i = 0; i < attempts; i++) {
DistributedJobLockService.LockHandle lockHandle = acquireCozeSubmitLock(currentCredential);
if (lockHandle == null) {
lastFailure = new IllegalStateException("Coze submit throttle lock timeout");
currentCredential = cozeClient.nextCredential();
continue;
}
CozeCredentialPoolService.BorrowedCredential borrowedCredential =
cozeCredentialPoolService.borrow(MODULE_TYPE, toPoolCredential(currentCredential));
if (borrowedCredential == null) {
lockHandle.close();
lastFailure = new IllegalStateException("Coze credential concurrency limit reached");
currentCredential = cozeClient.nextCredential();
continue;
}
try (lockHandle; borrowedCredential) {
return cozeClient.submitWorkflow(rows, prompt, apiKey, currentCredential);
} finally {
sleepQuietly(COZE_SUBMIT_MIN_INTERVAL_MILLIS);
}
}
throw lastFailure == null ? new IllegalStateException("Coze submit failed") : lastFailure;
}
private DistributedJobLockService.LockHandle acquireCozeSubmitLock() {
private CozeCredentialPoolService.CozeCredential toPoolCredential(SimilarAsinCozeClient.CozeCredentialRef credential) {
if (credential == null) {
return null;
}
return new CozeCredentialPoolService.CozeCredential(
credential.name(),
credential.workflowId(),
credential.token(),
credential.maxConcurrent());
}
private DistributedJobLockService.LockHandle acquireCozeSubmitLock(SimilarAsinCozeClient.CozeCredentialRef credential) {
long deadline = System.currentTimeMillis() + COZE_SUBMIT_LOCK_WAIT_MILLIS;
String credentialName = credential == null ? "default" : firstNonBlank(credential.name(), "default");
while (System.currentTimeMillis() <= deadline) {
DistributedJobLockService.LockHandle lockHandle =
distributedJobLockService.tryLock("similar-asin:coze-submit", COZE_SUBMIT_LOCK_TTL);
distributedJobLockService.tryLock("similar-asin:coze-submit:" + credentialName, COZE_SUBMIT_LOCK_TTL);
if (lockHandle != null) {
return lockHandle;
}
@@ -1836,14 +1950,16 @@ public class SimilarAsinTaskService {
int partIndex = 1;
for (List<SimilarAsinResultRowDto> partRows : partitions) {
SimilarAsinCozeClient.CozeSubmitResponse submit =
submitCozeWorkflowThrottled(partRows, readAiPrompt(task), readApiKey(task));
submitCozeWorkflowThrottled(partRows, readAiPrompt(task), readApiKey(task),
cozeClient.credentialByName(context.credentialName()), false);
if (submit.immediateData() != null && !submit.immediateData().isBlank()) {
List<SimilarAsinResultRowDto> cozeRows =
cozeClient.mergeRowsFromDataText(partRows, submit.immediateData());
mergeCozeRowsIntoChunk(task, context.chunkScopeHash(), context.chunkIndex(), cozeRows, allRowsByBaseId);
submittedAny = true;
} else if (submit.executeId() != null && !submit.executeId().isBlank()) {
saveSplitRetryCozeBatchState(state, context, partRows, partIndex, partitions.size(), retryCount, submit.executeId());
saveSplitRetryCozeBatchState(state, context, partRows, partIndex, partitions.size(), retryCount,
submit.executeId(), submit.credentialName());
submittedAny = true;
}
partIndex++;
@@ -1871,7 +1987,8 @@ public class SimilarAsinTaskService {
int partIndex,
int partTotal,
int retryCount,
String executeId) {
String executeId,
String credentialName) {
String scopeKey = parent.getScopeKey() + ":split:" + retryCount + ":" + partIndex;
String scopeHash = DigestUtil.sha256Hex(scopeKey);
CozeBatchContext context = new CozeBatchContext(
@@ -1882,7 +1999,8 @@ public class SimilarAsinTaskService {
partIndex,
partTotal,
parentContext.ownerInstanceId(),
retryCount
retryCount,
firstNonBlank(credentialName, parentContext.credentialName())
);
LocalDateTime now = LocalDateTime.now();
String batchPayload = writeJson(batchRows, "serialize split coze batch payload failed");
@@ -1926,6 +2044,130 @@ public class SimilarAsinTaskService {
|| normalized.contains("\u8c03\u7528\u8d85\u65f6");
}
private void retryPendingCozeSubmitState(TaskScopeStateEntity state) {
if (state == null || state.getId() == null) {
return;
}
if (!tryClaimCozeStateForPoll(state)) {
log.info("[similar-asin] coze submit retry skipped by claim guard taskId={} stateId={} lastPolledAt={}",
state.getTaskId(), state.getId(), state.getCozeLastPolledAt());
return;
}
CozeBatchContext context = readCozeBatchContext(state);
if (context == null || context.jobId() == null || context.resultId() == null) {
markCozeStateTerminal(state, COZE_STATUS_FAILED, "Coze pending submit context missing");
return;
}
List<SimilarAsinResultRowDto> batchRows = readCozeBatchRows(state);
if (batchRows.isEmpty()) {
markCozeStateTerminal(state, COZE_STATUS_FAILED, "Coze pending submit payload missing");
maybeFinalizeCozeJobLocked(state.getTaskId(), context);
return;
}
FileTaskEntity task = fileTaskMapper.selectById(state.getTaskId());
if (task == null || !MODULE_TYPE.equals(task.getModuleType())) {
markCozeStateTerminal(state, COZE_STATUS_FAILED, "Coze pending submit task missing");
return;
}
TaskChunkEntity currentChunk = taskChunkMapper.selectOne(new LambdaQueryWrapper<TaskChunkEntity>()
.eq(TaskChunkEntity::getTaskId, task.getId())
.eq(TaskChunkEntity::getModuleType, MODULE_TYPE)
.eq(TaskChunkEntity::getScopeHash, context.chunkScopeHash())
.eq(TaskChunkEntity::getChunkIndex, context.chunkIndex())
.last("limit 1"));
Map<String, SimilarAsinResultRowDto> currentRows = readChunkRows(currentChunk);
List<SimilarAsinResultRowDto> currentBatchRows = batchRows.stream()
.map(row -> currentRows.get(rowKey(row)))
.filter(Objects::nonNull)
.toList();
if (currentBatchRows.size() == batchRows.size()
&& currentBatchRows.stream().allMatch(this::hasResolvedCozeFields)) {
markCozeStateTerminal(state, COZE_STATUS_DONE, "Coze rows already resolved by another batch");
maybeFinalizeCozeJobLocked(state.getTaskId(), context);
log.info("[similar-asin] coze pending submit skipped because rows already resolved taskId={} stateId={} jobId={} rows={}",
state.getTaskId(), state.getId(), context.jobId(), batchRows.size());
return;
}
try {
taskFileJobService.touchRunning(context.jobId());
SimilarAsinCozeClient.CozeSubmitResponse submit =
submitCozeWorkflowThrottled(batchRows, readAiPrompt(task), readApiKey(task),
cozeClient.credentialByName(context.credentialName()), false);
Map<String, List<SimilarAsinParsedRowVo>> allRowsByBaseId = loadAllRowsByBaseId(task);
if (submit.immediateData() != null && !submit.immediateData().isBlank()) {
List<SimilarAsinResultRowDto> cozeRows =
cozeClient.mergeRowsFromDataText(batchRows, submit.immediateData());
String emptyResultMessage = emptyCozeResultMessage(cozeRows, batchRows.size());
if (!emptyResultMessage.isBlank()) {
throw new IllegalStateException(emptyResultMessage);
}
mergeCozeRowsIntoChunk(task, context.chunkScopeHash(), context.chunkIndex(), cozeRows, allRowsByBaseId);
markCozeStateTerminal(state, COZE_STATUS_DONE, null);
maybeFinalizeCozeJobLocked(state.getTaskId(), context);
return;
}
if (submit.executeId() == null || submit.executeId().isBlank()) {
markCozeStateTerminal(state, COZE_STATUS_FAILED, "Coze async execute_id missing");
mergeCozeRowsIntoChunk(task,
context.chunkScopeHash(),
context.chunkIndex(),
cozeClient.markRowsFailed(batchRows, "Coze async execute_id missing"),
allRowsByBaseId);
maybeFinalizeCozeJobLocked(state.getTaskId(), context);
return;
}
LocalDateTime now = LocalDateTime.now();
taskScopeStateMapper.update(null, new LambdaUpdateWrapper<TaskScopeStateEntity>()
.eq(TaskScopeStateEntity::getId, state.getId())
.in(TaskScopeStateEntity::getCozeStatus, List.of(COZE_STATUS_SUBMITTED, COZE_STATUS_RUNNING))
.set(TaskScopeStateEntity::getCozeExecuteId, submit.executeId())
.set(TaskScopeStateEntity::getCozeStatus, COZE_STATUS_SUBMITTED)
.set(TaskScopeStateEntity::getCozeSubmittedAt, now)
.set(TaskScopeStateEntity::getCozeLastPolledAt, null)
.set(TaskScopeStateEntity::getCozeError, null)
.set(TaskScopeStateEntity::getUpdatedAt, now));
touchJavaSideTaskActivity(state.getTaskId());
log.info("[similar-asin] coze pending submit retried taskId={} stateId={} jobId={} rows={} executeId={}",
state.getTaskId(), state.getId(), context.jobId(), batchRows.size(), submit.executeId());
} catch (Exception ex) {
String message = firstNonBlank(ex.getMessage(), "Coze pending submit retry failed");
log.warn("[similar-asin] coze pending submit retry failed taskId={} stateId={} jobId={} rows={} err={}",
state.getTaskId(), state.getId(), context.jobId(), batchRows.size(), message);
if (isCozeThrottleLockTimeout(message)) {
keepPendingCozeSubmitState(state, message);
return;
}
int nextAttemptCount = cozeAttemptCount(state) + 1;
if (nextAttemptCount >= MAX_COZE_SUBMIT_RETRY_COUNT) {
Map<String, List<SimilarAsinParsedRowVo>> allRowsByBaseId = loadAllRowsByBaseId(task);
String finalMessage = message + " after " + nextAttemptCount + " submit attempts";
mergeCozeRowsIntoChunk(task,
context.chunkScopeHash(),
context.chunkIndex(),
cozeClient.markRowsFailed(batchRows, finalMessage),
allRowsByBaseId);
markCozeStateTerminal(state, COZE_STATUS_FAILED, finalMessage);
maybeFinalizeCozeJobLocked(state.getTaskId(), context);
return;
}
updateCozeStateRunning(state, message);
}
}
private void keepPendingCozeSubmitState(TaskScopeStateEntity state, String error) {
int updated = taskScopeStateMapper.update(null, new LambdaUpdateWrapper<TaskScopeStateEntity>()
.eq(TaskScopeStateEntity::getId, state.getId())
.in(TaskScopeStateEntity::getCozeStatus, List.of(COZE_STATUS_SUBMITTED, COZE_STATUS_RUNNING))
.set(TaskScopeStateEntity::getCozeStatus, COZE_STATUS_RUNNING)
.set(TaskScopeStateEntity::getCozeExecuteId, null)
.set(TaskScopeStateEntity::getCozeLastPolledAt, LocalDateTime.now())
.set(TaskScopeStateEntity::getCozeError, error)
.set(TaskScopeStateEntity::getUpdatedAt, LocalDateTime.now()));
if (updated > 0) {
touchJavaSideTaskActivity(state.getTaskId());
}
}
private boolean isRetryableCozeFailure(String failureMessage) {
String normalized = normalize(failureMessage).toLowerCase(Locale.ROOT);
return normalized.contains("rate limit")
@@ -2173,7 +2415,8 @@ public class SimilarAsinTaskService {
context.batchIndex(),
context.batchTotal(),
context.ownerInstanceId(),
submitRetryCount
submitRetryCount,
context.credentialName()
);
}
@@ -2338,6 +2581,12 @@ public class SimilarAsinTaskService {
}
int safeTotal = Math.max(1, total);
int safeCompleted = Math.max(0, Math.min(completed, safeTotal));
TaskProgressSnapshotEntity existing = taskProgressSnapshotService.find(task.getId(), MODULE_TYPE);
int displayPercent = calculateDisplayProgressPercent(safeCompleted, safeTotal, job, LocalDateTime.now());
int previousDisplayPercent = calculateSnapshotDisplayPercent(existing, job);
if (previousDisplayPercent > displayPercent && safeCompleted < safeTotal) {
displayPercent = previousDisplayPercent;
}
taskProgressSnapshotService.save(
task.getId(),
MODULE_TYPE,
@@ -2347,10 +2596,57 @@ public class SimilarAsinTaskService {
0,
job.getScopeKey(),
message,
Map.of("phase", "RESULT_FILE", "jobId", job.getId())
Map.of("phase", "RESULT_FILE", "jobId", job.getId(), "displayPercent", displayPercent)
);
}
private int calculateDisplayProgressPercent(int current,
int total,
TaskFileJobEntity job,
LocalDateTime baseTime) {
if (total <= 0) {
return 0;
}
current = Math.max(0, Math.min(current, total));
int percent = Math.max(1, Math.min(99, (int) Math.floor(current * 100.0 / total)));
if (job != null && STATUS_RUNNING.equals(job.getStatus())) {
long elapsedSeconds = baseTime == null ? 0 : Math.max(0, Duration.between(baseTime, LocalDateTime.now()).getSeconds());
if (current <= 0) {
int firstRealProgressPercent = Math.max(1, Math.min(99, (int) Math.floor(100.0 / total)));
int waitingCap = Math.max(8, Math.min(35, firstRealProgressPercent - 1));
percent = Math.max(percent, Math.min(waitingCap, 8 + (int) (elapsedSeconds / 6)));
} else if (current < total) {
percent = Math.max(percent, Math.min(92, percent + (int) (elapsedSeconds / 10)));
}
}
return percent;
}
private int calculateSnapshotDisplayPercent(TaskProgressSnapshotEntity snapshot, TaskFileJobEntity job) {
if (snapshot == null) {
return 0;
}
int total = snapshot.getTotalCount() == null ? 0 : snapshot.getTotalCount();
int current = snapshot.getSuccessCount() == null ? 0 : snapshot.getSuccessCount();
int percent = total <= 0 ? 0 : calculateDisplayProgressPercent(current, total, job, snapshot.getUpdatedAt());
return Math.max(percent, extractSnapshotDisplayPercent(snapshot));
}
private int extractSnapshotDisplayPercent(TaskProgressSnapshotEntity snapshot) {
if (snapshot == null || snapshot.getSnapshotJson() == null || snapshot.getSnapshotJson().isBlank()) {
return 0;
}
try {
JsonNode displayPercent = objectMapper.readTree(snapshot.getSnapshotJson()).path("displayPercent");
if (!displayPercent.isNumber()) {
return 0;
}
return Math.max(0, Math.min(100, displayPercent.asInt()));
} catch (Exception ignored) {
return 0;
}
}
public void cleanupResultFileJob(TaskFileJobEntity job) {
if (job == null || job.getTaskId() == null) {
return;
@@ -2379,28 +2675,195 @@ public class SimilarAsinTaskService {
if (!outputDir.exists() && !outputDir.mkdirs()) {
throw new BusinessException("创建结果目录失败");
}
String filename = safeFileStem(result.getSourceFilename()) + "-result.xlsx";
String tempFilename = safeFileStem(result.getSourceFilename())
+ "-" + task.getId()
+ "-" + result.getId()
+ "-" + UUID.randomUUID()
+ "-result.xlsx";
File xlsx = new File(outputDir, tempFilename);
List<SourceRows> sourceRows = splitRowsBySourceFile(parsed, parsed.getAllItems(), result.getSourceFilename());
List<SourceResultWorkbook> workbooks = new ArrayList<>();
File zip = null;
try {
writeResultWorkbook(xlsx, parsed, resultMap);
String objectKey = ossStorageService.uploadResultFile(xlsx, MODULE_TYPE);
for (SourceRows item : sourceRows) {
String filename = safeFileStem(item.sourceFilename()) + "-result.xlsx";
String tempFilename = safeFileStem(item.sourceFilename())
+ "-" + task.getId()
+ "-" + result.getId()
+ "-" + UUID.randomUUID()
+ "-result.xlsx";
File xlsx = new File(outputDir, tempFilename);
writeResultWorkbook(xlsx, item.rows(), resultMap);
workbooks.add(new SourceResultWorkbook(xlsx, filename, item.rows().size()));
}
if (workbooks.isEmpty()) {
throw new BusinessException("相似ASIN检测结果为空,请稍后重试生成结果文件");
}
File uploadFile;
String filename;
String contentType;
if (workbooks.size() == 1) {
SourceResultWorkbook workbook = workbooks.get(0);
uploadFile = workbook.file();
filename = workbook.filename();
contentType = CONTENT_TYPE_XLSX;
} else {
filename = safeFileStem(result.getSourceFilename()) + "-result.zip";
String tempFilename = safeFileStem(result.getSourceFilename())
+ "-" + task.getId()
+ "-" + result.getId()
+ "-" + UUID.randomUUID()
+ "-result.zip";
zip = new File(outputDir, tempFilename);
packageResultWorkbooksAsZip(zip, workbooks);
uploadFile = zip;
contentType = CONTENT_TYPE_ZIP;
}
String objectKey = ossStorageService.uploadResultFile(uploadFile, MODULE_TYPE);
result.setResultFilename(filename);
result.setResultFileUrl(objectKey);
result.setResultFileSize(xlsx.length());
result.setResultContentType(CONTENT_TYPE_XLSX);
result.setResultFileSize(uploadFile.length());
result.setResultContentType(contentType);
result.setRowCount(parsed.getAllItems().size());
} finally {
if (xlsx.exists() && !xlsx.delete()) {
log.warn("[similar-asin] delete temp xlsx failed file={}", xlsx);
for (SourceResultWorkbook workbook : workbooks) {
if (workbook.file().exists() && !workbook.file().delete()) {
log.warn("[similar-asin] delete temp xlsx failed file={}", workbook.file());
}
}
if (zip != null && zip.exists() && !zip.delete()) {
log.warn("[similar-asin] delete temp zip failed file={}", zip);
}
}
}
private List<TaskScopeStateEntity> listOwnedPendingCozeStates() {
Map<Long, TaskScopeStateEntity> merged = new LinkedHashMap<>();
for (TaskScopeStateEntity state : queryOwnedPendingCozeStates(false, 50)) {
if (state != null && state.getId() != null) {
merged.put(state.getId(), state);
}
}
for (TaskScopeStateEntity state : queryOwnedPendingCozeStates(true, 50)) {
if (state != null && state.getId() != null) {
merged.putIfAbsent(state.getId(), state);
}
}
return new ArrayList<>(merged.values());
}
private List<TaskScopeStateEntity> queryOwnedPendingCozeStates(boolean oldestFirst, int limit) {
LambdaQueryWrapper<TaskScopeStateEntity> wrapper = new LambdaQueryWrapper<TaskScopeStateEntity>()
.eq(TaskScopeStateEntity::getModuleType, MODULE_TYPE)
.in(TaskScopeStateEntity::getCozeStatus, List.of(COZE_STATUS_SUBMITTED, COZE_STATUS_RUNNING))
.and(query -> query
.apply("JSON_UNQUOTE(JSON_EXTRACT(state_json, '$.ownerInstanceId')) IS NULL")
.or()
.apply("JSON_UNQUOTE(JSON_EXTRACT(state_json, '$.ownerInstanceId')) = ''")
.or()
.apply("JSON_UNQUOTE(JSON_EXTRACT(state_json, '$.ownerInstanceId')) = {0}", currentInstanceId()))
.last("limit " + Math.max(1, Math.min(limit, 100)));
if (oldestFirst) {
wrapper.orderByAsc(TaskScopeStateEntity::getUpdatedAt);
} else {
wrapper.orderByDesc(TaskScopeStateEntity::getUpdatedAt);
}
List<TaskScopeStateEntity> states = taskScopeStateMapper.selectList(wrapper);
return states == null ? List.of() : states;
}
private List<SourceRows> splitRowsBySourceFile(SimilarAsinParsedPayloadDto parsed,
List<SimilarAsinParsedRowVo> rows,
String fallbackFilename) {
String defaultFilename = firstNonBlank(fallbackFilename, "similar-asin");
Map<String, SourceRowsBuilder> builders = new LinkedHashMap<>();
if (parsed != null && parsed.getSourceFiles() != null) {
for (SimilarAsinSourceFileDto sourceFile : parsed.getSourceFiles()) {
if (sourceFile == null) {
continue;
}
String sourceFileKey = normalize(sourceFile.getFileKey());
if (sourceFileKey.isBlank()) {
continue;
}
builders.putIfAbsent(sourceFileKey,
new SourceRowsBuilder(sourceFileKey, firstNonBlank(sourceFile.getOriginalFilename(), defaultFilename)));
}
}
for (SimilarAsinParsedRowVo row : rows == null ? List.<SimilarAsinParsedRowVo>of() : rows) {
if (row == null) {
continue;
}
String sourceFileKey = normalize(row.getSourceFileKey());
if (sourceFileKey.isBlank()) {
sourceFileKey = normalize(row.getSourceFilename());
}
if (sourceFileKey.isBlank()) {
sourceFileKey = "__default__";
}
SourceRowsBuilder builder = builders.computeIfAbsent(sourceFileKey,
key -> new SourceRowsBuilder(key, firstNonBlank(row.getSourceFilename(), defaultFilename)));
if (builder.sourceFilename().isBlank() || Objects.equals(builder.sourceFilename(), defaultFilename)) {
builder.setSourceFilename(firstNonBlank(row.getSourceFilename(), defaultFilename));
}
builder.rows().add(row);
}
return builders.values().stream()
.filter(builder -> !builder.rows().isEmpty())
.map(builder -> new SourceRows(builder.sourceFileKey(), firstNonBlank(builder.sourceFilename(), defaultFilename), builder.rows()))
.toList();
}
private void packageResultWorkbooksAsZip(File zip, List<SourceResultWorkbook> workbooks) {
Set<String> entryNames = new LinkedHashSet<>();
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zip))) {
byte[] buffer = new byte[8192];
for (SourceResultWorkbook workbook : workbooks) {
writeResultZipEntry(zos, buffer, workbook.file(), uniqueZipEntryName(workbook.filename(), entryNames));
}
} catch (IOException ex) {
throw new BusinessException("生成相似ASIN检测结果压缩包失败");
}
}
private void writeResultZipEntry(ZipOutputStream zos,
byte[] buffer,
File file,
String entryName) throws IOException {
zos.putNextEntry(new ZipEntry(entryName));
try (FileInputStream inputStream = new FileInputStream(file)) {
int len;
while ((len = inputStream.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
}
zos.closeEntry();
}
private String uniqueZipEntryName(String filename, Set<String> entryNames) {
String safeFilename = normalizeZipFilename(filename);
if (entryNames.add(safeFilename)) {
return safeFilename;
}
int dotIndex = safeFilename.lastIndexOf('.');
String stem = dotIndex > 0 ? safeFilename.substring(0, dotIndex) : safeFilename;
String extension = dotIndex > 0 ? safeFilename.substring(dotIndex) : "";
int index = 2;
while (true) {
String candidate = stem + "(" + index + ")" + extension;
if (entryNames.add(candidate)) {
return candidate;
}
index++;
}
}
private String normalizeZipFilename(String filename) {
String normalized = firstNonBlank(filename, "similar-asin-result.xlsx").replace('\\', '/');
while (normalized.startsWith("/")) {
normalized = normalized.substring(1);
}
return normalized.isBlank() ? "similar-asin-result.xlsx" : normalized;
}
private Map<String, SimilarAsinResultRowDto> loadPersistedResultRows(Long taskId) {
Map<String, SimilarAsinResultRowDto> result = new LinkedHashMap<>();
List<TaskChunkEntity> chunks = taskChunkMapper.selectList(new LambdaQueryWrapper<TaskChunkEntity>()
@@ -2450,7 +2913,9 @@ public class SimilarAsinTaskService {
}
}
private void writeResultWorkbook(File xlsx, SimilarAsinParsedPayloadDto parsed, Map<String, SimilarAsinResultRowDto> resultMap) {
private void writeResultWorkbook(File xlsx,
List<SimilarAsinParsedRowVo> rowsToWrite,
Map<String, SimilarAsinResultRowDto> resultMap) {
try (SXSSFWorkbook workbook = new SXSSFWorkbook(200); FileOutputStream fos = new FileOutputStream(xlsx)) {
Sheet sheet = workbook.createSheet("相似asin检测");
CellStyle headerStyle = workbook.createCellStyle();
@@ -2467,7 +2932,7 @@ public class SimilarAsinTaskService {
}
int rowIndex = 1;
for (SimilarAsinParsedRowVo parsedRow : parsed.getAllItems()) {
for (SimilarAsinParsedRowVo parsedRow : rowsToWrite == null ? List.<SimilarAsinParsedRowVo>of() : rowsToWrite) {
SimilarAsinResultRowDto resultRow = findResultRow(parsedRow, resultMap);
Row row = sheet.createRow(rowIndex++);
int col = 0;
@@ -2807,23 +3272,25 @@ public class SimilarAsinTaskService {
}
int cozeCompleted = countCompletedCozeStates(taskId);
int cozePending = countPendingCozeStates(taskId);
TaskProgressSnapshotEntity snapshot = taskProgressSnapshotService.find(taskId, MODULE_TYPE);
if (job != null && STATUS_RUNNING.equals(job.getStatus()) && cozePending > 0) {
int total = Math.max(1, cozeCompleted + cozePending);
int current = Math.max(0, Math.min(cozeCompleted, total));
vo.setFileProgressCurrent(current);
vo.setFileProgressTotal(total);
vo.setFileProgressPercent(Math.max(0, Math.min(100, (int) Math.floor(current * 100.0 / total))));
int percent = calculateDisplayProgressPercent(current, total, job, snapshot == null ? null : snapshot.getUpdatedAt());
percent = Math.max(percent, calculateSnapshotDisplayPercent(snapshot, job));
vo.setFileProgressPercent(Math.min(99, percent));
vo.setFileProgressMessage("Coze 已完成 " + current + "/" + total + ",等待回流");
return;
}
TaskProgressSnapshotEntity snapshot = taskProgressSnapshotService.find(taskId, MODULE_TYPE);
if (snapshot == null) {
if (job != null && STATUS_RUNNING.equals(job.getStatus()) && cozeCompleted + cozePending > 0) {
int total = Math.max(1, cozeCompleted + cozePending);
int current = Math.max(0, Math.min(cozeCompleted, total));
vo.setFileProgressCurrent(current);
vo.setFileProgressTotal(total);
vo.setFileProgressPercent(Math.max(0, Math.min(100, (int) Math.floor(current * 100.0 / total))));
vo.setFileProgressPercent(Math.min(99, calculateDisplayProgressPercent(current, total, job, job.getUpdatedAt())));
vo.setFileProgressMessage(cozePending > 0
? "Coze 已完成 " + current + "/" + total + ",等待回流"
: "Coze 处理中");
@@ -2835,8 +3302,10 @@ public class SimilarAsinTaskService {
if (total <= 0) {
return;
}
current = Math.max(0, Math.min(current, total));
int percent = Math.max(0, Math.min(100, (int) Math.floor(current * 100.0 / total)));
LocalDateTime baseTime = snapshot.getUpdatedAt() != null ? snapshot.getUpdatedAt() : (job == null ? null : job.getUpdatedAt());
int percent = calculateDisplayProgressPercent(current, total, job, baseTime);
percent = Math.max(percent, extractSnapshotDisplayPercent(snapshot));
percent = Boolean.TRUE.equals(vo.getFileReady()) ? 100 : Math.min(99, percent);
vo.setFileProgressCurrent(current);
vo.setFileProgressTotal(total);
vo.setFileProgressPercent(percent);
@@ -3138,7 +3607,45 @@ public class SimilarAsinTaskService {
Integer batchIndex,
Integer batchTotal,
String ownerInstanceId,
Integer submitRetryCount) {
Integer submitRetryCount,
String credentialName) {
}
private static class SourceRowsBuilder {
private final String sourceFileKey;
private String sourceFilename;
private final List<SimilarAsinParsedRowVo> rows = new ArrayList<>();
private SourceRowsBuilder(String sourceFileKey, String sourceFilename) {
this.sourceFileKey = sourceFileKey;
this.sourceFilename = sourceFilename;
}
private String sourceFileKey() {
return sourceFileKey;
}
private String sourceFilename() {
return sourceFilename;
}
private void setSourceFilename(String sourceFilename) {
this.sourceFilename = sourceFilename;
}
private List<SimilarAsinParsedRowVo> rows() {
return rows;
}
}
private record SourceRows(String sourceFileKey,
String sourceFilename,
List<SimilarAsinParsedRowVo> rows) {
}
private record SourceResultWorkbook(File file,
String filename,
int rowCount) {
}
private record ParsedWorkbook(int totalRows, int droppedRows, List<String> headers, List<SimilarAsinParsedRowVo> allRows) {