mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-25 05:09:19 +08:00
feat: 抽出sse实时连接服务,导入进度和同步进度共用公共sse连接
This commit is contained in:
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user