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:
@@ -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