mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-23 23:19:19 +08:00
feat: 抽出sse实时连接服务,导入进度和同步进度共用公共sse连接
This commit is contained in:
+56
@@ -0,0 +1,56 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.service;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.po.PddOrderFullSyncTaskPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.vo.PddOrderFullSyncTaskVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.notify.sse.RealtimeSseEvents;
|
||||
import top.xyquan.ecomdmbbackend.modules.notify.sse.RealtimeSseService;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 全量同步进度推送到公司在线用户的 SSE 通道。
|
||||
*/
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class PddOrderFullSyncProgressPublisher {
|
||||
|
||||
private final RealtimeSseService realtimeSseService;
|
||||
|
||||
public void publish(PddOrderFullSyncTaskPO task) {
|
||||
if (task == null || task.getCompanyId() == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
PddOrderFullSyncTaskVO vo = toVo(task);
|
||||
Map<String, Object> payload = Map.of(
|
||||
"type", RealtimeSseEvents.PDD_ORDER_FULL_SYNC_PROGRESS,
|
||||
"task", vo
|
||||
);
|
||||
realtimeSseService.sendToCompany(
|
||||
task.getCompanyId(),
|
||||
RealtimeSseEvents.PDD_ORDER_FULL_SYNC_PROGRESS,
|
||||
payload);
|
||||
} catch (Exception ignored) {
|
||||
// SSE 失败不影响同步主流程
|
||||
}
|
||||
}
|
||||
|
||||
private static PddOrderFullSyncTaskVO toVo(PddOrderFullSyncTaskPO task) {
|
||||
return PddOrderFullSyncTaskVO.builder()
|
||||
.id(task.getId())
|
||||
.shopId(task.getShopId())
|
||||
.dateFrom(task.getDateFrom())
|
||||
.dateTo(task.getDateTo())
|
||||
.currentDate(task.getCurrentDate())
|
||||
.totalDays(task.getTotalDays())
|
||||
.doneDays(task.getDoneDays())
|
||||
.failedDays(task.getFailedDays())
|
||||
.status(task.getStatus())
|
||||
.lastError(task.getLastError())
|
||||
.createTime(task.getCreateTime())
|
||||
.finishTime(task.getFinishTime())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+8
@@ -20,6 +20,7 @@ public class PddOrderFullSyncTaskExecutor {
|
||||
|
||||
private final PddOrderFullSyncTaskMapper taskMapper;
|
||||
private final PddOrderSyncService pddOrderSyncService;
|
||||
private final PddOrderFullSyncProgressPublisher progressPublisher;
|
||||
|
||||
public void execute(PddSyncFullMessage message) {
|
||||
if (message.getTaskId() != null) {
|
||||
@@ -47,6 +48,7 @@ public class PddOrderFullSyncTaskExecutor {
|
||||
task.setStatus(PddOrderFullSyncTaskPO.STATUS_RUNNING);
|
||||
task.setFinishTime(null);
|
||||
taskMapper.updateById(task);
|
||||
progressPublisher.publish(task);
|
||||
|
||||
// 已成功天数之后的下一自然日(失败日未计入 doneDays,续跑会重试失败日)
|
||||
int done = task.getDoneDays() == null ? 0 : task.getDoneDays();
|
||||
@@ -56,25 +58,30 @@ public class PddOrderFullSyncTaskExecutor {
|
||||
PddOrderFullSyncTaskPO latest = taskMapper.selectById(taskId);
|
||||
if (latest != null && PddOrderFullSyncTaskPO.STATUS_CANCELLED.equals(latest.getStatus())) {
|
||||
log.info("全量同步任务已取消,停止执行 taskId={}", taskId);
|
||||
progressPublisher.publish(latest);
|
||||
return;
|
||||
}
|
||||
task.setCurrentDate(day);
|
||||
task.setStatus(PddOrderFullSyncTaskPO.STATUS_RUNNING);
|
||||
taskMapper.updateById(task);
|
||||
progressPublisher.publish(task);
|
||||
pddOrderSyncService.syncByConfirmDateForTask(
|
||||
task.getCompanyId(), task.getShopId(), day, task.getId());
|
||||
task.setDoneDays((task.getDoneDays() == null ? 0 : task.getDoneDays()) + 1);
|
||||
taskMapper.updateById(task);
|
||||
progressPublisher.publish(task);
|
||||
day = day.plusDays(1);
|
||||
}
|
||||
task.setStatus(PddOrderFullSyncTaskPO.STATUS_SUCCESS);
|
||||
task.setFinishTime(LocalDateTime.now());
|
||||
task.setLastError(null);
|
||||
taskMapper.updateById(task);
|
||||
progressPublisher.publish(task);
|
||||
} catch (Exception e) {
|
||||
log.error("全量同步任务失败 taskId={}", taskId, e);
|
||||
PddOrderFullSyncTaskPO latest = taskMapper.selectById(taskId);
|
||||
if (latest != null && PddOrderFullSyncTaskPO.STATUS_CANCELLED.equals(latest.getStatus())) {
|
||||
progressPublisher.publish(latest);
|
||||
return;
|
||||
}
|
||||
task.setFailedDays((task.getFailedDays() == null ? 0 : task.getFailedDays()) + 1);
|
||||
@@ -83,6 +90,7 @@ public class PddOrderFullSyncTaskExecutor {
|
||||
? e.getMessage().substring(0, 500) : e.getMessage());
|
||||
task.setFinishTime(LocalDateTime.now());
|
||||
taskMapper.updateById(task);
|
||||
progressPublisher.publish(task);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
+4
@@ -54,6 +54,7 @@ public class PddOrderFullSyncTaskService {
|
||||
private final PddOrderSyncPublisher syncPublisher;
|
||||
private final PddOrderSyncProperties syncProperties;
|
||||
private final CurrentUserContext currentUserContext;
|
||||
private final PddOrderFullSyncProgressPublisher progressPublisher;
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public PddOrderFullSyncTaskVO createTask(PddOrderFullSyncTaskCreateDTO dto) {
|
||||
@@ -88,6 +89,7 @@ public class PddOrderFullSyncTaskService {
|
||||
syncPublisher.publishFullTask(
|
||||
task.getId(), task.getCompanyId(), task.getShopId(),
|
||||
task.getDateFrom(), task.getDateTo());
|
||||
progressPublisher.publish(task);
|
||||
return toVo(task);
|
||||
}
|
||||
|
||||
@@ -146,6 +148,7 @@ public class PddOrderFullSyncTaskService {
|
||||
task.setFinishTime(LocalDateTime.now());
|
||||
task.setLastError(null);
|
||||
taskMapper.updateById(task);
|
||||
progressPublisher.publish(task);
|
||||
return toVo(task);
|
||||
}
|
||||
|
||||
@@ -170,6 +173,7 @@ public class PddOrderFullSyncTaskService {
|
||||
syncPublisher.publishFullTask(
|
||||
task.getId(), task.getCompanyId(), task.getShopId(),
|
||||
task.getDateFrom(), task.getDateTo());
|
||||
progressPublisher.publish(task);
|
||||
return toVo(task);
|
||||
}
|
||||
|
||||
|
||||
-43
@@ -1,43 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.importtask.controller;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.importtask.service.SseNotificationService;
|
||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||
|
||||
/**
|
||||
* 导入任务SSE控制器
|
||||
*/
|
||||
@Tag(name = "电商-导入任务SSE", description = "导入任务实时进度推送接口")
|
||||
@RestController
|
||||
@RequestMapping("/api/ec/import-task/sse")
|
||||
public class ImportTaskSseController {
|
||||
|
||||
private final SseNotificationService sseNotificationService;
|
||||
private final CurrentUserContext currentUserContext;
|
||||
|
||||
public ImportTaskSseController(SseNotificationService sseNotificationService,
|
||||
CurrentUserContext currentUserContext) {
|
||||
this.sseNotificationService = sseNotificationService;
|
||||
this.currentUserContext = currentUserContext;
|
||||
}
|
||||
|
||||
@Operation(summary = "建立SSE连接", description = "前端在创建任务前建立SSE连接,用于接收任务进度推送")
|
||||
@GetMapping(value = "/connect", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||
@RequirePermission(value = "data:import", description = "建立SSE连接", allowSuper = true)
|
||||
public SseEmitter connect(
|
||||
@RequestParam(value = "deviceId", required = false) String deviceId) {
|
||||
Long userId = currentUserContext.getCurrentUserId();
|
||||
if (deviceId == null || deviceId.trim().isEmpty()) {
|
||||
return sseNotificationService.createConnection(userId);
|
||||
}
|
||||
return sseNotificationService.createConnection(userId, deviceId.trim());
|
||||
}
|
||||
}
|
||||
-57
@@ -1,57 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.importtask.service;
|
||||
|
||||
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.importtask.model.vo.ImportTaskVO;
|
||||
|
||||
/**
|
||||
* SSE通知服务接口
|
||||
*/
|
||||
public interface SseNotificationService {
|
||||
|
||||
/**
|
||||
* 创建SSE连接(兼容旧调用,无设备标识)
|
||||
*
|
||||
* @param userId 用户ID
|
||||
* @return SSE发射器
|
||||
*/
|
||||
SseEmitter createConnection(Long userId);
|
||||
|
||||
/**
|
||||
* 创建SSE连接(多设备版本)
|
||||
*
|
||||
* @param userId 用户ID
|
||||
* @param deviceId 设备/标签页标识(用于多设备去重)
|
||||
* @return SSE发射器
|
||||
*/
|
||||
SseEmitter createConnection(Long userId, String deviceId);
|
||||
|
||||
/**
|
||||
* 发送任务进度通知
|
||||
*
|
||||
* @param userId 用户ID
|
||||
* @param taskVO 导入任务VO(完整信息)
|
||||
*/
|
||||
void sendTaskProgress(Long userId, ImportTaskVO taskVO);
|
||||
|
||||
/**
|
||||
* 关闭用户的SSE连接
|
||||
*
|
||||
* @param userId 用户ID
|
||||
*/
|
||||
void closeConnection(Long userId);
|
||||
|
||||
/**
|
||||
* 检查用户是否有活跃的任务
|
||||
*
|
||||
* @param userId 用户ID
|
||||
* @return 是否有活跃任务
|
||||
*/
|
||||
boolean hasActiveTasks(Long userId);
|
||||
|
||||
/**
|
||||
* 通知所有任务已完成,可以关闭连接
|
||||
*
|
||||
* @param userId 用户ID
|
||||
*/
|
||||
void notifyAllTasksCompleted(Long userId);
|
||||
}
|
||||
+28
-5
@@ -12,7 +12,8 @@ import top.xyquan.ecomdmbbackend.modules.ec.importtask.model.po.ImportTaskPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.importtask.model.vo.ImportTaskVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.importtask.service.ImportTaskProcessorService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.importtask.service.ImportTaskService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.importtask.service.SseNotificationService;
|
||||
import top.xyquan.ecomdmbbackend.modules.notify.sse.RealtimeSseEvents;
|
||||
import top.xyquan.ecomdmbbackend.modules.notify.sse.RealtimeSseService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.mapper.OrderItemMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.mapper.OrderMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.mapper.ProductMapper;
|
||||
@@ -49,7 +50,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
|
||||
|
||||
private final ImportTaskService importTaskService;
|
||||
private final OrderMapper orderMapper;
|
||||
private final SseNotificationService sseNotificationService;
|
||||
private final RealtimeSseService realtimeSseService;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final OssService ossService;
|
||||
private final SysFileService sysFileService;
|
||||
@@ -66,7 +67,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
|
||||
OrderItemMapper orderItemMapper,
|
||||
ProductMapper productMapper,
|
||||
ShopProductRelationMapper shopProductRelationMapper,
|
||||
SseNotificationService sseNotificationService,
|
||||
RealtimeSseService realtimeSseService,
|
||||
ObjectMapper objectMapper,
|
||||
SqlSessionFactory sqlSessionFactory,
|
||||
OssService ossService,
|
||||
@@ -76,7 +77,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
|
||||
this.importTaskService = importTaskService;
|
||||
this.licenseFeatureGuard = licenseFeatureGuard;
|
||||
this.orderMapper = orderMapper;
|
||||
this.sseNotificationService = sseNotificationService;
|
||||
this.realtimeSseService = realtimeSseService;
|
||||
this.objectMapper = objectMapper;
|
||||
this.ossService = ossService;
|
||||
this.sysFileService = sysFileService;
|
||||
@@ -369,12 +370,34 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
|
||||
private void notifyTaskProgress(Long userId, ImportTaskVO taskVO) {
|
||||
if (userId == null || taskVO == null) return;
|
||||
try {
|
||||
sseNotificationService.sendTaskProgress(userId, taskVO);
|
||||
Map<String, Object> payload = Map.of(
|
||||
"type", RealtimeSseEvents.IMPORT_TASK_PROGRESS,
|
||||
"task", taskVO
|
||||
);
|
||||
realtimeSseService.sendToUser(userId, RealtimeSseEvents.IMPORT_TASK_PROGRESS, payload);
|
||||
if ("success".equals(taskVO.getStatus()) || "failed".equals(taskVO.getStatus())) {
|
||||
notifyImportAllCompletedIfIdle(userId);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
// SSE 发送失败不影响主流程
|
||||
}
|
||||
}
|
||||
|
||||
private void notifyImportAllCompletedIfIdle(Long userId) {
|
||||
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ImportTaskPO> wrapper =
|
||||
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
|
||||
wrapper.eq(ImportTaskPO::getCreateBy, userId)
|
||||
.in(ImportTaskPO::getStatus, "pending", "processing");
|
||||
if (importTaskService.count(wrapper) > 0) {
|
||||
return;
|
||||
}
|
||||
Map<String, Object> payload = Map.of(
|
||||
"type", RealtimeSseEvents.IMPORT_ALL_TASKS_COMPLETED,
|
||||
"message", "所有任务已完成"
|
||||
);
|
||||
realtimeSseService.sendToUser(userId, RealtimeSseEvents.IMPORT_ALL_TASKS_COMPLETED, payload);
|
||||
}
|
||||
|
||||
private ImportTaskVO convertToVO(ImportTaskPO importTaskPO) {
|
||||
if (importTaskPO == null) return null;
|
||||
ImportTaskVO vo = new ImportTaskVO();
|
||||
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.notify.sse;
|
||||
|
||||
/**
|
||||
* 用户级 SSE 事件名(与前端 EventSource.addEventListener 对齐)
|
||||
*/
|
||||
public final class RealtimeSseEvents {
|
||||
|
||||
private RealtimeSseEvents() {
|
||||
}
|
||||
|
||||
/** 连接建立 */
|
||||
public static final String CONNECTED = "message";
|
||||
|
||||
/** 心跳 */
|
||||
public static final String PING = "ping";
|
||||
|
||||
/** 导入任务进度 */
|
||||
public static final String IMPORT_TASK_PROGRESS = "import_task_progress";
|
||||
|
||||
/** 导入任务全部结束(可刷新列表) */
|
||||
public static final String IMPORT_ALL_TASKS_COMPLETED = "import_all_tasks_completed";
|
||||
|
||||
/** 拼多多订单全量同步任务进度 */
|
||||
public static final String PDD_ORDER_FULL_SYNC_PROGRESS = "pdd_order_full_sync_progress";
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.notify.sse;
|
||||
|
||||
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||
|
||||
/**
|
||||
* 用户级实时推送(单用户多设备/多标签页)
|
||||
*/
|
||||
public interface RealtimeSseService {
|
||||
|
||||
/**
|
||||
* 建立连接
|
||||
*
|
||||
* @param userId 用户 ID
|
||||
* @param companyId 当前公司 ID(可为 null)
|
||||
* @param deviceId 设备/标签页标识
|
||||
*/
|
||||
SseEmitter createConnection(Long userId, Long companyId, String deviceId);
|
||||
|
||||
/**
|
||||
* 推送给指定用户的全部设备连接
|
||||
*/
|
||||
void sendToUser(Long userId, String eventName, Object payload);
|
||||
|
||||
/**
|
||||
* 推送给指定公司下当前在线的全部用户连接
|
||||
*/
|
||||
void sendToCompany(Long companyId, String eventName, Object payload);
|
||||
|
||||
/**
|
||||
* 关闭用户全部连接
|
||||
*/
|
||||
void closeUserConnections(Long userId);
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.notify.sse.controller;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||
import top.xyquan.ecomdmbbackend.modules.notify.sse.RealtimeSseService;
|
||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||
|
||||
/**
|
||||
* 用户级实时通道:登录即可连接,业务事件按类型分发。
|
||||
*/
|
||||
@Tag(name = "实时通知SSE", description = "用户级实时推送(导入/同步等)")
|
||||
@RestController
|
||||
@RequestMapping("/api/notify/sse")
|
||||
public class RealtimeSseController {
|
||||
|
||||
private final RealtimeSseService realtimeSseService;
|
||||
private final CurrentUserContext currentUserContext;
|
||||
|
||||
public RealtimeSseController(RealtimeSseService realtimeSseService,
|
||||
CurrentUserContext currentUserContext) {
|
||||
this.realtimeSseService = realtimeSseService;
|
||||
this.currentUserContext = currentUserContext;
|
||||
}
|
||||
|
||||
@Operation(summary = "建立SSE连接", description = "登录后建立用户级 SSE;支持多设备/多标签页(deviceId)")
|
||||
@GetMapping(value = "/connect", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||
public SseEmitter connect(
|
||||
@RequestParam(value = "deviceId", required = false) String deviceId) {
|
||||
Long userId = currentUserContext.getCurrentUserId();
|
||||
Long companyId = null;
|
||||
try {
|
||||
companyId = currentUserContext.getCurrentCompanyId();
|
||||
} catch (Exception ignored) {
|
||||
// 超管等无公司上下文时仍可连接,仅收用户级事件
|
||||
}
|
||||
return realtimeSseService.createConnection(userId, companyId, deviceId);
|
||||
}
|
||||
}
|
||||
+150
-210
@@ -1,4 +1,4 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.importtask.service.impl;
|
||||
package top.xyquan.ecomdmbbackend.modules.notify.sse.impl;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.slf4j.Logger;
|
||||
@@ -6,103 +6,76 @@ import org.slf4j.LoggerFactory;
|
||||
import org.springframework.lang.NonNull;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.importtask.model.po.ImportTaskPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.importtask.model.vo.ImportTaskVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.importtask.service.ImportTaskService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.importtask.service.SseNotificationService;
|
||||
import top.xyquan.ecomdmbbackend.modules.notify.sse.RealtimeSseEvents;
|
||||
import top.xyquan.ecomdmbbackend.modules.notify.sse.RealtimeSseService;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.ScheduledThreadPoolExecutor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* SSE通知服务实现类(多设备版本)
|
||||
*
|
||||
* 架构:Map(userId → List(EmitterWithDevice))
|
||||
* - 一个用户可有多个设备/标签页同时连接
|
||||
* - deviceId 去重:新连接同 deviceId 则关掉旧连接
|
||||
* - 单用户最大连接数:10(超出则踢最旧的)
|
||||
* 用户级 SSE:Map(userId → List(device)),同 deviceId 去重,单用户最多 10 路。
|
||||
*/
|
||||
@Service
|
||||
public class SseNotificationServiceImpl implements SseNotificationService {
|
||||
public class RealtimeSseServiceImpl implements RealtimeSseService {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(SseNotificationServiceImpl.class);
|
||||
private static final Logger logger = LoggerFactory.getLogger(RealtimeSseServiceImpl.class);
|
||||
|
||||
/** 单用户最大设备连接数 */
|
||||
private static final int MAX_DEVICES_PER_USER = 10;
|
||||
|
||||
/** SSE 超时时间:30 分钟 */
|
||||
private static final long SSE_TIMEOUT_MS = 30 * 60 * 1000L;
|
||||
|
||||
/** 心跳间隔:15 秒 */
|
||||
private static final long HEARTBEAT_INTERVAL_SECONDS = 15;
|
||||
|
||||
/** 设备元数据包装器 */
|
||||
private static class EmitterEntry {
|
||||
final String deviceId;
|
||||
final Long companyId;
|
||||
final SseEmitter emitter;
|
||||
long lastHeartbeat;
|
||||
|
||||
EmitterEntry(String deviceId, SseEmitter emitter) {
|
||||
EmitterEntry(String deviceId, Long companyId, SseEmitter emitter) {
|
||||
this.deviceId = deviceId;
|
||||
this.companyId = companyId;
|
||||
this.emitter = emitter;
|
||||
this.lastHeartbeat = System.currentTimeMillis();
|
||||
}
|
||||
}
|
||||
|
||||
/** userId → 该用户的所有设备连接 */
|
||||
private final Map<Long, List<EmitterEntry>> userConnections = new ConcurrentHashMap<>();
|
||||
/** userId → 心跳定时任务 */
|
||||
private final Map<Long, ScheduledFuture<?>> heartbeatTasks = new ConcurrentHashMap<>();
|
||||
|
||||
private final ImportTaskService importTaskService;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final ScheduledExecutorService scheduler;
|
||||
|
||||
public SseNotificationServiceImpl(ImportTaskService importTaskService, ObjectMapper objectMapper) {
|
||||
this.importTaskService = importTaskService;
|
||||
public RealtimeSseServiceImpl(ObjectMapper objectMapper) {
|
||||
this.objectMapper = objectMapper;
|
||||
this.scheduler = new ScheduledThreadPoolExecutor(2, r -> {
|
||||
Thread t = new Thread(r, "sse-heartbeat");
|
||||
Thread t = new Thread(r, "realtime-sse-heartbeat");
|
||||
t.setDaemon(true);
|
||||
return t;
|
||||
});
|
||||
}
|
||||
|
||||
// ==================== 连接管理 ====================
|
||||
|
||||
/**
|
||||
* 兼容旧调用:自动生成匿名 deviceId
|
||||
*/
|
||||
@Override
|
||||
public SseEmitter createConnection(Long userId) {
|
||||
return createConnection(userId, "device-" + System.nanoTime());
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建/重建 SSE 连接(多设备版本)
|
||||
*
|
||||
* @param userId 用户ID
|
||||
* @param deviceId 设备标识(标签页 UUID)
|
||||
*/
|
||||
@Override
|
||||
public SseEmitter createConnection(Long userId, String deviceId) {
|
||||
logger.info("创建SSE连接,userId={}, deviceId={}", userId, deviceId);
|
||||
public SseEmitter createConnection(Long userId, Long companyId, String deviceId) {
|
||||
String resolvedDeviceId = (deviceId == null || deviceId.isBlank())
|
||||
? "device-" + System.nanoTime()
|
||||
: deviceId.trim();
|
||||
logger.info("创建SSE连接,userId={}, companyId={}, deviceId={}", userId, companyId, resolvedDeviceId);
|
||||
|
||||
List<EmitterEntry> entries = userConnections.computeIfAbsent(userId, k -> new ArrayList<>());
|
||||
|
||||
// 1. deviceId 去重:同设备的新连接覆盖旧的
|
||||
EmitterEntry existingEntry = findEntry(entries, deviceId);
|
||||
if (existingEntry != null) {
|
||||
logger.info("设备已存在连接,关闭旧连接,deviceId={}", deviceId);
|
||||
safeComplete(existingEntry.emitter);
|
||||
entries.remove(existingEntry);
|
||||
EmitterEntry existing = findEntry(entries, resolvedDeviceId);
|
||||
if (existing != null) {
|
||||
logger.info("设备已存在连接,关闭旧连接,deviceId={}", resolvedDeviceId);
|
||||
safeComplete(existing.emitter);
|
||||
entries.remove(existing);
|
||||
}
|
||||
|
||||
// 2. 超出上限,移除最旧的连接
|
||||
if (entries.size() >= MAX_DEVICES_PER_USER) {
|
||||
EmitterEntry oldest = entries.stream()
|
||||
.min((a, b) -> Long.compare(a.lastHeartbeat, b.lastHeartbeat))
|
||||
@@ -114,37 +87,110 @@ public class SseNotificationServiceImpl implements SseNotificationService {
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 创建新 emitter
|
||||
SseEmitter emitter = new SseEmitter(SSE_TIMEOUT_MS);
|
||||
EmitterEntry newEntry = new EmitterEntry(deviceId, emitter);
|
||||
EmitterEntry newEntry = new EmitterEntry(resolvedDeviceId, companyId, emitter);
|
||||
entries.add(newEntry);
|
||||
registerCallbacks(userId, resolvedDeviceId, entries, emitter, newEntry);
|
||||
|
||||
// 4. 注册回调
|
||||
registerCallbacks(userId, deviceId, entries, emitter, newEntry);
|
||||
|
||||
// 5. 发送初始消息
|
||||
try {
|
||||
Map<String, Object> msg = Map.of(
|
||||
"type", "connected",
|
||||
"message", "SSE连接已建立",
|
||||
"deviceId", deviceId
|
||||
"deviceId", resolvedDeviceId
|
||||
);
|
||||
emitter.send(SseEmitter.event()
|
||||
.name("message")
|
||||
.name(RealtimeSseEvents.CONNECTED)
|
||||
.data(Objects.requireNonNull(serializeForSse(msg))));
|
||||
// 建连线程立刻发一帧 ping,避免只靠调度器导致首包延迟/丢包被前端误判超时
|
||||
Map<String, Object> pingMsg = Map.of(
|
||||
"type", "ping",
|
||||
"timestamp", System.currentTimeMillis()
|
||||
);
|
||||
emitter.send(SseEmitter.event()
|
||||
.name(RealtimeSseEvents.PING)
|
||||
.data(Objects.requireNonNull(serializeForSse(pingMsg))));
|
||||
newEntry.lastHeartbeat = System.currentTimeMillis();
|
||||
} catch (IOException e) {
|
||||
logger.error("发送初始SSE消息失败,userId={}, deviceId={}", userId, deviceId, e);
|
||||
logger.error("发送初始SSE消息失败,userId={}, deviceId={}", userId, resolvedDeviceId, e);
|
||||
entries.remove(newEntry);
|
||||
safeComplete(emitter);
|
||||
return emitter;
|
||||
}
|
||||
|
||||
// 6. 启动/重启心跳
|
||||
ensureHeartbeatRunning(userId);
|
||||
|
||||
return emitter;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendToUser(Long userId, String eventName, Object payload) {
|
||||
if (userId == null) {
|
||||
return;
|
||||
}
|
||||
List<EmitterEntry> entries = userConnections.get(userId);
|
||||
if (entries == null || entries.isEmpty()) {
|
||||
logger.debug("用户没有SSE连接,userId={}", userId);
|
||||
return;
|
||||
}
|
||||
broadcast(userId, entries, eventName, payload);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendToCompany(Long companyId, String eventName, Object payload) {
|
||||
if (companyId == null) {
|
||||
return;
|
||||
}
|
||||
for (Map.Entry<Long, List<EmitterEntry>> e : userConnections.entrySet()) {
|
||||
Long userId = e.getKey();
|
||||
List<EmitterEntry> companyEntries = new ArrayList<>();
|
||||
for (EmitterEntry entry : e.getValue()) {
|
||||
if (companyId.equals(entry.companyId)) {
|
||||
companyEntries.add(entry);
|
||||
}
|
||||
}
|
||||
if (!companyEntries.isEmpty()) {
|
||||
broadcast(userId, companyEntries, eventName, payload);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void closeUserConnections(Long userId) {
|
||||
List<EmitterEntry> entries = userConnections.remove(userId);
|
||||
ScheduledFuture<?> task = heartbeatTasks.remove(userId);
|
||||
if (task != null) {
|
||||
task.cancel(false);
|
||||
}
|
||||
if (entries != null) {
|
||||
for (EmitterEntry e : entries) {
|
||||
safeComplete(e.emitter);
|
||||
}
|
||||
}
|
||||
logger.info("关闭用户所有SSE连接,userId={}", userId);
|
||||
}
|
||||
|
||||
private void broadcast(Long userId, List<EmitterEntry> entries, String eventName, Object payload) {
|
||||
List<EmitterEntry> deadEntries = new ArrayList<>();
|
||||
String data;
|
||||
try {
|
||||
data = serializeForSse(payload);
|
||||
} catch (IOException ex) {
|
||||
logger.warn("SSE载荷序列化失败,userId={}, event={}", userId, eventName, ex);
|
||||
return;
|
||||
}
|
||||
|
||||
for (EmitterEntry entry : entries) {
|
||||
try {
|
||||
entry.emitter.send(SseEmitter.event()
|
||||
.name(eventName)
|
||||
.data(Objects.requireNonNull(data)));
|
||||
} catch (IOException ex) {
|
||||
logger.debug("SSE发送失败,移除连接,userId={}, deviceId={}", userId, entry.deviceId);
|
||||
deadEntries.add(entry);
|
||||
}
|
||||
}
|
||||
handleDeadEntries(userId, deadEntries);
|
||||
}
|
||||
|
||||
private void registerCallbacks(Long userId, String deviceId,
|
||||
List<EmitterEntry> entries,
|
||||
SseEmitter emitter, EmitterEntry entry) {
|
||||
@@ -153,16 +199,16 @@ public class SseNotificationServiceImpl implements SseNotificationService {
|
||||
entries.remove(entry);
|
||||
cleanupIfEmpty(userId, entries);
|
||||
});
|
||||
|
||||
emitter.onTimeout(() -> {
|
||||
logger.info("SSE连接超时,userId={}, deviceId={}", userId, deviceId);
|
||||
entries.remove(entry);
|
||||
safeComplete(emitter);
|
||||
cleanupIfEmpty(userId, entries);
|
||||
});
|
||||
|
||||
emitter.onError((ex) -> {
|
||||
logger.error("SSE连接错误,userId={}, deviceId={}", userId, deviceId, ex);
|
||||
// 客户端断开时常见,避免刷 ERROR(尤其 AccessDenied + response committed)
|
||||
logger.debug("SSE连接错误,userId={}, deviceId={}, err={}",
|
||||
userId, deviceId, ex != null ? ex.getMessage() : null);
|
||||
entries.remove(entry);
|
||||
safeComplete(emitter);
|
||||
cleanupIfEmpty(userId, entries);
|
||||
@@ -173,68 +219,70 @@ public class SseNotificationServiceImpl implements SseNotificationService {
|
||||
if (entries.isEmpty()) {
|
||||
userConnections.remove(userId);
|
||||
ScheduledFuture<?> task = heartbeatTasks.remove(userId);
|
||||
if (task != null) task.cancel(false);
|
||||
if (task != null) {
|
||||
task.cancel(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private EmitterEntry findEntry(List<EmitterEntry> entries, String deviceId) {
|
||||
for (EmitterEntry e : entries) {
|
||||
if (e.deviceId.equals(deviceId)) return e;
|
||||
if (e.deviceId.equals(deviceId)) {
|
||||
return e;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void safeComplete(SseEmitter emitter) {
|
||||
if (emitter != null) {
|
||||
try {
|
||||
emitter.complete();
|
||||
} catch (Exception ignored) {}
|
||||
if (emitter == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
emitter.complete();
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== 心跳 ====================
|
||||
|
||||
private void ensureHeartbeatRunning(Long userId) {
|
||||
// 已有任务就复用
|
||||
if (heartbeatTasks.containsKey(userId)) {
|
||||
return;
|
||||
}
|
||||
List<EmitterEntry> entries = userConnections.get(userId);
|
||||
if (entries == null || entries.isEmpty()) return;
|
||||
|
||||
// initialDelay=0:连接建立后尽快发首帧 ping,避免客户端在「首 ping 前」用短窗口误判超时
|
||||
if (entries == null || entries.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
// 首包已在建连时发送;周期心跳从 interval 后开始
|
||||
ScheduledFuture<?> task = scheduler.scheduleAtFixedRate(
|
||||
() -> heartbeatForUser(userId),
|
||||
0,
|
||||
HEARTBEAT_INTERVAL_SECONDS,
|
||||
HEARTBEAT_INTERVAL_SECONDS,
|
||||
TimeUnit.SECONDS
|
||||
);
|
||||
heartbeatTasks.put(userId, task);
|
||||
ScheduledFuture<?> prev = heartbeatTasks.putIfAbsent(userId, task);
|
||||
if (prev != null) {
|
||||
task.cancel(false);
|
||||
}
|
||||
}
|
||||
|
||||
private void heartbeatForUser(Long userId) {
|
||||
List<EmitterEntry> entries = userConnections.get(userId);
|
||||
if (entries == null || entries.isEmpty()) {
|
||||
ScheduledFuture<?> t = heartbeatTasks.remove(userId);
|
||||
if (t != null) t.cancel(false);
|
||||
if (t != null) {
|
||||
t.cancel(false);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
Map<String, Object> pingMsg = Map.of(
|
||||
"type", "ping",
|
||||
"timestamp", System.currentTimeMillis()
|
||||
);
|
||||
List<EmitterEntry> deadEntries = new ArrayList<>();
|
||||
Map<String, Object> pingMsg;
|
||||
try {
|
||||
pingMsg = Map.of(
|
||||
"type", "ping",
|
||||
"timestamp", System.currentTimeMillis()
|
||||
);
|
||||
} catch (Exception e) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (EmitterEntry entry : entries) {
|
||||
try {
|
||||
entry.emitter.send(SseEmitter.event()
|
||||
.name("ping")
|
||||
.name(RealtimeSseEvents.PING)
|
||||
.data(Objects.requireNonNull(serializeForSse(pingMsg))));
|
||||
entry.lastHeartbeat = System.currentTimeMillis();
|
||||
} catch (IOException e) {
|
||||
@@ -242,63 +290,17 @@ public class SseNotificationServiceImpl implements SseNotificationService {
|
||||
deadEntries.add(entry);
|
||||
}
|
||||
}
|
||||
|
||||
// 移除失效连接
|
||||
if (!deadEntries.isEmpty()) {
|
||||
entries.removeAll(deadEntries);
|
||||
for (EmitterEntry de : deadEntries) {
|
||||
safeComplete(de.emitter);
|
||||
}
|
||||
if (entries.isEmpty()) {
|
||||
userConnections.remove(userId);
|
||||
ScheduledFuture<?> t = heartbeatTasks.remove(userId);
|
||||
if (t != null) t.cancel(false);
|
||||
}
|
||||
}
|
||||
handleDeadEntries(userId, deadEntries);
|
||||
}
|
||||
|
||||
// ==================== 发送消息 ====================
|
||||
|
||||
@Override
|
||||
public void sendTaskProgress(Long userId, ImportTaskVO taskVO) {
|
||||
private void handleDeadEntries(Long userId, List<EmitterEntry> deadEntries) {
|
||||
if (deadEntries.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
List<EmitterEntry> entries = userConnections.get(userId);
|
||||
if (entries == null || entries.isEmpty()) {
|
||||
logger.debug("用户没有SSE连接,userId={}", userId);
|
||||
if (entries == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
List<EmitterEntry> deadEntries = new ArrayList<>();
|
||||
Map<String, Object> progressMsg;
|
||||
try {
|
||||
progressMsg = Map.of(
|
||||
"type", "task_progress",
|
||||
"task", taskVO
|
||||
);
|
||||
} catch (Exception e) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (EmitterEntry entry : entries) {
|
||||
try {
|
||||
entry.emitter.send(SseEmitter.event()
|
||||
.name("task_progress")
|
||||
.data(Objects.requireNonNull(serializeForSse(progressMsg))));
|
||||
} catch (IOException e) {
|
||||
logger.debug("发送任务进度失败,移除连接,userId={}, deviceId={}", userId, entry.deviceId);
|
||||
deadEntries.add(entry);
|
||||
}
|
||||
}
|
||||
|
||||
handleDeadEntries(userId, entries, deadEntries);
|
||||
|
||||
// 任务完成时,检查是否所有任务都结束了
|
||||
if ("success".equals(taskVO.getStatus()) || "failed".equals(taskVO.getStatus())) {
|
||||
checkAndNotifyAllTasksCompleted(userId);
|
||||
}
|
||||
}
|
||||
|
||||
private void handleDeadEntries(Long userId, List<EmitterEntry> entries, List<EmitterEntry> deadEntries) {
|
||||
if (deadEntries.isEmpty()) return;
|
||||
entries.removeAll(deadEntries);
|
||||
for (EmitterEntry de : deadEntries) {
|
||||
safeComplete(de.emitter);
|
||||
@@ -306,75 +308,13 @@ public class SseNotificationServiceImpl implements SseNotificationService {
|
||||
if (entries.isEmpty()) {
|
||||
userConnections.remove(userId);
|
||||
ScheduledFuture<?> t = heartbeatTasks.remove(userId);
|
||||
if (t != null) t.cancel(false);
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== 批量通知 ====================
|
||||
|
||||
@Override
|
||||
public void notifyAllTasksCompleted(Long userId) {
|
||||
List<EmitterEntry> entries = userConnections.get(userId);
|
||||
if (entries == null || entries.isEmpty()) return;
|
||||
|
||||
Map<String, Object> msg;
|
||||
try {
|
||||
msg = Map.of(
|
||||
"type", "all_tasks_completed",
|
||||
"message", "所有任务已完成"
|
||||
);
|
||||
} catch (Exception e) {
|
||||
return;
|
||||
}
|
||||
|
||||
List<EmitterEntry> deadEntries = new ArrayList<>();
|
||||
for (EmitterEntry entry : entries) {
|
||||
try {
|
||||
entry.emitter.send(SseEmitter.event()
|
||||
.name("all_tasks_completed")
|
||||
.data(Objects.requireNonNull(serializeForSse(msg))));
|
||||
} catch (IOException e) {
|
||||
deadEntries.add(entry);
|
||||
if (t != null) {
|
||||
t.cancel(false);
|
||||
}
|
||||
}
|
||||
handleDeadEntries(userId, entries, deadEntries);
|
||||
logger.info("通知所有任务已完成,userId={}", userId);
|
||||
}
|
||||
|
||||
private void checkAndNotifyAllTasksCompleted(Long userId) {
|
||||
if (!hasActiveTasks(userId)) {
|
||||
notifyAllTasksCompleted(userId);
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== 关闭连接 ====================
|
||||
|
||||
@Override
|
||||
public void closeConnection(Long userId) {
|
||||
List<EmitterEntry> entries = userConnections.remove(userId);
|
||||
ScheduledFuture<?> task = heartbeatTasks.remove(userId);
|
||||
if (task != null) task.cancel(false);
|
||||
if (entries != null) {
|
||||
for (EmitterEntry e : entries) {
|
||||
safeComplete(e.emitter);
|
||||
}
|
||||
}
|
||||
logger.info("关闭用户所有SSE连接,userId={}", userId);
|
||||
}
|
||||
|
||||
// ==================== 查询 ====================
|
||||
|
||||
/** 序列化 SSE 载荷;@NonNull 满足 IDE 对 SseEmitter.data(@NonNull Object) 的空值分析 */
|
||||
private @NonNull String serializeForSse(Object payload) throws IOException {
|
||||
return Objects.requireNonNull(objectMapper.writeValueAsString(payload));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasActiveTasks(Long userId) {
|
||||
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ImportTaskPO> wrapper =
|
||||
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
|
||||
wrapper.eq(ImportTaskPO::getCreateBy, userId)
|
||||
.in(ImportTaskPO::getStatus, "pending", "processing");
|
||||
return importTaskService.count(wrapper) > 0;
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,10 @@ spring:
|
||||
- optional:classpath:config/channel-pdd.yml
|
||||
jackson:
|
||||
time-zone: Asia/Shanghai
|
||||
mvc:
|
||||
# SSE 长连接:避免默认异步超时把 emitter 掐断(只收到 connected 后反复重连)
|
||||
async:
|
||||
request-timeout: -1
|
||||
# 配置404错误处理 - 注释掉,避免影响Swagger文档访问
|
||||
# mvc:
|
||||
# throw-exception-if-no-handler-found: true
|
||||
|
||||
@@ -2,13 +2,8 @@ import type { ImportTaskDTO, ImportTaskVO } from './types';
|
||||
|
||||
import type { PageQueryDTO, PageResultVO } from '#/types/common';
|
||||
|
||||
import { useAppConfig } from '@vben/hooks';
|
||||
import { useAccessStore } from '@vben/stores';
|
||||
|
||||
import { requestClient } from '#/api/request';
|
||||
|
||||
const { apiURL } = useAppConfig(import.meta.env, import.meta.env.PROD);
|
||||
|
||||
/**
|
||||
* 导入任务管理API
|
||||
*/
|
||||
@@ -36,133 +31,3 @@ export async function getImportTaskPageApi(
|
||||
params,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* SSE连接管理器(使用原生EventSource,支持多设备和 token 刷新重连)
|
||||
*/
|
||||
class SseConnection {
|
||||
private eventSource: EventSource | null = null;
|
||||
private listeners: Map<string, Set<(event: MessageEvent) => void>> =
|
||||
new Map();
|
||||
// EventSource 原生状态常量
|
||||
private readyState: number = EventSource.CLOSED;
|
||||
/** 每个标签页独立 deviceId,重开标签页为新 ID */
|
||||
private deviceId: string;
|
||||
|
||||
constructor() {
|
||||
// 每个 SseConnection 实例独立生成 deviceId
|
||||
// 不存 sessionStorage:同 origin 不同标签页不应共享 ID
|
||||
this.deviceId = crypto.randomUUID
|
||||
? crypto.randomUUID()
|
||||
: `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加事件监听器(需在 connect 之前调用)
|
||||
*/
|
||||
addEventListener(eventType: string, handler: (event: MessageEvent) => void) {
|
||||
if (!this.listeners.has(eventType)) {
|
||||
this.listeners.set(eventType, new Set());
|
||||
}
|
||||
this.listeners.get(eventType)!.add(handler);
|
||||
// 如果 EventSource 已建立,额外绑定一次(防止在 connect 之后调用 listener 漏掉)
|
||||
if (this.eventSource) {
|
||||
this.eventSource.addEventListener(eventType, handler as EventListener);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除事件监听器
|
||||
*/
|
||||
removeEventListener(eventType: string, handler: (event: MessageEvent) => void) {
|
||||
const handlers = this.listeners.get(eventType);
|
||||
if (handlers) {
|
||||
handlers.delete(handler);
|
||||
}
|
||||
if (this.eventSource) {
|
||||
this.eventSource.removeEventListener(eventType, handler as EventListener);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 建立SSE连接
|
||||
* EventSource 原生支持自动重连,无需手动实现
|
||||
*/
|
||||
connect(): void {
|
||||
if (this.eventSource) {
|
||||
this.disconnect();
|
||||
}
|
||||
|
||||
// token 必须由调用方传入(connectSse 在重连前已刷新 token)
|
||||
const accessStore = useAccessStore();
|
||||
const token = accessStore.accessToken;
|
||||
if (!token) {
|
||||
console.error('无法建立SSE连接:token不存在');
|
||||
return;
|
||||
}
|
||||
|
||||
// 加时间戳参数避免浏览器复用/合并同 URL 的 EventSource 连接
|
||||
const ts = Date.now();
|
||||
const url = `${apiURL}/ec/import-task/sse/connect?token=${encodeURIComponent(token)}&deviceId=${encodeURIComponent(this.deviceId)}&t=${ts}`;
|
||||
this.readyState = EventSource.CONNECTING;
|
||||
|
||||
const es = new EventSource(url);
|
||||
this.eventSource = es;
|
||||
|
||||
es.onopen = () => {
|
||||
this.readyState = EventSource.OPEN;
|
||||
};
|
||||
|
||||
es.onerror = (event) => {
|
||||
this.readyState = EventSource.CLOSED;
|
||||
this.dispatchEvent('error', new MessageEvent('error', { data: event }));
|
||||
// EventSource 会自动重连,无需手动处理
|
||||
};
|
||||
|
||||
// 将所有自定义事件类型的 listener 注册到 EventSource 上
|
||||
this.listeners.forEach((handlers, eventType) => {
|
||||
handlers.forEach((handler) => {
|
||||
es.addEventListener(eventType, handler as EventListener);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 断开连接(手动断开后不会自动重连)
|
||||
*/
|
||||
disconnect() {
|
||||
if (this.eventSource) {
|
||||
this.eventSource.close();
|
||||
this.eventSource = null;
|
||||
this.readyState = EventSource.CLOSED;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取连接状态
|
||||
*/
|
||||
getReadyState(): number {
|
||||
return this.readyState;
|
||||
}
|
||||
|
||||
private dispatchEvent(eventType: string, event: MessageEvent) {
|
||||
const handlers = this.listeners.get(eventType);
|
||||
if (handlers) {
|
||||
handlers.forEach((handler) => {
|
||||
try {
|
||||
handler(event);
|
||||
} catch (error) {
|
||||
console.error('事件处理器执行失败:', error);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 建立SSE连接
|
||||
* @returns SseConnection实例
|
||||
*/
|
||||
export function createSseConnection(): SseConnection {
|
||||
return new SseConnection();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
import { useAppConfig } from '@vben/hooks';
|
||||
import { useAccessStore } from '@vben/stores';
|
||||
|
||||
const { apiURL } = useAppConfig(import.meta.env, import.meta.env.PROD);
|
||||
|
||||
const DEVICE_ID_KEY = 'ecom-dmb:realtime-sse-device-id';
|
||||
|
||||
/** SSE 事件名(与后端 RealtimeSseEvents 对齐) */
|
||||
export const RealtimeSseEvent = {
|
||||
CONNECTED: 'message',
|
||||
PING: 'ping',
|
||||
IMPORT_TASK_PROGRESS: 'import_task_progress',
|
||||
IMPORT_ALL_TASKS_COMPLETED: 'import_all_tasks_completed',
|
||||
PDD_ORDER_FULL_SYNC_PROGRESS: 'pdd_order_full_sync_progress',
|
||||
} as const;
|
||||
|
||||
export type RealtimeSseEventName =
|
||||
(typeof RealtimeSseEvent)[keyof typeof RealtimeSseEvent];
|
||||
|
||||
function resolveDeviceId(): string {
|
||||
try {
|
||||
const existing = sessionStorage.getItem(DEVICE_ID_KEY);
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
const id = crypto.randomUUID
|
||||
? crypto.randomUUID()
|
||||
: `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
||||
sessionStorage.setItem(DEVICE_ID_KEY, id);
|
||||
return id;
|
||||
} catch {
|
||||
return crypto.randomUUID
|
||||
? crypto.randomUUID()
|
||||
: `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户级 SSE 连接(同标签页复用 deviceId;多标签页各自独立)
|
||||
*/
|
||||
export class RealtimeSseConnection {
|
||||
private eventSource: EventSource | null = null;
|
||||
private listeners: Map<string, Set<(event: MessageEvent) => void>> =
|
||||
new Map();
|
||||
private readyState: number = EventSource.CLOSED;
|
||||
private deviceId: string;
|
||||
/** 主动断开时忽略后续 error,避免误触发业务重连 */
|
||||
private intentionalClose = false;
|
||||
|
||||
constructor() {
|
||||
this.deviceId = resolveDeviceId();
|
||||
}
|
||||
|
||||
addEventListener(eventType: string, handler: (event: MessageEvent) => void) {
|
||||
if (!this.listeners.has(eventType)) {
|
||||
this.listeners.set(eventType, new Set());
|
||||
}
|
||||
this.listeners.get(eventType)!.add(handler);
|
||||
if (this.eventSource) {
|
||||
this.eventSource.addEventListener(eventType, handler as EventListener);
|
||||
}
|
||||
}
|
||||
|
||||
removeEventListener(
|
||||
eventType: string,
|
||||
handler: (event: MessageEvent) => void,
|
||||
) {
|
||||
const handlers = this.listeners.get(eventType);
|
||||
if (handlers) {
|
||||
handlers.delete(handler);
|
||||
}
|
||||
if (this.eventSource) {
|
||||
this.eventSource.removeEventListener(eventType, handler as EventListener);
|
||||
}
|
||||
}
|
||||
|
||||
connect(): void {
|
||||
if (this.eventSource) {
|
||||
this.disconnect();
|
||||
}
|
||||
|
||||
const accessStore = useAccessStore();
|
||||
const token = accessStore.accessToken;
|
||||
if (!token) {
|
||||
console.error('无法建立SSE连接:token不存在');
|
||||
return;
|
||||
}
|
||||
|
||||
this.intentionalClose = false;
|
||||
const ts = Date.now();
|
||||
const url = `${apiURL}/notify/sse/connect?token=${encodeURIComponent(token)}&deviceId=${encodeURIComponent(this.deviceId)}&t=${ts}`;
|
||||
this.readyState = EventSource.CONNECTING;
|
||||
|
||||
const es = new EventSource(url);
|
||||
this.eventSource = es;
|
||||
|
||||
es.onopen = () => {
|
||||
this.readyState = EventSource.OPEN;
|
||||
};
|
||||
|
||||
es.onerror = () => {
|
||||
// 主动 disconnect 时忽略
|
||||
if (this.intentionalClose) {
|
||||
return;
|
||||
}
|
||||
// EventSource 断线后会用旧 URL(含过期 token)自动重连,这里关掉交给业务层重建
|
||||
try {
|
||||
es.close();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
this.eventSource = null;
|
||||
this.readyState = EventSource.CLOSED;
|
||||
this.dispatchEvent(
|
||||
'error',
|
||||
new MessageEvent('error', { data: { reason: 'stream-closed' } }),
|
||||
);
|
||||
};
|
||||
|
||||
this.listeners.forEach((handlers, eventType) => {
|
||||
handlers.forEach((handler) => {
|
||||
es.addEventListener(eventType, handler as EventListener);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
disconnect() {
|
||||
this.intentionalClose = true;
|
||||
if (this.eventSource) {
|
||||
this.eventSource.close();
|
||||
this.eventSource = null;
|
||||
this.readyState = EventSource.CLOSED;
|
||||
}
|
||||
}
|
||||
|
||||
getReadyState(): number {
|
||||
return this.readyState;
|
||||
}
|
||||
|
||||
getDeviceId(): string {
|
||||
return this.deviceId;
|
||||
}
|
||||
|
||||
private dispatchEvent(eventType: string, event: MessageEvent) {
|
||||
const handlers = this.listeners.get(eventType);
|
||||
if (handlers) {
|
||||
handlers.forEach((handler) => {
|
||||
try {
|
||||
handler(event);
|
||||
} catch (error) {
|
||||
console.error('事件处理器执行失败:', error);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function createRealtimeSseConnection(): RealtimeSseConnection {
|
||||
return new RealtimeSseConnection();
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import type { ImportTaskVO } from '#/api/ecommerce/import-task';
|
||||
|
||||
import { computed, onMounted, onUnmounted, ref, watch } from 'vue';
|
||||
import { computed, onMounted, ref, watch } from 'vue';
|
||||
|
||||
import { useVbenModal } from '@vben/common-ui';
|
||||
|
||||
@@ -89,18 +89,9 @@ function formatTime(time: string): string {
|
||||
return new Date(time).toLocaleString();
|
||||
}
|
||||
|
||||
// 组件挂载时初始化
|
||||
onMounted(() => {
|
||||
importTaskStore.init();
|
||||
});
|
||||
|
||||
// 组件卸载时清理
|
||||
onUnmounted(() => {
|
||||
// 如果没有进行中的任务,断开SSE连接
|
||||
if (!importTaskStore.hasActiveTasks) {
|
||||
importTaskStore.disconnectSse();
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
@@ -19,7 +19,7 @@ import { useAccessStore, useUserStore } from '@vben/stores';
|
||||
import ImportTaskButton from '#/components/ImportTaskButton.vue';
|
||||
import SwitchAccountModal from '#/components/SwitchAccountModal.vue';
|
||||
import SwitchCompanyModal from '#/components/SwitchCompanyModal.vue';
|
||||
import { useAuthStore, useImportTaskStore } from '#/store';
|
||||
import { useAuthStore, useImportTaskStore, useRealtimeStore } from '#/store';
|
||||
import LoginForm from '#/views/_core/authentication/login.vue';
|
||||
|
||||
const router = useRouter();
|
||||
@@ -59,13 +59,15 @@ const userStore = useUserStore();
|
||||
const authStore = useAuthStore();
|
||||
const accessStore = useAccessStore();
|
||||
const importTaskStore = useImportTaskStore();
|
||||
const realtimeStore = useRealtimeStore();
|
||||
const { destroyWatermark, updateWatermark } = useWatermark();
|
||||
const showDot = computed(() =>
|
||||
notifications.value.some((item) => !item.isRead),
|
||||
);
|
||||
|
||||
// 初始化导入任务store
|
||||
// 登录布局挂载:先建用户级 SSE,再拉导入任务
|
||||
onMounted(() => {
|
||||
realtimeStore.start();
|
||||
importTaskStore.init();
|
||||
});
|
||||
|
||||
|
||||
@@ -3,63 +3,42 @@ import type { PageQueryDTO } from '#/types/common';
|
||||
|
||||
import { computed, ref } from 'vue';
|
||||
|
||||
import { useAccessStore } from '@vben/stores';
|
||||
import { defineStore } from 'pinia';
|
||||
|
||||
import {
|
||||
createSseConnection,
|
||||
getImportTaskPageApi,
|
||||
} from '#/api/ecommerce/import-task';
|
||||
import { requestClient } from '#/api/request';
|
||||
import { getImportTaskPageApi } from '#/api/ecommerce/import-task';
|
||||
import { RealtimeSseEvent } from '#/api/notify/sse';
|
||||
import { useRealtimeStore } from '#/store/realtime';
|
||||
|
||||
/**
|
||||
* 导入任务管理 Store
|
||||
* 导入任务管理 Store(进度通过全局 realtime SSE 订阅)
|
||||
*/
|
||||
export const useImportTaskStore = defineStore('import-task', () => {
|
||||
// 任务列表
|
||||
const tasks = ref<ImportTaskVO.ImportTaskInfoVO[]>([]);
|
||||
|
||||
// 分页信息
|
||||
const pagination = ref({
|
||||
current: 1,
|
||||
pageSize: 10,
|
||||
total: 0,
|
||||
});
|
||||
|
||||
// SSE连接
|
||||
const sseConnection = ref<null | ReturnType<typeof createSseConnection>>(
|
||||
null,
|
||||
);
|
||||
const sseConnected = ref(false);
|
||||
// 心跳检测:上次收到ping的时间
|
||||
const lastPingTime = ref<number | null>(null);
|
||||
let pingCheckTimer: ReturnType<typeof setInterval> | null = null;
|
||||
// 页面可见性监听器引用
|
||||
let visibilityHandler: (() => void) | null = null;
|
||||
|
||||
// 加载状态
|
||||
const loading = ref(false);
|
||||
|
||||
// 控制下拉菜单打开状态
|
||||
const shouldOpenDropdown = ref(false);
|
||||
|
||||
// 计算属性:是否有进行中的任务
|
||||
let unsubProgress: (() => void) | null = null;
|
||||
let unsubAllDone: (() => void) | null = null;
|
||||
|
||||
const hasActiveTasks = computed(() => {
|
||||
return tasks.value.some(
|
||||
(task) => task.status === 'pending' || task.status === 'processing',
|
||||
);
|
||||
});
|
||||
|
||||
// 计算属性:进行中的任务数量
|
||||
const activeTaskCount = computed(() => {
|
||||
return tasks.value.filter(
|
||||
(task) => task.status === 'pending' || task.status === 'processing',
|
||||
).length;
|
||||
});
|
||||
|
||||
/**
|
||||
* 获取任务列表
|
||||
*/
|
||||
async function fetchTasks(reset = false) {
|
||||
if (loading.value) return;
|
||||
|
||||
@@ -93,249 +72,68 @@ export const useImportTaskStore = defineStore('import-task', () => {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新任务状态(通过SSE接收到的更新)
|
||||
*/
|
||||
function updateTask(task: ImportTaskVO.ImportTaskInfoVO) {
|
||||
const index = tasks.value.findIndex((t) => t.id === task.id);
|
||||
if (index === -1) {
|
||||
// 如果是新任务,添加到列表开头
|
||||
tasks.value.unshift(task);
|
||||
} else {
|
||||
// 更新现有任务
|
||||
tasks.value[index] = task;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 确保持有有效的 access token
|
||||
*
|
||||
* 逻辑:
|
||||
* 1. 如果 refreshToken 已过期 → 返回 null(需重新登录)
|
||||
* 2. 如果 accessToken 未过期且未接近过期 → 直接返回
|
||||
* 3. 如果 accessToken 快过期或已过期 → 发一个轻量请求,
|
||||
* requestClient 会自动刷新 token,等待刷新完成后返回新 token
|
||||
*
|
||||
* @returns 有效 token,null 表示 refreshToken 已过期无法刷新
|
||||
*/
|
||||
async function ensureValidToken(): Promise<string | null> {
|
||||
const accessStore = useAccessStore();
|
||||
|
||||
// refreshToken 已过期,无法刷新
|
||||
if (accessStore.isRefreshTokenExpired()) {
|
||||
console.warn('[SSE] refreshToken 已过期,无法刷新 token,SSE 将不建立连接');
|
||||
return null;
|
||||
}
|
||||
|
||||
// accessToken 仍然有效且未接近过期,直接返回
|
||||
if (!accessStore.isAccessTokenExpiringSoon()) {
|
||||
return accessStore.accessToken;
|
||||
}
|
||||
|
||||
// accessToken 快过期或已过期,通过 requestClient 触发刷新
|
||||
// 随便发一个轻量请求,走 requestClient 的 401 拦截器自动刷新
|
||||
try {
|
||||
await requestClient.get('/user/info');
|
||||
} catch {
|
||||
// 刷新失败,ignore(requestClient 已处理)
|
||||
}
|
||||
|
||||
// 刷新后检查
|
||||
if (accessStore.isRefreshTokenExpired()) {
|
||||
return null;
|
||||
}
|
||||
return accessStore.accessToken;
|
||||
}
|
||||
|
||||
/**
|
||||
* 建立SSE连接(连接前自动确保 token 有效)
|
||||
*
|
||||
* @returns Promise,连接建立成功后 resolve
|
||||
*/
|
||||
async function connectSse(): Promise<void> {
|
||||
// 如果已经连接且已连接成功,直接返回
|
||||
if (sseConnection.value && sseConnected.value) {
|
||||
function subscribeRealtime() {
|
||||
if (unsubProgress) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 确保 token 有效(可能触发刷新)
|
||||
const token = await ensureValidToken();
|
||||
if (!token) {
|
||||
console.warn('[SSE] token 无效,无法建立连接');
|
||||
return;
|
||||
}
|
||||
|
||||
// 关闭旧连接
|
||||
disconnectSse();
|
||||
|
||||
try {
|
||||
const connection = createSseConnection();
|
||||
sseConnection.value = connection;
|
||||
sseConnected.value = false;
|
||||
|
||||
// 监听连接成功事件
|
||||
const connectedHandler = (event: MessageEvent) => {
|
||||
lastPingTime.value = Date.now();
|
||||
const realtime = useRealtimeStore();
|
||||
unsubProgress = realtime.on(
|
||||
RealtimeSseEvent.IMPORT_TASK_PROGRESS,
|
||||
(event) => {
|
||||
try {
|
||||
const data = JSON.parse(event.data);
|
||||
if (data.type === 'connected') {
|
||||
sseConnected.value = true;
|
||||
connection.removeEventListener('message', connectedHandler);
|
||||
}
|
||||
} catch {
|
||||
// 忽略解析错误
|
||||
}
|
||||
};
|
||||
|
||||
// 连接失败(拒绝 Promise)
|
||||
const errorHandler = (_event: MessageEvent) => {
|
||||
connection.removeEventListener('message', connectedHandler);
|
||||
connection.removeEventListener('error', errorHandler);
|
||||
sseConnected.value = false;
|
||||
// 安排重连(会重新检查并刷新 token)
|
||||
scheduleReconnect(5000);
|
||||
};
|
||||
|
||||
connection.addEventListener('message', connectedHandler);
|
||||
connection.addEventListener('error', errorHandler);
|
||||
|
||||
connection.connect();
|
||||
|
||||
// 心跳检测:须大于服务端首包 ping 间隔(后端约 15s 一发),避免「已连接但首 ping 未到」误判超时
|
||||
const HEARTBEAT_STALE_MS = 45_000;
|
||||
lastPingTime.value = Date.now();
|
||||
if (pingCheckTimer !== null) {
|
||||
clearInterval(pingCheckTimer);
|
||||
}
|
||||
pingCheckTimer = setInterval(() => {
|
||||
if (
|
||||
lastPingTime.value !== null &&
|
||||
Date.now() - lastPingTime.value > HEARTBEAT_STALE_MS
|
||||
) {
|
||||
console.warn('[SSE] 心跳超时,断开并重连');
|
||||
scheduleReconnect(1000);
|
||||
}
|
||||
}, 5_000);
|
||||
|
||||
// 监听页面可见性变化:切回前台时重连(token 可能已刷新)
|
||||
if (visibilityHandler === null) {
|
||||
visibilityHandler = () => {
|
||||
if (document.visibilityState === 'visible') {
|
||||
scheduleReconnect(1000);
|
||||
}
|
||||
};
|
||||
document.addEventListener('visibilitychange', visibilityHandler);
|
||||
}
|
||||
|
||||
// 接收心跳ping
|
||||
connection.addEventListener('ping', () => {
|
||||
lastPingTime.value = Date.now();
|
||||
});
|
||||
|
||||
// 接收任务进度更新(也算链路存活,刷新心跳时间)
|
||||
connection.addEventListener('task_progress', (event) => {
|
||||
lastPingTime.value = Date.now();
|
||||
try {
|
||||
const data = JSON.parse(event.data);
|
||||
if (data.type === 'task_progress' && data.task) {
|
||||
if (data.task) {
|
||||
updateTask(data.task);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('解析任务进度消息失败:', error);
|
||||
console.error('解析导入任务进度失败:', error);
|
||||
}
|
||||
});
|
||||
|
||||
// 所有任务完成
|
||||
connection.addEventListener('all_tasks_completed', () => {
|
||||
lastPingTime.value = Date.now();
|
||||
try {
|
||||
fetchTasks(true);
|
||||
} catch (error) {
|
||||
console.error('刷新任务列表失败:', error);
|
||||
}
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('建立SSE连接失败:', error);
|
||||
sseConnected.value = false;
|
||||
}
|
||||
},
|
||||
);
|
||||
unsubAllDone = realtime.on(
|
||||
RealtimeSseEvent.IMPORT_ALL_TASKS_COMPLETED,
|
||||
() => {
|
||||
fetchTasks(true).catch(() => {});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 延迟重连(重连前会刷新 token)
|
||||
*/
|
||||
let reconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
function scheduleReconnect(delayMs: number) {
|
||||
// 取消待执行的重连
|
||||
if (reconnectTimer !== null) {
|
||||
clearTimeout(reconnectTimer);
|
||||
reconnectTimer = null;
|
||||
}
|
||||
// 先断开现有连接
|
||||
disconnectSse();
|
||||
reconnectTimer = setTimeout(() => {
|
||||
reconnectTimer = null;
|
||||
connectSse();
|
||||
}, delayMs);
|
||||
function unsubscribeRealtime() {
|
||||
unsubProgress?.();
|
||||
unsubAllDone?.();
|
||||
unsubProgress = null;
|
||||
unsubAllDone = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 断开SSE连接
|
||||
*/
|
||||
function disconnectSse() {
|
||||
if (reconnectTimer !== null) {
|
||||
clearTimeout(reconnectTimer);
|
||||
reconnectTimer = null;
|
||||
}
|
||||
if (pingCheckTimer !== null) {
|
||||
clearInterval(pingCheckTimer);
|
||||
pingCheckTimer = null;
|
||||
}
|
||||
if (visibilityHandler !== null) {
|
||||
document.removeEventListener('visibilitychange', visibilityHandler);
|
||||
visibilityHandler = null;
|
||||
}
|
||||
if (sseConnection.value) {
|
||||
sseConnection.value.disconnect();
|
||||
sseConnection.value = null;
|
||||
}
|
||||
sseConnected.value = false;
|
||||
lastPingTime.value = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化:获取第一页任务
|
||||
*/
|
||||
async function init() {
|
||||
subscribeRealtime();
|
||||
await fetchTasks(true);
|
||||
// 页面加载时建立SSE连接,接收实时任务状态更新
|
||||
connectSse();
|
||||
}
|
||||
|
||||
/**
|
||||
* 重置store
|
||||
*/
|
||||
function $reset() {
|
||||
unsubscribeRealtime();
|
||||
tasks.value = [];
|
||||
pagination.value = {
|
||||
current: 1,
|
||||
pageSize: 10,
|
||||
total: 0,
|
||||
};
|
||||
disconnectSse();
|
||||
loading.value = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开下拉菜单
|
||||
*/
|
||||
function openDropdown() {
|
||||
shouldOpenDropdown.value = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭下拉菜单
|
||||
*/
|
||||
function closeDropdown() {
|
||||
shouldOpenDropdown.value = false;
|
||||
}
|
||||
@@ -343,16 +141,12 @@ export const useImportTaskStore = defineStore('import-task', () => {
|
||||
return {
|
||||
tasks,
|
||||
pagination,
|
||||
sseConnection,
|
||||
sseConnected,
|
||||
loading,
|
||||
shouldOpenDropdown,
|
||||
hasActiveTasks,
|
||||
activeTaskCount,
|
||||
fetchTasks,
|
||||
updateTask,
|
||||
connectSse,
|
||||
disconnectSse,
|
||||
init,
|
||||
openDropdown,
|
||||
closeDropdown,
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
export * from './auth';
|
||||
export * from './import-task';
|
||||
export * from './realtime';
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
import { ref } from 'vue';
|
||||
|
||||
import { useAccessStore } from '@vben/stores';
|
||||
import { defineStore } from 'pinia';
|
||||
|
||||
import {
|
||||
createRealtimeSseConnection,
|
||||
RealtimeSseEvent,
|
||||
type RealtimeSseConnection,
|
||||
} from '#/api/notify/sse';
|
||||
import { requestClient } from '#/api/request';
|
||||
|
||||
type SseHandler = (event: MessageEvent) => void;
|
||||
|
||||
/**
|
||||
* 全站唯一用户级 SSE 通道:登录后连接,业务 store 只订阅事件。
|
||||
*/
|
||||
export const useRealtimeStore = defineStore('realtime', () => {
|
||||
const connection = ref<null | RealtimeSseConnection>(null);
|
||||
const connected = ref(false);
|
||||
const lastPingTime = ref<number | null>(null);
|
||||
|
||||
const handlers = new Map<string, Set<SseHandler>>();
|
||||
|
||||
let pingCheckTimer: ReturnType<typeof setInterval> | null = null;
|
||||
let visibilityHandler: (() => void) | null = null;
|
||||
let reconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let started = false;
|
||||
let connecting = false;
|
||||
|
||||
async function ensureValidToken(): Promise<string | null> {
|
||||
const accessStore = useAccessStore();
|
||||
if (accessStore.isRefreshTokenExpired()) {
|
||||
console.warn('[RealtimeSSE] refreshToken 已过期');
|
||||
return null;
|
||||
}
|
||||
if (!accessStore.isAccessTokenExpiringSoon()) {
|
||||
return accessStore.accessToken;
|
||||
}
|
||||
try {
|
||||
await requestClient.get('/user/info');
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
if (accessStore.isRefreshTokenExpired()) {
|
||||
return null;
|
||||
}
|
||||
return accessStore.accessToken;
|
||||
}
|
||||
|
||||
function bindConnectionHandlers(conn: RealtimeSseConnection) {
|
||||
handlers.forEach((set, eventType) => {
|
||||
set.forEach((handler) => {
|
||||
conn.addEventListener(eventType, handler);
|
||||
});
|
||||
});
|
||||
|
||||
const connectedHandler = (event: MessageEvent) => {
|
||||
lastPingTime.value = Date.now();
|
||||
try {
|
||||
const data = JSON.parse(event.data);
|
||||
if (data.type === 'connected') {
|
||||
connected.value = true;
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
};
|
||||
|
||||
const errorHandler = () => {
|
||||
connected.value = false;
|
||||
// 断线后由我们刷新 token 再连,避免 EventSource 用旧 query token 死循环
|
||||
scheduleReconnect(3000);
|
||||
};
|
||||
|
||||
conn.addEventListener(RealtimeSseEvent.CONNECTED, connectedHandler);
|
||||
conn.addEventListener('error', errorHandler);
|
||||
conn.addEventListener(RealtimeSseEvent.PING, () => {
|
||||
lastPingTime.value = Date.now();
|
||||
});
|
||||
}
|
||||
|
||||
async function connect(): Promise<void> {
|
||||
if (connecting) {
|
||||
return;
|
||||
}
|
||||
if (connection.value && connected.value) {
|
||||
return;
|
||||
}
|
||||
|
||||
connecting = true;
|
||||
try {
|
||||
const token = await ensureValidToken();
|
||||
if (!token) {
|
||||
console.warn('[RealtimeSSE] token 无效,无法建立连接');
|
||||
return;
|
||||
}
|
||||
|
||||
disconnect(false);
|
||||
|
||||
const conn = createRealtimeSseConnection();
|
||||
connection.value = conn;
|
||||
connected.value = false;
|
||||
bindConnectionHandlers(conn);
|
||||
conn.connect();
|
||||
|
||||
const HEARTBEAT_STALE_MS = 60_000;
|
||||
lastPingTime.value = Date.now();
|
||||
if (pingCheckTimer !== null) {
|
||||
clearInterval(pingCheckTimer);
|
||||
}
|
||||
pingCheckTimer = setInterval(() => {
|
||||
if (
|
||||
lastPingTime.value !== null &&
|
||||
Date.now() - lastPingTime.value > HEARTBEAT_STALE_MS
|
||||
) {
|
||||
console.warn('[RealtimeSSE] 心跳超时,断开并重连');
|
||||
scheduleReconnect(1000);
|
||||
}
|
||||
}, 10_000);
|
||||
|
||||
if (visibilityHandler === null) {
|
||||
visibilityHandler = () => {
|
||||
if (document.visibilityState !== 'visible') {
|
||||
return;
|
||||
}
|
||||
// 仅在确认掉线时重连,避免切回标签就拆掉健康连接
|
||||
if (!connected.value || connection.value == null) {
|
||||
scheduleReconnect(500);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
lastPingTime.value !== null &&
|
||||
Date.now() - lastPingTime.value > HEARTBEAT_STALE_MS
|
||||
) {
|
||||
scheduleReconnect(500);
|
||||
}
|
||||
};
|
||||
document.addEventListener('visibilitychange', visibilityHandler);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('建立实时SSE连接失败:', error);
|
||||
connected.value = false;
|
||||
} finally {
|
||||
connecting = false;
|
||||
}
|
||||
}
|
||||
|
||||
function scheduleReconnect(delayMs: number) {
|
||||
if (reconnectTimer !== null) {
|
||||
clearTimeout(reconnectTimer);
|
||||
reconnectTimer = null;
|
||||
}
|
||||
disconnect(false);
|
||||
reconnectTimer = setTimeout(() => {
|
||||
reconnectTimer = null;
|
||||
connect();
|
||||
}, delayMs);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param clearVisibility 是否移除可见性监听(登出时 true)
|
||||
*/
|
||||
function disconnect(clearVisibility = true) {
|
||||
if (reconnectTimer !== null) {
|
||||
clearTimeout(reconnectTimer);
|
||||
reconnectTimer = null;
|
||||
}
|
||||
if (pingCheckTimer !== null) {
|
||||
clearInterval(pingCheckTimer);
|
||||
pingCheckTimer = null;
|
||||
}
|
||||
if (clearVisibility && visibilityHandler !== null) {
|
||||
document.removeEventListener('visibilitychange', visibilityHandler);
|
||||
visibilityHandler = null;
|
||||
}
|
||||
if (connection.value) {
|
||||
connection.value.disconnect();
|
||||
connection.value = null;
|
||||
}
|
||||
connected.value = false;
|
||||
lastPingTime.value = null;
|
||||
}
|
||||
|
||||
function touchHeartbeat() {
|
||||
lastPingTime.value = Date.now();
|
||||
}
|
||||
|
||||
/**
|
||||
* 订阅事件;返回取消订阅函数
|
||||
*/
|
||||
function on(eventType: string, handler: SseHandler): () => void {
|
||||
if (!handlers.has(eventType)) {
|
||||
handlers.set(eventType, new Set());
|
||||
}
|
||||
const wrapped: SseHandler = (event) => {
|
||||
touchHeartbeat();
|
||||
handler(event);
|
||||
};
|
||||
(handler as SseHandler & { __wrapped?: SseHandler }).__wrapped = wrapped;
|
||||
handlers.get(eventType)!.add(wrapped);
|
||||
connection.value?.addEventListener(eventType, wrapped);
|
||||
return () => off(eventType, handler);
|
||||
}
|
||||
|
||||
function off(eventType: string, handler: SseHandler) {
|
||||
const wrapped =
|
||||
(handler as SseHandler & { __wrapped?: SseHandler }).__wrapped || handler;
|
||||
handlers.get(eventType)?.delete(wrapped);
|
||||
connection.value?.removeEventListener(eventType, wrapped);
|
||||
}
|
||||
|
||||
/** 布局挂载时调用:建立连接 */
|
||||
async function start() {
|
||||
if (started) {
|
||||
return;
|
||||
}
|
||||
started = true;
|
||||
await connect();
|
||||
}
|
||||
|
||||
function $reset() {
|
||||
started = false;
|
||||
connecting = false;
|
||||
handlers.clear();
|
||||
disconnect(true);
|
||||
}
|
||||
|
||||
return {
|
||||
connection,
|
||||
connected,
|
||||
lastPingTime,
|
||||
connect,
|
||||
disconnect,
|
||||
on,
|
||||
off,
|
||||
start,
|
||||
touchHeartbeat,
|
||||
$reset,
|
||||
};
|
||||
});
|
||||
+75
-29
@@ -29,6 +29,8 @@ import {
|
||||
syncPddOrdersIncrementalApi,
|
||||
togglePddIncrementalSyncApi,
|
||||
} from '#/api/ecommerce/pdd/order-sync';
|
||||
import { RealtimeSseEvent } from '#/api/notify/sse';
|
||||
import { useRealtimeStore } from '#/store';
|
||||
|
||||
defineOptions({ name: 'PddOrderSyncDrawer' });
|
||||
|
||||
@@ -51,6 +53,8 @@ const range = ref<[Dayjs, Dayjs]>([
|
||||
const incremental = ref<null | PddOrderSyncVO.IncrementalStatus>(null);
|
||||
const fullTask = ref<null | PddOrderSyncVO.FullTask>(null);
|
||||
let pollTimer: null | ReturnType<typeof setInterval> = null;
|
||||
let unsubProgress: (() => void) | null = null;
|
||||
let terminalNotifiedTaskId: null | number = null;
|
||||
|
||||
const drawerTitle = computed(() =>
|
||||
shop.value ? `同步拼多多订单 - ${shop.value.name}` : '同步拼多多订单',
|
||||
@@ -104,6 +108,60 @@ function stopPoll() {
|
||||
}
|
||||
}
|
||||
|
||||
function unsubscribeProgress() {
|
||||
unsubProgress?.();
|
||||
unsubProgress = null;
|
||||
}
|
||||
|
||||
function applyFullTaskUpdate(task: PddOrderSyncVO.FullTask) {
|
||||
if (!shop.value || task.shopId !== shop.value.id) {
|
||||
return;
|
||||
}
|
||||
fullTask.value = task;
|
||||
const terminal =
|
||||
task.status === 'SUCCESS' ||
|
||||
task.status === 'FAILED' ||
|
||||
task.status === 'CANCELLED';
|
||||
if (!terminal) {
|
||||
return;
|
||||
}
|
||||
stopPoll();
|
||||
submitting.value = false;
|
||||
loading.value = false;
|
||||
if (terminalNotifiedTaskId === task.id) {
|
||||
return;
|
||||
}
|
||||
terminalNotifiedTaskId = task.id;
|
||||
if (task.status === 'SUCCESS') {
|
||||
message.success(`全量同步完成:${task.doneDays}/${task.totalDays} 天`);
|
||||
emit('success');
|
||||
} else if (task.status === 'FAILED') {
|
||||
message.error(task.lastError || '全量同步失败');
|
||||
emit('success');
|
||||
} else {
|
||||
message.info('全量同步已取消');
|
||||
emit('success');
|
||||
}
|
||||
}
|
||||
|
||||
function subscribeProgress() {
|
||||
unsubscribeProgress();
|
||||
const realtime = useRealtimeStore();
|
||||
unsubProgress = realtime.on(
|
||||
RealtimeSseEvent.PDD_ORDER_FULL_SYNC_PROGRESS,
|
||||
(event) => {
|
||||
try {
|
||||
const data = JSON.parse(event.data);
|
||||
if (data.task) {
|
||||
applyFullTaskUpdate(data.task as PddOrderSyncVO.FullTask);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('解析全量同步进度失败:', error);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async function loadIncrementalStatus() {
|
||||
if (!shop.value) return;
|
||||
try {
|
||||
@@ -119,7 +177,7 @@ async function loadLatestFullTask() {
|
||||
const task = await getPddLatestFullSyncTaskApi(shop.value.id);
|
||||
fullTask.value = task;
|
||||
if (task && (task.status === 'PENDING' || task.status === 'RUNNING')) {
|
||||
pollFullTask(task.id);
|
||||
watchFullTask(task.id);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('加载全量任务失败:', error);
|
||||
@@ -144,37 +202,18 @@ async function handleToggleIncremental(checked: boolean | string | number) {
|
||||
}
|
||||
}
|
||||
|
||||
async function pollFullTask(taskId: number) {
|
||||
/** SSE 为主,低频轮询兜底(防止漏事件) */
|
||||
function watchFullTask(taskId: number) {
|
||||
stopPoll();
|
||||
subscribeProgress();
|
||||
pollTimer = setInterval(async () => {
|
||||
try {
|
||||
const task = await getPddFullSyncTaskApi(taskId);
|
||||
fullTask.value = task;
|
||||
if (
|
||||
task.status === 'SUCCESS' ||
|
||||
task.status === 'FAILED' ||
|
||||
task.status === 'CANCELLED'
|
||||
) {
|
||||
stopPoll();
|
||||
submitting.value = false;
|
||||
loading.value = false;
|
||||
if (task.status === 'SUCCESS') {
|
||||
message.success(
|
||||
`全量同步完成:${task.doneDays}/${task.totalDays} 天`,
|
||||
);
|
||||
emit('success');
|
||||
} else if (task.status === 'FAILED') {
|
||||
message.error(task.lastError || '全量同步失败');
|
||||
emit('success');
|
||||
} else {
|
||||
message.info('全量同步已取消');
|
||||
emit('success');
|
||||
}
|
||||
}
|
||||
applyFullTaskUpdate(task);
|
||||
} catch (error) {
|
||||
console.error('轮询全量任务失败:', error);
|
||||
}
|
||||
}, 2000);
|
||||
}, 10_000);
|
||||
}
|
||||
|
||||
async function handleCancelFull() {
|
||||
@@ -198,10 +237,11 @@ async function handleResumeFull() {
|
||||
try {
|
||||
loading.value = true;
|
||||
submitting.value = true;
|
||||
terminalNotifiedTaskId = null;
|
||||
const task = await resumePddFullSyncTaskApi(fullTask.value.id);
|
||||
fullTask.value = task;
|
||||
message.success('已续跑入队');
|
||||
pollFullTask(task.id);
|
||||
watchFullTask(task.id);
|
||||
} catch (error) {
|
||||
console.error('续跑全量任务失败:', error);
|
||||
message.error('续跑全量任务失败');
|
||||
@@ -237,6 +277,7 @@ async function handleSubmit() {
|
||||
mode.value === 'day'
|
||||
? confirmDate.value.format('YYYY-MM-DD')
|
||||
: range.value[1].format('YYYY-MM-DD');
|
||||
terminalNotifiedTaskId = null;
|
||||
const task = await createPddFullSyncTaskApi({
|
||||
shopId: shop.value.id,
|
||||
dateFrom,
|
||||
@@ -248,7 +289,7 @@ async function handleSubmit() {
|
||||
? '单日全量任务已创建,正在后台执行'
|
||||
: '全量同步任务已创建,正在后台执行',
|
||||
);
|
||||
pollFullTask(task.id);
|
||||
watchFullTask(task.id);
|
||||
emit('success');
|
||||
return;
|
||||
}
|
||||
@@ -259,7 +300,6 @@ async function handleSubmit() {
|
||||
await loadIncrementalStatus();
|
||||
} catch (error) {
|
||||
console.error('同步拼多多订单失败:', error);
|
||||
// 业务错误由 request 拦截器已提示(如区间已涵盖)
|
||||
loading.value = false;
|
||||
submitting.value = false;
|
||||
} finally {
|
||||
@@ -272,6 +312,7 @@ async function handleSubmit() {
|
||||
|
||||
function handleClose() {
|
||||
stopPoll();
|
||||
unsubscribeProgress();
|
||||
openFlag.value = false;
|
||||
}
|
||||
|
||||
@@ -284,12 +325,17 @@ async function open(record: ShopVO.Info) {
|
||||
incremental.value = null;
|
||||
submitting.value = false;
|
||||
loading.value = false;
|
||||
terminalNotifiedTaskId = null;
|
||||
stopPoll();
|
||||
subscribeProgress();
|
||||
openFlag.value = true;
|
||||
await Promise.all([loadIncrementalStatus(), loadLatestFullTask()]);
|
||||
}
|
||||
|
||||
onBeforeUnmount(() => stopPoll());
|
||||
onBeforeUnmount(() => {
|
||||
stopPoll();
|
||||
unsubscribeProgress();
|
||||
});
|
||||
|
||||
defineExpose({ open, close: handleClose });
|
||||
</script>
|
||||
|
||||
@@ -14,6 +14,9 @@ export default defineConfig(async () => {
|
||||
// 后端服务地址
|
||||
target: 'http://localhost:8080',
|
||||
ws: true,
|
||||
// SSE 长连接:禁止代理空闲超时断开
|
||||
timeout: 0,
|
||||
proxyTimeout: 0,
|
||||
},
|
||||
// 静态资源代理 - 用于访问上传的图片和文件
|
||||
'/uploads': {
|
||||
|
||||
Reference in New Issue
Block a user