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