mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 13:49:19 +08:00
149 lines
4.1 KiB
TypeScript
149 lines
4.1 KiB
TypeScript
import { useAppConfig } from '@vben/hooks';
|
|
import { useAccessStore } from '@vben/stores';
|
|
|
|
const { apiURL } = useAppConfig(import.meta.env, import.meta.env.PROD);
|
|
|
|
/** 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 createDeviceId(): string {
|
|
return crypto.randomUUID
|
|
? crypto.randomUUID()
|
|
: `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
|
}
|
|
|
|
/**
|
|
* 用户级 SSE 连接。
|
|
* deviceId 仅存本页内存:避免 Chrome「复制标签」复制 sessionStorage 导致同 id 互踢。
|
|
* 同标签重连会换新 id;旧连接已 disconnect,服务端靠回调清理即可。
|
|
*/
|
|
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 = createDeviceId();
|
|
}
|
|
|
|
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();
|
|
}
|