Compare commits
3 Commits
16643f6912
...
3766a34360
| Author | SHA1 | Date | |
|---|---|---|---|
| 3766a34360 | |||
| 58c40b6695 | |||
| 96315fe302 |
+76
-2
@@ -14,6 +14,9 @@ import org.springframework.web.client.RestClient;
|
||||
|
||||
import com.nanri.aiimage.config.HttpClientPool;
|
||||
|
||||
import java.net.ConnectException;
|
||||
import java.net.NoRouteToHostException;
|
||||
import java.net.UnknownHostException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
@@ -53,6 +56,20 @@ public class BrandCheckClient {
|
||||
private static final String REASON_RESPONSE_TIMEOUT = "品牌检查响应超时";
|
||||
private static final String REASON_INTERRUPTED = "品牌检查被中断";
|
||||
private static final String REASON_UNEXPECTED_FAILURE = "品牌检查异常";
|
||||
/**
|
||||
* 「连接根本没建立」的证据条数:到这一数就收口整批的重试阶梯。
|
||||
*
|
||||
* <p>取 2 而不是 1:一次 refused/reset 可能是抖动,两次同形状、中间没有任何一次成功,
|
||||
* 才是服务在掉。与既有 {@code upstreamRejecting} 同一条保守口径——短路只省重试,
|
||||
* 每个品牌仍然真发得出它那一次首轮请求。
|
||||
*
|
||||
* <p>2026-10-22 现网:主机B→主机A:16890 被安全组挡死(B17 那次只恢复了 80/443),
|
||||
* 35 小时窗口里 Java 侧为这一形状发出去 {@code 请求异常将重试} <b>14,944</b> 次、
|
||||
* {@code 重试耗尽判定查询失败} <b>7,667</b> 次,而外观专利正在 B 上跑批
|
||||
* (taskId 31891)——用户看到的是交付表里成片的「商标查询失败」。
|
||||
*/
|
||||
private static final int CONNECT_FAILURE_EVIDENCE = 2;
|
||||
private static final String REASON_SERVICE_UNREACHABLE = "品牌检测服务不可达(连接未建立,非本行数据问题)";
|
||||
|
||||
/** 用户没配代理时交回的原因文案;采集侧与补测队列都按它把行判查询失败。 */
|
||||
public static final String NO_PROXY_REASON = "用户未配置代理";
|
||||
@@ -258,6 +275,9 @@ public class BrandCheckClient {
|
||||
// 一次批量一份判定:本批里只要有一个品牌跑满阶梯仍被判查询失败,其余品牌就不再
|
||||
// 各自烧完整条重试阶梯(见 checkOneBrand 的短路分支)。
|
||||
AtomicBoolean upstreamRejecting = new AtomicBoolean(false);
|
||||
// 连接层证据跨品牌累计:批内任一次成功响应清零(见 checkOneBrand)。
|
||||
// 一次批量一份,不跨批复用——另一批的 upstreamRejecting 也是这个理由。
|
||||
AtomicInteger connectFailures = new AtomicInteger();
|
||||
for (String brand : brands) {
|
||||
AtomicBoolean started = new AtomicBoolean(false);
|
||||
AtomicBoolean rejected = new AtomicBoolean(false);
|
||||
@@ -267,7 +287,8 @@ public class BrandCheckClient {
|
||||
future = CompletableFuture.supplyAsync(
|
||||
() -> {
|
||||
started.set(true);
|
||||
return checkOneBrand(brand, strategy, deadlineNanos, upstreamRejecting, proxyUrl, userId);
|
||||
return checkOneBrand(brand, strategy, deadlineNanos, upstreamRejecting,
|
||||
proxyUrl, userId, connectFailures);
|
||||
},
|
||||
checkExecutor);
|
||||
} finally {
|
||||
@@ -296,11 +317,13 @@ public class BrandCheckClient {
|
||||
}
|
||||
|
||||
private BrandCheckOutcome checkOneBrand(String brand, String strategy, long deadlineNanos,
|
||||
AtomicBoolean upstreamRejecting, String proxyUrl, Long userId) {
|
||||
AtomicBoolean upstreamRejecting, String proxyUrl, Long userId,
|
||||
AtomicInteger connectFailures) {
|
||||
int attempts = Math.max(1, properties.getRetryTimes());
|
||||
BrandCheckResponse response = null;
|
||||
Exception lastFailure = null;
|
||||
String reason = "";
|
||||
boolean connectDown = false;
|
||||
// 只有「把整条重试阶梯走完」才算拿到"上游在确定性拒绝"的证据。
|
||||
// 被预算或短路掐断的轮次不是证据,拿它去短路同批其余品牌会把偶发抖动放大成整批放弃。
|
||||
boolean ladderCompleted = true;
|
||||
@@ -325,11 +348,33 @@ public class BrandCheckClient {
|
||||
brand, attempt, attempts);
|
||||
break;
|
||||
}
|
||||
// 与上一条同构,但证据在连接层:会话根本没建立时重试阶梯救不回来(见常量注释的现网读数)
|
||||
if (attempt > 1 && connectFailures.get() >= CONNECT_FAILURE_EVIDENCE) {
|
||||
ladderCompleted = false;
|
||||
connectDown = true;
|
||||
log.warn("[brand-check] SERVICE_UNREACHABLE 同批已连续 {} 次连接未建立,本品牌停止重试"
|
||||
+ " brand={} attempt={}/{}",
|
||||
CONNECT_FAILURE_EVIDENCE, brand, attempt, attempts);
|
||||
break;
|
||||
}
|
||||
try {
|
||||
response = postCheck(brand, strategy, userId, proxyUrl);
|
||||
} catch (Exception ex) {
|
||||
lastFailure = ex;
|
||||
response = null;
|
||||
if (isConnectFailure(ex)) {
|
||||
if (connectFailures.incrementAndGet() >= CONNECT_FAILURE_EVIDENCE) {
|
||||
ladderCompleted = false;
|
||||
connectDown = true;
|
||||
log.warn("[brand-check] SERVICE_UNREACHABLE 连续 {} 次连接未建立,判定品牌检测服务不可达,"
|
||||
+ "停止重试 brand={} attempt={}/{} err={}",
|
||||
CONNECT_FAILURE_EVIDENCE, brand, attempt, attempts, ex.getMessage());
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
// 连上了只是这次没答好(读超时/解析失败):连接层证据不作数
|
||||
connectFailures.set(0);
|
||||
}
|
||||
if (attempt < attempts) {
|
||||
long retryDelayMillis = retryDelayMillis(attempt);
|
||||
log.warn("[brand-check] 请求异常将重试 brand={} attempt={}/{} 等待={}ms err={}",
|
||||
@@ -338,6 +383,8 @@ public class BrandCheckClient {
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// 拿到响应=连接是通的,证据清零,别跨到下一次真断连时凑数
|
||||
connectFailures.set(0);
|
||||
if (response != null && nullToEmpty(response.getQueryFaildData()).isEmpty()) {
|
||||
// 本次查询完成且无失败项:命中侵权(faild_data)属有效结论,不重试。
|
||||
return new BrandCheckOutcome(nullToEmpty(response.getFaildData()), List.of(), "");
|
||||
@@ -369,6 +416,13 @@ public class BrandCheckClient {
|
||||
&& !nullToEmpty(response.getQueryFaildData()).isEmpty()) {
|
||||
upstreamRejecting.set(true);
|
||||
}
|
||||
if (connectDown) {
|
||||
// 结论与旧版一致(这个品牌的商标维没核上),差别只在耗时与归因文案:
|
||||
// 品牌侧不再把一个"服务没连上"写成空 reason,交付表与补测队列都读得到真因
|
||||
log.warn("[brand-check] SERVICE_UNREACHABLE 品牌检测服务不可达,按查询失败收口 brand={} lastErr={}",
|
||||
brand, lastFailure == null ? "" : lastFailure.getMessage());
|
||||
return queryFailedOutcome(brand, REASON_SERVICE_UNREACHABLE);
|
||||
}
|
||||
log.warn("[brand-check] 重试耗尽判定查询失败 brand={} attempts={} lastErr={} reason={}",
|
||||
brand, attempts,
|
||||
lastFailure == null ? "query_faild_data 持续非空" : lastFailure.getMessage(), reason);
|
||||
@@ -490,6 +544,26 @@ public class BrandCheckClient {
|
||||
return new BrandCheckOutcome(List.of(), List.of(brand), reason);
|
||||
}
|
||||
|
||||
/**
|
||||
* 「会话根本没建立」的形状:连接被拒、无路由、域名解不开。
|
||||
*
|
||||
* <p>顺着 cause 链找:Spring 的 {@code ResourceAccessException} 把真凶挂在 cause 上
|
||||
* (现网日志读到的就是它那句 {@code I/O error on POST request for "..."}),
|
||||
* 而 JDK 的 {@code HttpConnectTimeoutException} 本身就是 {@code ConnectException} 的子类。
|
||||
*
|
||||
* <p>故意不含读超时与 5xx:那两种是"连上了但这次没答好",重试救得回来;把它们算进
|
||||
* 不可达证据,就会把一次上游抖动误判成服务在掉、把同批其余品牌的重试一起掐掉。
|
||||
*/
|
||||
static boolean isConnectFailure(Throwable error) {
|
||||
for (Throwable t = error; t != null && t != t.getCause(); t = t.getCause()) {
|
||||
if (t instanceof ConnectException || t instanceof NoRouteToHostException
|
||||
|| t instanceof UnknownHostException) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 单个品牌的结论。
|
||||
*
|
||||
|
||||
+45
@@ -25,6 +25,7 @@ import com.nanri.aiimage.modules.similarasin.model.dto.SimilarAsinSubmitResultRe
|
||||
import com.nanri.aiimage.modules.similarasin.model.entity.SimilarAsinFilterConditionEntity;
|
||||
import com.nanri.aiimage.modules.similarasin.model.vo.SimilarAsinDashboardVo;
|
||||
import com.nanri.aiimage.modules.similarasin.model.vo.SimilarAsinFilterConditionVo;
|
||||
import com.nanri.aiimage.modules.similarasin.model.vo.SimilarAsinHistoryItemVo;
|
||||
import com.nanri.aiimage.modules.similarasin.model.vo.SimilarAsinHistoryVo;
|
||||
import com.nanri.aiimage.modules.similarasin.model.vo.SimilarAsinParsedGroupVo;
|
||||
import com.nanri.aiimage.modules.similarasin.model.vo.SimilarAsinParsedRowVo;
|
||||
@@ -587,6 +588,7 @@ public class SimilarAsinTaskService implements SimilarAsinPipelineHost {
|
||||
for (FileTaskEntity task : fileTaskMapper.selectList(new LambdaQueryWrapper<FileTaskEntity>()
|
||||
.select(FileTaskEntity::getId,
|
||||
FileTaskEntity::getStatus,
|
||||
FileTaskEntity::getResumeOfTaskId,
|
||||
FileTaskEntity::getCreatedAt,
|
||||
FileTaskEntity::getFinishedAt)
|
||||
.in(FileTaskEntity::getId, taskIds))) {
|
||||
@@ -598,9 +600,52 @@ public class SimilarAsinTaskService implements SimilarAsinPipelineHost {
|
||||
.filter(Objects::nonNull)
|
||||
.toList());
|
||||
vo.getItems().addAll(historyAssembler().buildHistoryItems(rows, taskMap, jobMap));
|
||||
prependActiveTasksOutsideWindow(vo, userId, taskIds);
|
||||
return vo;
|
||||
}
|
||||
|
||||
/**
|
||||
* 把「结果行被挤出 top-N 窗口」的活跃任务补回列表最前。
|
||||
*
|
||||
* 历史列表按结果行 created_at 倒序取 50/100 行(每个任务一行):一个还在跑、但结果行
|
||||
* 排在窗口外的任务会从列表里彻底消失。前端「当前任务」唯一的兜底是内存里的实时缓存,
|
||||
* 页面重载/客户端更新即清零——于是用户看到的在跑任务凭空没了。这里按任务头补回;
|
||||
* 只补 RUNNING 与续跑克隆件(PENDING),未启动的解析预览不进列表(保持原历史语义)。
|
||||
*/
|
||||
private void prependActiveTasksOutsideWindow(SimilarAsinHistoryVo vo, Long userId, List<Long> coveredTaskIds) {
|
||||
List<FileTaskEntity> activeTasks = fileTaskMapper.selectList(new LambdaQueryWrapper<FileTaskEntity>()
|
||||
.select(FileTaskEntity::getId,
|
||||
FileTaskEntity::getStatus,
|
||||
FileTaskEntity::getResumeOfTaskId,
|
||||
FileTaskEntity::getCreatedAt,
|
||||
FileTaskEntity::getFinishedAt)
|
||||
.eq(FileTaskEntity::getModuleType, MODULE_TYPE)
|
||||
.eq(FileTaskEntity::getUserId, userId)
|
||||
.in(FileTaskEntity::getStatus, List.of(STATUS_PENDING, STATUS_RUNNING))
|
||||
.orderByDesc(FileTaskEntity::getCreatedAt)
|
||||
.last("limit 50"));
|
||||
if (activeTasks == null || activeTasks.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
SimilarAsinHistoryAssembler assembler = historyAssembler();
|
||||
List<SimilarAsinHistoryItemVo> activeItems = new ArrayList<>();
|
||||
for (FileTaskEntity task : activeTasks) {
|
||||
if (task == null || task.getId() == null) {
|
||||
continue;
|
||||
}
|
||||
if (coveredTaskIds.contains(task.getId())) {
|
||||
continue;
|
||||
}
|
||||
if (STATUS_PENDING.equals(task.getStatus()) && !assembler.isResumeClone(task)) {
|
||||
continue;
|
||||
}
|
||||
activeItems.add(assembler.buildActiveItem(task));
|
||||
}
|
||||
if (!activeItems.isEmpty()) {
|
||||
vo.getItems().addAll(0, activeItems);
|
||||
}
|
||||
}
|
||||
|
||||
public SimilarAsinTaskLightBatchVo progressLight(List<Long> taskIds) {
|
||||
SimilarAsinTaskLightBatchVo vo = new SimilarAsinTaskLightBatchVo();
|
||||
List<Long> normalizedIds = taskIds == null ? List.of() : taskIds.stream()
|
||||
|
||||
+33
-3
@@ -76,8 +76,13 @@ public class SimilarAsinHistoryAssembler {
|
||||
}
|
||||
|
||||
/**
|
||||
* 按 rows 顺序组装历史项;PENDING 任务(history 语义)跳过。
|
||||
* taskMap/jobMap 均为调用方已查好的映射,本方法只读不改输入。
|
||||
* 按 rows 顺序组装历史项;PENDING 只在「续跑克隆件」时保留,普通解析预览仍按原口径跳过。
|
||||
*
|
||||
* 为什么续跑件必须留:客户端更新打断任务后,V129 自动续跑会克隆出一条新的 PENDING
|
||||
* (TaskRetryCloneSupport 置 status=PENDING + resume_of_task_id=原件)。原件已 FAILED 沉进历史,
|
||||
* 这条克隆件如果在这里被跳过,就出现「当前任务」和「历史任务」两头都看不到的空窗——
|
||||
* 用户看到的正是「更新完在跑的任务没了」,得等某个在线客户端把它领走才重新出现。
|
||||
* 普通 PENDING(只解析未启动的预览)不进列表,避免用户没打算跑的预览一直挂在当前任务里。
|
||||
*/
|
||||
public List<SimilarAsinHistoryItemVo> buildHistoryItems(List<FileResultEntity> rows,
|
||||
Map<Long, FileTaskEntity> taskMap,
|
||||
@@ -89,7 +94,7 @@ public class SimilarAsinHistoryAssembler {
|
||||
for (FileResultEntity row : rows) {
|
||||
FileTaskEntity task = taskMap.get(row.getTaskId());
|
||||
String taskStatus = task == null ? null : task.getStatus();
|
||||
if (STATUS_PENDING.equals(taskStatus)) {
|
||||
if (STATUS_PENDING.equals(taskStatus) && !isResumeClone(task)) {
|
||||
continue;
|
||||
}
|
||||
items.add(toHistoryItem(row, task, jobMap.get(row.getId())));
|
||||
@@ -97,6 +102,31 @@ public class SimilarAsinHistoryAssembler {
|
||||
return items;
|
||||
}
|
||||
|
||||
/** 续跑克隆件:已经跑过、被中断后重新排队的 PENDING(resume_of_task_id 指向原件)。 */
|
||||
public boolean isResumeClone(FileTaskEntity task) {
|
||||
return task != null && task.getResumeOfTaskId() != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 由任务头拼一条「结果行不在返回窗口里」的列表项(仍在执行、或续跑排队中)。
|
||||
*
|
||||
* 历史列表是按结果行 created_at 倒序的 top-N 窗口(每个任务一行);一个还在跑、
|
||||
* 但结果行被更新任务挤出窗口的任务会从列表里整个消失,客户端更新/页面重载后
|
||||
* 前端「当前任务」的兜底(内存缓存)也已经清零——用户看到的就是任务没了。
|
||||
* 这里只带前端渲染当前任务所需字段:没有 resultId/downloadUrl 表示还没有结果文件,
|
||||
* 进度链拿不到结果行就不伪造百分比,由页面按 taskStatus 显示「执行中/排队中」。
|
||||
*/
|
||||
public SimilarAsinHistoryItemVo buildActiveItem(FileTaskEntity task) {
|
||||
SimilarAsinHistoryItemVo vo = new SimilarAsinHistoryItemVo();
|
||||
vo.setTaskId(task.getId());
|
||||
vo.setTaskStatus(task.getStatus());
|
||||
vo.setSuccess(false);
|
||||
vo.setCreatedAt(fmt(task.getCreatedAt()));
|
||||
vo.setStartedAt(fmt(task.getCreatedAt()));
|
||||
vo.setFinishedAt(fmt(task.getFinishedAt()));
|
||||
return vo;
|
||||
}
|
||||
|
||||
private SimilarAsinHistoryItemVo toHistoryItem(FileResultEntity row, FileTaskEntity task, TaskFileJobEntity job) {
|
||||
SimilarAsinHistoryItemVo vo = new SimilarAsinHistoryItemVo();
|
||||
vo.setResultId(row.getId());
|
||||
|
||||
+78
@@ -8,7 +8,13 @@ import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.net.ConnectException;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.NoRouteToHostException;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.SocketTimeoutException;
|
||||
import java.net.UnknownHostException;
|
||||
import java.net.http.HttpTimeoutException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
@@ -16,6 +22,8 @@ import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import org.springframework.web.client.ResourceAccessException;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
@@ -167,6 +175,76 @@ class BrandCheckClientTest {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 连接根本没建立时,重试阶梯救不回来 —— 2026-10-22 现网那一刀的形状。
|
||||
*
|
||||
* <p>主机B→主机A:16890 被安全组挡死(B17 那次摘 DROP 只恢复了 80/443),35 小时窗口里
|
||||
* {@code 请求异常将重试} 14,944 次、{@code 重试耗尽判定查询失败} 7,667 次,而外观专利
|
||||
* 正在 B 上跑批:每个品牌烧满 10 轮(约 45~65 秒)只为了得到同一个「连不上」。
|
||||
* 收口的判据是证据条数(批内连续两次连接失败、中间没有任何一次成功),
|
||||
* 结论一字不变——每条品牌仍全部判查询失败,只是不再白等,且 reason 写明是服务不可达。
|
||||
*/
|
||||
@Test
|
||||
void connectRefusalsStopTheWholeBatchFromBurningRetryLadders() throws Exception {
|
||||
BrandCheckClient client = newClientToClosedPort(10, 300, 60_000);
|
||||
List<String> brands = List.of("b1", "b2", "b3", "b4", "b5", "b6");
|
||||
|
||||
long startedAt = System.nanoTime();
|
||||
BrandCheckClient.BrandCheckBatchResult result = client.checkAll(brands, "Terms", 60_000L, 7L);
|
||||
long elapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startedAt);
|
||||
|
||||
assertThat(result.queryFaildData()).as("短路只省白等,不改结论:6 个品牌仍全部判查询失败")
|
||||
.hasSize(brands.size());
|
||||
assertThat(result.reason()).as("归因必须写明「服务没连上」,不许再留空 reason").contains("品牌检测服务不可达");
|
||||
// 不短路时:6 品牌按并发 3 分两波,每波阶梯 300×(1+…+9)≈13.5 秒 ≈ 27 秒;
|
||||
// 判据取 5 秒——远低于"烧满"的最坏读数,又给机器负载留了十倍余量。
|
||||
assertThat(elapsedMillis).as("连接层证据到两次即收口,实测耗时=%dms", elapsedMillis)
|
||||
.isLessThan(5_000L);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判据必须只认"会话没建立"这一类。读超时与 5xx 是"连上了但这次没答好",
|
||||
* 把它们算进不可达证据,一次上游抖动就会掐掉同批别的品牌本该拿到的重试。
|
||||
*/
|
||||
@Test
|
||||
void connectFailurePredicateSeparatesNoConnectionFromBadAnswer() {
|
||||
assertThat(BrandCheckClient.isConnectFailure(
|
||||
new ConnectException("Connection refused: connect"))).isTrue();
|
||||
assertThat(BrandCheckClient.isConnectFailure(
|
||||
new UnknownHostException("brand.aishufu.top"))).isTrue();
|
||||
assertThat(BrandCheckClient.isConnectFailure(new NoRouteToHostException("no route"))).isTrue();
|
||||
// Spring 把真凶挂在 cause 上,现网日志读到的就是外层那句 I/O error
|
||||
assertThat(BrandCheckClient.isConnectFailure(new ResourceAccessException(
|
||||
"I/O error on POST request for \"http://127.0.0.1:16890/brand_check\"",
|
||||
new ConnectException("Connection refused")))).isTrue();
|
||||
|
||||
assertThat(BrandCheckClient.isConnectFailure(
|
||||
new SocketTimeoutException("Read timed out"))).isFalse();
|
||||
assertThat(BrandCheckClient.isConnectFailure(
|
||||
new HttpTimeoutException("request timed out"))).isFalse();
|
||||
assertThat(BrandCheckClient.isConnectFailure(
|
||||
new IllegalStateException("500 Internal Server Error"))).isFalse();
|
||||
assertThat(BrandCheckClient.isConnectFailure(null)).isFalse();
|
||||
}
|
||||
|
||||
/** 一个确定没人监听的端口:connect 当场被拒,正是"服务不在了"而不是"服务很慢"。 */
|
||||
private static int closedPort() throws IOException {
|
||||
try (ServerSocket socket = new ServerSocket(0)) {
|
||||
return socket.getLocalPort();
|
||||
}
|
||||
}
|
||||
|
||||
private BrandCheckClient newClientToClosedPort(int retryTimes, int retryIntervalMillis,
|
||||
int totalTimeoutMillis) throws IOException {
|
||||
BrandCheckProperties props = new BrandCheckProperties();
|
||||
props.setBaseUrl("http://127.0.0.1:" + closedPort());
|
||||
props.setPath("/brand_check");
|
||||
props.setRetryTimes(retryTimes);
|
||||
props.setRetryIntervalMillis(retryIntervalMillis);
|
||||
props.setTotalTimeoutMillis(totalTimeoutMillis);
|
||||
return new BrandCheckClient(props, null, stubbedUserSecrets());
|
||||
}
|
||||
|
||||
private BrandCheckClient newClient(HttpServer server, int retryTimes) {
|
||||
BrandCheckProperties props = new BrandCheckProperties();
|
||||
props.setBaseUrl("http://127.0.0.1:" + server.getAddress().getPort());
|
||||
|
||||
+64
-2
@@ -45,6 +45,7 @@ import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
@@ -161,6 +162,26 @@ class SimilarAsinTaskServiceHistoryBatchTest {
|
||||
LambdaQueryWrapper<FileTaskEntity> q = invocation.getArgument(0);
|
||||
String segment = q.getSqlSegment() == null ? "" : q.getSqlSegment();
|
||||
List<Object> params = paramValuesOf(q, segment);
|
||||
// 非终态任务查询(history 补回窗口外的在跑任务):按 status 条件过滤任务表。
|
||||
// MyBatis-Plus 3.5.7 把 IN 展开成逐值占位符,所以字符串参数要两个分支一起收。
|
||||
if (segment.contains("status")) {
|
||||
List<String> wantedStatuses = new ArrayList<>();
|
||||
for (Object value : params) {
|
||||
if (value instanceof List<?> list) {
|
||||
for (Object item : list) {
|
||||
if (item instanceof String status) {
|
||||
wantedStatuses.add(status);
|
||||
}
|
||||
}
|
||||
} else if (value instanceof String status) {
|
||||
wantedStatuses.add(status);
|
||||
}
|
||||
}
|
||||
return taskDb.stream()
|
||||
.filter(t -> wantedStatuses.contains(t.getStatus()))
|
||||
.filter(t -> MODULE.equals(t.getModuleType()))
|
||||
.toList();
|
||||
}
|
||||
List<Long> wanted = new ArrayList<>();
|
||||
for (Object value : params) {
|
||||
if (value instanceof List<?> list) {
|
||||
@@ -306,6 +327,46 @@ class SimilarAsinTaskServiceHistoryBatchTest {
|
||||
vo.getItems().stream().map(SimilarAsinHistoryItemVo::getResultId).toList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void historyIncludesActiveTaskOutsideResultWindow() throws Exception {
|
||||
// 结果行窗口只装得下新任务;老任务还在跑,结果行已被挤出窗口
|
||||
taskDb.add(task(900L, "RUNNING", LocalDateTime.of(2026, 8, 1, 8, 0)));
|
||||
seed(3, 3, 0);
|
||||
|
||||
SimilarAsinHistoryVo vo = service.history(1L, 3);
|
||||
|
||||
assertEquals(4, vo.getItems().size(), "窗口外仍在跑的任务必须补回列表");
|
||||
SimilarAsinHistoryItemVo first = vo.getItems().getFirst();
|
||||
assertEquals(900L, first.getTaskId(), "补回项排在最前");
|
||||
assertEquals("RUNNING", first.getTaskStatus());
|
||||
assertNull(first.getResultId(), "补回项还没有结果行,不许伪造");
|
||||
}
|
||||
|
||||
@Test
|
||||
void historyDoesNotDuplicateActiveTaskAlreadyInWindow() throws Exception {
|
||||
seed(1, 1, 0);
|
||||
taskDb.getFirst().setStatus("RUNNING");
|
||||
|
||||
SimilarAsinHistoryVo vo = service.history(1L, 50);
|
||||
|
||||
assertEquals(1, vo.getItems().size(), "结果行已在窗口里的任务不得重复补回");
|
||||
}
|
||||
|
||||
@Test
|
||||
void historyHidesPendingPreviewButKeepsResumeCloneOutsideWindow() throws Exception {
|
||||
taskDb.add(task(910L, "PENDING", LocalDateTime.of(2026, 8, 2, 9, 0)));
|
||||
FileTaskEntity clone = task(911L, "PENDING", LocalDateTime.of(2026, 8, 2, 10, 0));
|
||||
clone.setResumeOfTaskId(910L);
|
||||
taskDb.add(clone);
|
||||
seed(2, 2, 0);
|
||||
|
||||
SimilarAsinHistoryVo vo = service.history(1L, 50);
|
||||
|
||||
List<Long> taskIds = vo.getItems().stream().map(SimilarAsinHistoryItemVo::getTaskId).toList();
|
||||
assertTrue(taskIds.contains(911L), "续跑克隆件必须可见(更新打断后就靠它显示)");
|
||||
assertFalse(taskIds.contains(910L), "未启动的解析预览不进列表");
|
||||
}
|
||||
|
||||
@Test
|
||||
void historyMissingRelated() throws Exception {
|
||||
resultDb.add(result(201L, 9999L, 1L, LocalDateTime.of(2026, 8, 1, 10, 1)));
|
||||
@@ -344,10 +405,11 @@ class SimilarAsinTaskServiceHistoryBatchTest {
|
||||
seed(20, 4, 20);
|
||||
service.history(1L, 50);
|
||||
verify(fileResultMapper, org.mockito.Mockito.times(1)).selectList(any());
|
||||
verify(fileTaskMapper, org.mockito.Mockito.times(1)).selectList(any());
|
||||
// 2 次固定任务查询:①结果行 taskId 的 IN 批查;②窗口外非终态任务的补回查询
|
||||
verify(fileTaskMapper, org.mockito.Mockito.times(2)).selectList(any());
|
||||
verify(taskFileJobService, org.mockito.Mockito.times(1)).findAssembleJobsByResultIds(eq(MODULE), anyList());
|
||||
assertEquals(1, resultSelectCount.get(), "结果 1 次 IN 查询");
|
||||
assertEquals(1, taskSelectCount.get(), "任务 1 次 IN 查询");
|
||||
assertEquals(2, taskSelectCount.get(), "任务 2 次固定查询(IN 批查 + 非终态补回)");
|
||||
assertEquals(1, jobSelectCount.get(), "Job 1 次 IN 查询");
|
||||
assertEquals(20, resultSelectCount.get() * 20, "查询次数与结果行数无关(无 N+1)");
|
||||
}
|
||||
|
||||
+2
-1
@@ -434,7 +434,8 @@ class SimilarAsinTaskServicePerf500Test {
|
||||
jobQueryCount.set(0);
|
||||
service.history(USER_ID, HISTORY_LIMIT);
|
||||
assertTrue(resultSelectCount.get() <= 1, "history 结果查询 ≤ 1 次");
|
||||
assertTrue(taskSelectCount.get() <= 1, "history 任务查询 ≤ 1 次");
|
||||
// 2 次固定任务查询:①结果行 taskId 的 IN 批查;②窗口外非终态任务的补回查询(都是常数,与行数无关)
|
||||
assertTrue(taskSelectCount.get() <= 2, "history 任务查询 ≤ 2 次");
|
||||
assertTrue(jobQueryCount.get() <= 2, "history Job 查询 ≤ 2 次(findAssembleJobsByResultIds 一次)");
|
||||
int historyTotal = resultSelectCount.get() + taskSelectCount.get() + jobQueryCount.get();
|
||||
assertTrue(historyTotal <= MAX_QUERY_COUNT_HISTORY,
|
||||
|
||||
+25
-3
@@ -239,13 +239,35 @@ class SimilarAsinHistoryAssemblerTest {
|
||||
Map<Long, FileTaskEntity> taskMap = new LinkedHashMap<>();
|
||||
taskMap.put(10L, task(10L, "PENDING", null));
|
||||
taskMap.put(11L, task(11L, "RUNNING", null));
|
||||
// 续跑克隆件:客户端更新打断后 V129 自动续跑排回来的 PENDING(resume_of_task_id 指向原件),
|
||||
// 原件已 FAILED 沉进历史,这一条再被跳过就两头都看不到——必须保留
|
||||
taskMap.put(12L, task(12L, "PENDING", null));
|
||||
taskMap.get(12L).setResumeOfTaskId(11L);
|
||||
|
||||
List<SimilarAsinHistoryItemVo> items = assembler.buildHistoryItems(
|
||||
List.of(result(100L, 10L, "a.xlsx", null, 0), result(101L, 11L, "b.xlsx", null, 0)),
|
||||
List.of(result(100L, 10L, "a.xlsx", null, 0),
|
||||
result(101L, 11L, "b.xlsx", null, 0),
|
||||
result(102L, 12L, "c.xlsx", null, 0)),
|
||||
taskMap, jobMap());
|
||||
|
||||
assertEquals(1, items.size(), "PENDING 任务历史项被跳过");
|
||||
assertEquals(101L, items.get(0).getResultId());
|
||||
assertEquals(2, items.size(), "普通 PENDING 预览跳过,续跑克隆件保留");
|
||||
assertEquals(List.of(101L, 102L),
|
||||
items.stream().map(SimilarAsinHistoryItemVo::getResultId).toList());
|
||||
assertEquals("PENDING", items.get(1).getTaskStatus(), "克隆件按排队中呈现");
|
||||
}
|
||||
|
||||
@Test
|
||||
void test_assembler_active_item_without_result_row() {
|
||||
FileTaskEntity running = task(20L, "RUNNING", LocalDateTime.of(2026, 8, 2, 9, 0));
|
||||
|
||||
SimilarAsinHistoryItemVo item = assembler.buildActiveItem(running);
|
||||
|
||||
assertEquals(20L, item.getTaskId());
|
||||
assertEquals("RUNNING", item.getTaskStatus());
|
||||
assertNull(item.getResultId(), "还没有结果行,不许伪造 resultId");
|
||||
assertNull(item.getDownloadUrl());
|
||||
assertEquals(Boolean.FALSE, item.getSuccess());
|
||||
assertEquals("2026-08-02T09:00", item.getStartedAt());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -776,16 +776,24 @@ async function loadDashboard() {
|
||||
}
|
||||
}
|
||||
|
||||
/** 上一轮 /history 是真拉到的还是失败的:失败轮没有任何资格判定任务「已不存在」 */
|
||||
let historyLoadOk = false
|
||||
|
||||
async function loadHistory() {
|
||||
try {
|
||||
const vo = await getPriceTrackHistory()
|
||||
historyItems.value = vo.items || []
|
||||
historyLoadOk = true
|
||||
} catch {
|
||||
historyItems.value = []
|
||||
// 失败保留上一轮列表:清成空会让紧接着的结算把在跑的任务判成「已不存在」,
|
||||
// 连带删掉 localStorage 里的轮询 id 与快照——一次抖动(或客户端更新的那几十秒)
|
||||
// 就能把「当前任务」整个抹没,用户看到的就是任务凭空消失。
|
||||
historyLoadOk = false
|
||||
}
|
||||
}
|
||||
|
||||
function syncPollingIdsWithHistory() {
|
||||
if (!historyLoadOk) return
|
||||
for (const taskId of [...pollingTaskIds.value]) {
|
||||
const any = historyItems.value.some((r) => r.taskId === taskId)
|
||||
if (!any && !taskSnapshots.value[taskId]) {
|
||||
|
||||
@@ -522,8 +522,13 @@ async function removeMatchedRow(row: ProductRiskShopQueueItem) {
|
||||
}
|
||||
}
|
||||
|
||||
/** 上一轮 /history 是真拉到的还是失败的:失败轮没有任何资格判定任务「已不存在」 */
|
||||
let historyLoadOk = false
|
||||
|
||||
/** 历史列表中已无该 taskId 时,停止轮询并清本地快照 */
|
||||
function syncPollingIdsWithHistory() {
|
||||
// 本轮 /history 没真拉到就不结算:否则一次拉取失败等于把每个在跑的任务判成「已不存在」
|
||||
if (!historyLoadOk) return
|
||||
for (const taskId of [...pollingTaskIds.value]) {
|
||||
const rows = historyItems.value.filter((r) => r.taskId === taskId)
|
||||
if (!rows.length || rows.some((row) => isHistoryItemTerminal(row))) {
|
||||
@@ -630,8 +635,11 @@ async function loadCandidates() {
|
||||
async function loadHistory() {
|
||||
try {
|
||||
historyItems.value = (await getProductRiskHistory()).items || []
|
||||
historyLoadOk = true
|
||||
} catch {
|
||||
historyItems.value = []
|
||||
// 失败保留上一轮列表:清成空会让下面的结算把每一个在跑的任务都判成「已不存在」,
|
||||
// 连带删光本地轮询 id——客户端更新/网络抖动那几十秒就足以把「当前任务」整个抹没。
|
||||
historyLoadOk = false
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -92,7 +92,7 @@
|
||||
<button type="button" class="btn-refresh" @click="refreshList">刷新任务状态</button>
|
||||
</div>
|
||||
<div class="queue-body">
|
||||
<div v-if="!currentTasks.length" class="empty-tasks">暂无变体采集任务</div>
|
||||
<div v-if="!currentTasks.length" class="empty-tasks" :class="{ 'empty-warn': Boolean(listNotice) }">{{ listNotice || '暂无变体采集任务' }}</div>
|
||||
<div v-else class="queue-grid">
|
||||
<div v-for="item in currentTasks" :key="`vc-${item.task_id}`" class="task-card">
|
||||
<div class="task-card-head">
|
||||
@@ -171,6 +171,11 @@ import { saveUrlWithProgress } from '@/shared/utils/download-progress'
|
||||
import { isHttpUrl, safeHttpUrl } from '@/shared/utils/safe-url'
|
||||
import { createCategorizedTimers } from '@/shared/utils/categorized-timers'
|
||||
import { useHistoryPolling } from '@/shared/composables/useHistoryPolling'
|
||||
import {
|
||||
bridgeListHint,
|
||||
runBridgeListFirstLoad,
|
||||
type BridgeListAttempt,
|
||||
} from '@/shared/bridges/bridge-list-state'
|
||||
import { taskStatusClass, taskStatusText, type TaskStatusOptions } from '@/shared/utils/task-status-text'
|
||||
|
||||
/** 本地任务记录:桥接返回的列表项 + 前端维护字段 */
|
||||
@@ -206,6 +211,8 @@ const currentPage = ref(1)
|
||||
const totalPages = ref(1)
|
||||
const totalCount = ref(0)
|
||||
const isLoading = ref(false)
|
||||
/** 最近一次列表取回的结局:桥未就绪/登录态未恢复/请求失败都不得再伪装成「暂无任务」 */
|
||||
const listState = ref<BridgeListAttempt>('bridge')
|
||||
|
||||
const detailVisible = ref(false)
|
||||
const detailItem = ref<VariantEntry | null>(null)
|
||||
@@ -215,6 +222,8 @@ const asinLines = computed(() => asinText.value.split(/\r?\n/).map((s) => s.trim
|
||||
const currentTasks = computed(() =>
|
||||
currentTaskIds.value.map((id) => tasks[id]).filter((item): item is VariantEntry => Boolean(item)),
|
||||
)
|
||||
/** 列表为空时才给失败文案;有任务时不抢话 */
|
||||
const listNotice = computed(() => (currentTasks.value.length ? '' : bridgeListHint(listState.value)))
|
||||
const canSubmit = computed(() =>
|
||||
inputMode.value === 'asin' ? asinLines.value.length > 0 : selectedFiles.value.length > 0,
|
||||
)
|
||||
@@ -474,16 +483,25 @@ async function refreshTask(item: VariantTaskListItem) {
|
||||
}
|
||||
}
|
||||
|
||||
async function loadTasks(page?: number) {
|
||||
async function loadTasks(page?: number): Promise<BridgeListAttempt> {
|
||||
if (isLoading.value) return listState.value
|
||||
const bridge = getPywebviewApi()
|
||||
if (!bridge?.vc_list_tasks) return
|
||||
if (isLoading.value) return
|
||||
if (!uid()) return
|
||||
if (!bridge?.vc_list_tasks) {
|
||||
listState.value = 'bridge'
|
||||
return 'bridge'
|
||||
}
|
||||
if (!uid()) {
|
||||
listState.value = 'uid'
|
||||
return 'uid'
|
||||
}
|
||||
isLoading.value = true
|
||||
try {
|
||||
const targetPage = page || currentPage.value || 1
|
||||
const res = await bridge.vc_list_tasks({ uid: uid(), page: targetPage, page_size: PAGE_SIZE })
|
||||
if (!res?.success) return
|
||||
if (!res?.success) {
|
||||
listState.value = 'failed'
|
||||
return 'failed'
|
||||
}
|
||||
currentPage.value = res.page || targetPage || 1
|
||||
totalPages.value = Math.max(1, res.total_page || 1)
|
||||
totalCount.value = res.total || (res.tasks || []).length
|
||||
@@ -510,8 +528,12 @@ async function loadTasks(page?: number) {
|
||||
ids.push(item.task_id)
|
||||
})
|
||||
currentTaskIds.value = ids
|
||||
listState.value = 'ok'
|
||||
return 'ok'
|
||||
} catch {
|
||||
/* 静默:列表加载失败时保留现状 */
|
||||
// 失败不清列表(保留上一轮读数),但必须让用户看见「这次没取到」而不是「没有任务」
|
||||
listState.value = 'failed'
|
||||
return 'failed'
|
||||
} finally {
|
||||
isLoading.value = false
|
||||
}
|
||||
@@ -738,9 +760,23 @@ function cleanup() {
|
||||
timers.clearScope()
|
||||
}
|
||||
|
||||
/**
|
||||
* 首拉引导:客户端更新或启动的头几秒桥还没注入(getPywebviewApi() 退化成不含 vc_ 方法的
|
||||
* 降级桥),此前「onMounted 只发一次 + 轮询要等有活跃任务」两件事咬死——撞空一次就永久
|
||||
* 停在「暂无变体采集任务」,用户看到在跑的任务凭空没了。这里重试到成功或次数用尽。
|
||||
*/
|
||||
async function bootstrapListLoad() {
|
||||
const result = await runBridgeListFirstLoad(() => loadTasks(1), {
|
||||
sleep: (ms) => timers.sleep('list-bootstrap', ms),
|
||||
isCancelled: () => disposed,
|
||||
})
|
||||
if (result.cancelled || disposed || result.attempt === 'ok') return
|
||||
ElMessage.warning(`${bridgeListHint(result.attempt)},可点「刷新任务状态」再试`)
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
// 首发只发一次:此前 startPolling() 的立即 loadTasks(1) 与 scheduleAutoRefresh() 各打一遍同一页
|
||||
void loadTasks(1)
|
||||
// 只起这一条链:此前立即 loadTasks(1) 与 scheduleAutoRefresh() 各打一遍同一页
|
||||
void bootstrapListLoad()
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
@@ -809,6 +845,7 @@ onBeforeUnmount(() => {
|
||||
.page-btn:disabled { opacity: 0.4; cursor: not-allowed; }
|
||||
.page-now { min-width: 22px; text-align: center; color: #c8d2e2; font-size: 12px; }
|
||||
.empty-tasks { color: #5e6878; font-size: 13px; padding: 12px 0; text-align: center; }
|
||||
.empty-warn { color: #e0b341; }
|
||||
.detail-body { max-height: 60vh; overflow: auto; }
|
||||
.kv-row { display: flex; gap: 12px; padding: 6px 0; font-size: 13px; }
|
||||
.kv-key { flex-shrink: 0; width: 110px; color: #5e6878; }
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
/**
|
||||
* 桌面桥任务列表的取回判据(客户端更新后「在跑的任务列表没掉」修复)。
|
||||
*
|
||||
* 客户端更新=进程被 update.exe 替换 + WebView 整页重载。这一瞬 `window.pywebview` 还没注入,
|
||||
* `getPywebviewApi()` 退化成不含任何 `vc_` 方法的降级桥,于是页面里那句
|
||||
* `if (!bridge?.vc_list_tasks) return` 把「桥还没起来」渲染成「暂无任务」;而列表轮询又被
|
||||
* 「列表里有活跃任务才启动」反锁——首拉撞上这个窗口 ⇒ 列表空 ⇒ 活跃任务恒 false ⇒
|
||||
* 轮询永不启动 ⇒ 这一页被钉死在空列表,除了手点刷新没有出路。
|
||||
*
|
||||
* 这里只收敛**无副作用的判据与首拉重试驱动**:败在哪一环、有没有可见文案、要不要接着试。
|
||||
* 计时器与页面状态由调用方注入,本模块不碰 window。
|
||||
*/
|
||||
|
||||
import { getTaskPollBackoffMs } from '../task-progress-config.ts'
|
||||
|
||||
/** 一次列表取回的结局:成功 / 桥未就绪 / 登录态未恢复 / 请求或后端失败 */
|
||||
export type BridgeListAttempt = 'ok' | 'bridge' | 'uid' | 'failed'
|
||||
|
||||
/** 首拉最多试几轮(含首次)。退避曲线复用任务轮询那一套:0.5s→1s→2s→4s→8s→10s 封顶,
|
||||
* 8 轮累计约 35 秒,覆盖客户端进程替换到页面可打桥的实测窗口。 */
|
||||
export const BRIDGE_LIST_FIRST_LOAD_MAX_ATTEMPTS = 8
|
||||
|
||||
/** 每种结局的用户可见文案;非 ok 一律不许空白呈现(静默 catch 棘轮同源口径)。 */
|
||||
const BRIDGE_LIST_HINTS: Record<Exclude<BridgeListAttempt, 'ok'>, string> = {
|
||||
bridge: '客户端正在启动或更新,任务列表暂时连不上,会自动重试…',
|
||||
uid: '登录态还没恢复,任务列表暂时取不到,请重新登录后再看',
|
||||
failed: '任务列表拉取失败,会自动重试',
|
||||
}
|
||||
|
||||
export function bridgeListHint(attempt: BridgeListAttempt): string {
|
||||
return attempt === 'ok' ? '' : BRIDGE_LIST_HINTS[attempt]
|
||||
}
|
||||
|
||||
/** 只有成功不必再试;其余三种都值得再试(桥会起来、登录态会补上、网络会恢复)。 */
|
||||
export function isRetryableBridgeListAttempt(attempt: BridgeListAttempt): boolean {
|
||||
return attempt !== 'ok'
|
||||
}
|
||||
|
||||
/** 第 attempts 次尝试(从 1 计)之后该等多久。 */
|
||||
export function bridgeListRetryDelayMs(attempts: number): number {
|
||||
return getTaskPollBackoffMs(Math.max(0, attempts - 1))
|
||||
}
|
||||
|
||||
export interface BridgeListFirstLoadOptions {
|
||||
/** 已尝试次数(含首次)的上限 */
|
||||
maxAttempts?: number
|
||||
/** 注入退避曲线(测试用) */
|
||||
delayMs?: (attempts: number) => number
|
||||
/** 注入等待:页面用 categorized-timers 的 sleep,卸载时随 scope 一起清掉 */
|
||||
sleep: (ms: number) => Promise<void>
|
||||
/** 组件已卸载/用户已切换:立即停止,不再续链 */
|
||||
isCancelled?: () => boolean
|
||||
/** 每轮结局回调(页面据此更新可见提示) */
|
||||
onAttempt?: (result: { attempt: BridgeListAttempt; attempts: number }) => void
|
||||
}
|
||||
|
||||
export interface BridgeListFirstLoadResult {
|
||||
attempt: BridgeListAttempt
|
||||
attempts: number
|
||||
/** 被调用方取消(组件卸载)时为 true:此时不代表列表真的取不到 */
|
||||
cancelled: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* 首拉驱动:把「只发一次就放弃」换成「重试到成功或次数用尽」。
|
||||
*
|
||||
* load() 必须自己把失败归成 'bridge' | 'uid' | 'failed' 并返回,不得抛(抛了这里不兜,
|
||||
* 免得把真 bug 吞成一次重试)。成功即停;失败按退避重试;取消即停且不算失败。
|
||||
*/
|
||||
export async function runBridgeListFirstLoad(
|
||||
load: () => Promise<BridgeListAttempt>,
|
||||
options: BridgeListFirstLoadOptions,
|
||||
): Promise<BridgeListFirstLoadResult> {
|
||||
const maxAttempts = options.maxAttempts ?? BRIDGE_LIST_FIRST_LOAD_MAX_ATTEMPTS
|
||||
const delayMs = options.delayMs ?? bridgeListRetryDelayMs
|
||||
let attempts = 0
|
||||
let attempt: BridgeListAttempt = 'bridge'
|
||||
while (attempts < maxAttempts) {
|
||||
if (options.isCancelled?.()) {
|
||||
return { attempt, attempts, cancelled: true }
|
||||
}
|
||||
attempt = await load()
|
||||
attempts += 1
|
||||
options.onAttempt?.({ attempt, attempts })
|
||||
if (!isRetryableBridgeListAttempt(attempt)) break
|
||||
if (attempts >= maxAttempts) break
|
||||
await options.sleep(delayMs(attempts))
|
||||
}
|
||||
return { attempt, attempts, cancelled: false }
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join } from 'node:path'
|
||||
|
||||
import {
|
||||
BRIDGE_LIST_FIRST_LOAD_MAX_ATTEMPTS,
|
||||
bridgeListHint,
|
||||
bridgeListRetryDelayMs,
|
||||
isRetryableBridgeListAttempt,
|
||||
runBridgeListFirstLoad,
|
||||
} from '../src/shared/bridges/bridge-list-state.ts'
|
||||
|
||||
/**
|
||||
* 「更新客户端 → 在跑的任务列表没掉」回归钉。
|
||||
*
|
||||
* 现场:点「立即更新」→ 闸门放行 → 进程被 update.exe 替换 → WebView 整页重载。
|
||||
* 重载那一下 pywebview 桥还没注入,`getPywebviewApi()` 返回的降级桥里 vc_ 方法数为 0,
|
||||
* 而变体采集页把「桥不在」和「没有任务」画成同一句「暂无变体采集任务」,
|
||||
* 首拉又只发一次、轮询还被「列表里有活跃任务」反锁 ⇒ 用户看到在跑的任务凭空没了。
|
||||
* 这里钉三件事:①首拉必须重试到桥起来;②每种失败都要有可见文案;
|
||||
* ③跟价页一次拉取失败不得反过来把本地轮询 id 连快照一起删掉。
|
||||
*/
|
||||
|
||||
const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..')
|
||||
|
||||
function sourceOf(rel: string) {
|
||||
return readFileSync(join(ROOT, rel), 'utf8')
|
||||
}
|
||||
|
||||
const VARIANT = 'src/pages/brand/components/BrandVariantTab.vue'
|
||||
const PRICE_TRACK = 'src/pages/brand/components/BrandPriceTrackTab.vue'
|
||||
const PRODUCT_RISK = 'src/pages/brand/components/BrandProductRiskTab.vue'
|
||||
|
||||
async function noWait(ms: number) {
|
||||
void ms
|
||||
}
|
||||
|
||||
test('桥未就绪的那几次必须重试回来,不能一次撞空就放弃', async () => {
|
||||
const seen: string[] = []
|
||||
const result = await runBridgeListFirstLoad(async () => {
|
||||
// 前两轮正撞进程替换窗口(降级桥),第三轮桥就绪
|
||||
seen.push(seen.length < 2 ? 'bridge' : 'ok')
|
||||
return seen.length <= 2 ? 'bridge' : 'ok'
|
||||
}, { sleep: noWait })
|
||||
assert.equal(result.attempts, 3, `桥起来后应在第 3 轮恢复,实际跑了 ${result.attempts} 轮`)
|
||||
assert.equal(result.attempt, 'ok')
|
||||
assert.equal(result.cancelled, false)
|
||||
})
|
||||
|
||||
test('一直失败就到上限为止,不许无限重试打爆桥', async () => {
|
||||
let calls = 0
|
||||
const result = await runBridgeListFirstLoad(async () => {
|
||||
calls += 1
|
||||
return 'failed'
|
||||
}, { sleep: noWait })
|
||||
assert.equal(calls, BRIDGE_LIST_FIRST_LOAD_MAX_ATTEMPTS)
|
||||
assert.equal(result.attempts, BRIDGE_LIST_FIRST_LOAD_MAX_ATTEMPTS)
|
||||
assert.equal(result.attempt, 'failed')
|
||||
})
|
||||
|
||||
test('组件卸载即停链,且不把「已取消」说成「取不到」', async () => {
|
||||
let calls = 0
|
||||
const result = await runBridgeListFirstLoad(async () => {
|
||||
calls += 1
|
||||
return 'bridge'
|
||||
}, { sleep: noWait, isCancelled: () => calls > 0 })
|
||||
assert.equal(calls, 1, '卸载后不得再发起下一轮取回')
|
||||
assert.equal(result.cancelled, true)
|
||||
})
|
||||
|
||||
test('每一种失败都有用户可见文案,成功不许带文案', () => {
|
||||
for (const attempt of ['bridge', 'uid', 'failed'] as const) {
|
||||
assert.ok(bridgeListHint(attempt).trim(), `${attempt} 没有可见文案,会退化成「暂无任务」`)
|
||||
assert.equal(isRetryableBridgeListAttempt(attempt), true, `${attempt} 必须可重试`)
|
||||
}
|
||||
assert.equal(bridgeListHint('ok'), '')
|
||||
assert.equal(isRetryableBridgeListAttempt('ok'), false)
|
||||
})
|
||||
|
||||
test('退避曲线复用任务轮询那一套,单调且封顶不失控', () => {
|
||||
const delays = [1, 2, 3, 4, 5, 6, 7, 8].map(bridgeListRetryDelayMs)
|
||||
for (let i = 1; i < delays.length; i += 1) {
|
||||
assert.ok(delays[i] >= delays[i - 1], `第 ${i + 1} 轮退避比上一轮短:${delays}`)
|
||||
assert.ok(delays[i] <= 10_000, `退避超过 10s:${delays}`)
|
||||
}
|
||||
})
|
||||
|
||||
test('变体采集页不再把「桥没起来」画成「暂无任务」', () => {
|
||||
const source = sourceOf(VARIANT)
|
||||
assert.ok(source.includes('runBridgeListFirstLoad'), `${VARIANT} 没接首拉重试驱动`)
|
||||
assert.ok(source.includes('bridgeListHint'), `${VARIANT} 没把失败文案呈现给用户`)
|
||||
// 三条无出口 return:撞上了既不重试也不告诉用户,就是这个 bug 的本体
|
||||
assert.ok(!/if \(!bridge\?\.vc_list_tasks\) return/.test(source),
|
||||
'桥未就绪仍被静默 return,重载后列表会永久空')
|
||||
assert.ok(!/if \(!uid\(\)\) return/.test(source),
|
||||
'登录态缺失仍被静默 return')
|
||||
assert.match(source, /async function bootstrapListLoad\(\)[\s\S]*?runBridgeListFirstLoad\(\(\) => loadTasks\(1\)/,
|
||||
'首拉必须走重试驱动,而不是裸发一次')
|
||||
assert.match(source, /onMounted\(\(\) => \{[\s\S]*?void bootstrapListLoad\(\)/,
|
||||
'onMounted 必须起这条重试链')
|
||||
})
|
||||
|
||||
test('history 拉取失败不得清空列表、更不得据此删本地轮询 id', () => {
|
||||
for (const [rel, name] of [[PRICE_TRACK, '跟价'], [PRODUCT_RISK, '商品风险']] as const) {
|
||||
const source = sourceOf(rel)
|
||||
const loadHistory = source.match(/async function loadHistory\(\)[\s\S]*?\n\}/)
|
||||
assert.ok(loadHistory, `${name}:找不到 loadHistory,接线断言失去对象`)
|
||||
assert.ok(!/historyItems\.value = \[\]/.test(loadHistory[0]),
|
||||
`${name}:拉取失败把列表清空,随后的结算会把在跑的任务判成「已不存在」并删掉本地 id`)
|
||||
const sync = source.match(/function syncPollingIdsWithHistory\(\)[\s\S]*?\n\}/)
|
||||
assert.ok(sync, `${name}:找不到 syncPollingIdsWithHistory,接线断言失去对象`)
|
||||
assert.match(sync[0], /historyLoad(Ok|Failed)/,
|
||||
`${name}:结算必须先确认本轮 history 真拉成功,否则一次抖动就会删光本地轮询 id 与快照`)
|
||||
}
|
||||
})
|
||||
@@ -39,7 +39,13 @@ const BASELINE = {
|
||||
// 拆分是为了 SFC 顶到可读棘轮的 800 行上限(1439 行 > 台账点名的 1318),不是冲静默来的:
|
||||
// 铃铛那两处"有意静默降级"(轮询失败不亮红点、列表失败在面板内给文案)整块搬进了新文件,
|
||||
// 逐文件台账跟着实况走——组件 3→0、新记 useNotificationBellPanel.ts=2,总数还比基线少 1。
|
||||
silent: 83,
|
||||
// 81 = 本轮(更新客户端把在跑的任务列表抹空)修变体采集页时实扫的总数。
|
||||
// 两处各减 1 的来源不同,分开记:
|
||||
// ① BrandVariantTab.vue 的 loadTasks 把「桥未注入/无 uid/请求失败」四条无出口 return 与
|
||||
// 那句空 catch 换成可见状态 + 首拉重试,静默 2→1(台账跟着改);
|
||||
// ② 基线此前停在 83,而改动前实扫是 82——上一轮减下去没缩台账,本轮一并拉平到实扫值。
|
||||
// blocks 一格没动:本轮没有新增 try/catch,只是给既有 catch 补了出口。
|
||||
silent: 81,
|
||||
/** 逐文件台账:只钉总数与文件数两个标量的棘轮,会被「A 加一条 + B 减一条」整段绕过。 */
|
||||
perFile: {
|
||||
'src/pages/brand/components/BrandCollectDataTab.vue': 4,
|
||||
@@ -53,7 +59,7 @@ const BASELINE = {
|
||||
'src/pages/brand/components/BrandShopMatchTab.vue': 1,
|
||||
'src/pages/brand/components/BrandSimilarAsinTab.vue': 1,
|
||||
'src/pages/brand/components/BrandSplitTab.vue': 1,
|
||||
'src/pages/brand/components/BrandVariantTab.vue': 2,
|
||||
'src/pages/brand/components/BrandVariantTab.vue': 1,
|
||||
'src/pages/home/DesktopHomePage.vue': 1,
|
||||
'src/pages/image-video/components/DeliveryVideoWorkspace.vue': 1,
|
||||
'src/pages/login/DesktopLoginPage.vue': 12,
|
||||
|
||||
Reference in New Issue
Block a user