fix: SSE多设备连接修复(token刷新+deviceId隔离)

This commit is contained in:
小蟑螂
2026-04-21 00:21:36 +08:00
parent 024d2443d6
commit b48a4cbdf1
5 changed files with 488 additions and 346 deletions
@@ -38,18 +38,26 @@ export async function getImportTaskPageApi(
}
/**
* SSE连接管理器(使用原生EventSource,支持自动重连)
* SSE连接管理器(使用原生EventSource,支持多设备和 token 刷新重连)
*/
class SseConnection {
private eventSource: EventSource | null = null;
private accessStore: ReturnType<typeof useAccessStore>;
private listeners: Map<string, Set<(event: MessageEvent) => void>> =
new Map();
// EventSource 原生状态常量
private readyState: number = EventSource.CLOSED;
/** 设备标识,同一标签页内共用,重开标签页是新ID */
private deviceId: string;
/** 设备标识,每个标签页独立,不跨标签页共享 */
private deviceId: string;
constructor() {
this.accessStore = useAccessStore();
// 每个 SseConnection 实例独立生成 deviceId
// 不存 sessionStorage:同 origin 不同标签页不应共享 ID
this.deviceId = crypto.randomUUID
? crypto.randomUUID()
: `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
}
/**
@@ -88,13 +96,17 @@ class SseConnection {
this.disconnect();
}
const token = this.accessStore.accessToken;
// token 必须由调用方传入(connectSse 在重连前已刷新 token)
const accessStore = useAccessStore();
const token = accessStore.accessToken;
if (!token) {
console.error('无法建立SSE连接:token不存在');
return;
}
const url = `${apiURL}/ec/import-task/sse/connect?token=${encodeURIComponent(token)}`;
// 加时间戳参数避免浏览器复用/合并同 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);