2026-06-22 13:46:36 +08:00
|
|
|
import { ref } from 'vue'
|
2026-06-23 10:13:53 +08:00
|
|
|
import { fetchEventSource } from '@microsoft/fetch-event-source'
|
2026-06-22 13:46:36 +08:00
|
|
|
import { sseBus } from '@/stores/sseBus'
|
2026-06-24 08:30:33 +08:00
|
|
|
import type { SseEvents } from '@/stores/sseBus'
|
2026-06-22 13:46:36 +08:00
|
|
|
import { useAccountStore } from '@/stores/modules/account'
|
|
|
|
|
|
2026-06-24 08:30:33 +08:00
|
|
|
const SSE_URL = '/api/sse/subscribe'
|
|
|
|
|
const MAX_RETRY_COUNT = 5
|
|
|
|
|
const BASE_RETRY_DELAY_MS = 3000
|
|
|
|
|
const MAX_RETRY_DELAY_MS = 30000
|
|
|
|
|
|
|
|
|
|
const isConnected = ref(false)
|
|
|
|
|
let abortController: AbortController | null = null
|
|
|
|
|
let currentToken: string | null = null
|
|
|
|
|
let connecting = false
|
|
|
|
|
let retryCount = 0
|
|
|
|
|
let isRefreshing = false
|
|
|
|
|
|
|
|
|
|
class SseHttpError extends Error {
|
|
|
|
|
constructor(
|
|
|
|
|
message: string,
|
|
|
|
|
readonly response: Response
|
|
|
|
|
) {
|
|
|
|
|
super(message)
|
|
|
|
|
this.name = 'SseHttpError'
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function isSseHttpError(error: unknown): error is SseHttpError {
|
|
|
|
|
return error instanceof SseHttpError
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function getRetryDelay(): number {
|
|
|
|
|
return Math.min(BASE_RETRY_DELAY_MS * Math.pow(2, retryCount - 1), MAX_RETRY_DELAY_MS)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function resetConnectionState(): void {
|
|
|
|
|
connecting = false
|
|
|
|
|
isConnected.value = false
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-22 13:46:36 +08:00
|
|
|
/**
|
2026-06-24 08:30:33 +08:00
|
|
|
* Global SSE connection manager.
|
2026-06-22 13:46:36 +08:00
|
|
|
*
|
2026-06-24 08:30:33 +08:00
|
|
|
* Module-level state guarantees a single active connection across all callers.
|
2026-06-22 13:46:36 +08:00
|
|
|
*/
|
|
|
|
|
export function useSse() {
|
2026-06-23 10:13:53 +08:00
|
|
|
async function connect(): Promise<void> {
|
2026-06-22 13:46:36 +08:00
|
|
|
const accountStore = useAccountStore()
|
|
|
|
|
const token = accountStore.accessToken
|
2026-06-24 08:30:33 +08:00
|
|
|
|
2026-06-22 13:46:36 +08:00
|
|
|
if (!token) {
|
2026-06-24 08:30:33 +08:00
|
|
|
console.warn('[SSE] Missing accessToken, skip connection')
|
2026-06-22 13:46:36 +08:00
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-23 14:32:00 +08:00
|
|
|
if (currentToken === token && (isConnected.value || connecting)) {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-23 10:13:53 +08:00
|
|
|
abort()
|
2026-06-23 14:32:00 +08:00
|
|
|
connecting = true
|
|
|
|
|
currentToken = token
|
2026-06-23 10:13:53 +08:00
|
|
|
abortController = new AbortController()
|
2026-06-22 13:46:36 +08:00
|
|
|
|
2026-06-24 08:30:33 +08:00
|
|
|
await fetchEventSource(SSE_URL, {
|
2026-06-23 10:13:53 +08:00
|
|
|
headers: { saToken: token },
|
|
|
|
|
signal: abortController.signal,
|
2026-06-24 08:30:33 +08:00
|
|
|
openWhenHidden: true,
|
|
|
|
|
|
|
|
|
|
async onopen(response) {
|
|
|
|
|
const contentType = response.headers.get('content-type') || ''
|
|
|
|
|
|
|
|
|
|
if (response.status === 401) {
|
|
|
|
|
throw new SseHttpError('SSE unauthorized', response)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (!response.ok) {
|
|
|
|
|
throw new SseHttpError(`SSE connection failed: ${response.status}`, response)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (!contentType.includes('text/event-stream')) {
|
|
|
|
|
throw new SseHttpError(`Invalid SSE content-type: ${contentType || 'empty'}`, response)
|
|
|
|
|
}
|
2026-06-22 13:46:36 +08:00
|
|
|
|
2026-06-23 14:32:00 +08:00
|
|
|
connecting = false
|
2026-06-23 10:13:53 +08:00
|
|
|
isConnected.value = true
|
|
|
|
|
retryCount = 0
|
2026-06-24 08:30:33 +08:00
|
|
|
sseBus.emit('connected', undefined)
|
|
|
|
|
console.log('[SSE] Connected')
|
2026-06-23 10:13:53 +08:00
|
|
|
},
|
2026-06-22 13:46:36 +08:00
|
|
|
|
2026-06-24 08:30:33 +08:00
|
|
|
onmessage(message) {
|
|
|
|
|
if (!message.event || !message.data) {
|
|
|
|
|
return
|
|
|
|
|
}
|
2026-06-22 13:46:36 +08:00
|
|
|
|
|
|
|
|
try {
|
2026-06-24 08:30:33 +08:00
|
|
|
const data = JSON.parse(message.data)
|
|
|
|
|
sseBus.emit(message.event as keyof SseEvents, data)
|
2026-06-23 10:13:53 +08:00
|
|
|
} catch {
|
2026-06-24 08:30:33 +08:00
|
|
|
console.warn('[SSE] Failed to parse event payload:', message.event, message.data)
|
2026-06-22 13:46:36 +08:00
|
|
|
}
|
2026-06-23 10:13:53 +08:00
|
|
|
},
|
2026-06-22 13:46:36 +08:00
|
|
|
|
2026-06-23 10:13:53 +08:00
|
|
|
onclose() {
|
2026-06-24 08:30:33 +08:00
|
|
|
resetConnectionState()
|
|
|
|
|
console.log('[SSE] Closed')
|
2026-06-23 10:13:53 +08:00
|
|
|
},
|
2026-06-22 13:46:36 +08:00
|
|
|
|
2026-06-24 08:30:33 +08:00
|
|
|
onerror(error) {
|
|
|
|
|
resetConnectionState()
|
2026-06-22 13:46:36 +08:00
|
|
|
|
2026-06-24 08:30:33 +08:00
|
|
|
if (isSseHttpError(error) && error.response.status === 401) {
|
|
|
|
|
void refreshTokenAndReconnect()
|
|
|
|
|
throw error
|
2026-06-23 10:13:53 +08:00
|
|
|
}
|
|
|
|
|
|
2026-06-24 08:30:33 +08:00
|
|
|
retryCount += 1
|
|
|
|
|
if (retryCount >= MAX_RETRY_COUNT) {
|
2026-06-23 10:13:53 +08:00
|
|
|
sseBus.emit('error', {
|
2026-06-24 08:30:33 +08:00
|
|
|
message: 'Realtime connection failed. Please refresh the page.',
|
2026-06-23 10:13:53 +08:00
|
|
|
retryCount
|
|
|
|
|
})
|
2026-06-24 08:30:33 +08:00
|
|
|
throw error
|
2026-06-23 10:13:53 +08:00
|
|
|
}
|
|
|
|
|
|
2026-06-24 08:30:33 +08:00
|
|
|
const delay = getRetryDelay()
|
|
|
|
|
console.warn(`[SSE] Connection error, retry in ${delay / 1000}s (${retryCount}/${MAX_RETRY_COUNT})`)
|
2026-06-23 10:13:53 +08:00
|
|
|
return delay
|
2026-06-22 13:46:36 +08:00
|
|
|
}
|
2026-06-23 10:13:53 +08:00
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function abort(): void {
|
|
|
|
|
if (abortController) {
|
|
|
|
|
abortController.abort()
|
|
|
|
|
abortController = null
|
2026-06-22 13:46:36 +08:00
|
|
|
}
|
2026-06-24 08:30:33 +08:00
|
|
|
|
2026-06-23 14:32:00 +08:00
|
|
|
currentToken = null
|
2026-06-23 10:13:53 +08:00
|
|
|
retryCount = 0
|
2026-06-24 08:30:33 +08:00
|
|
|
resetConnectionState()
|
2026-06-22 13:46:36 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function disconnect(): void {
|
2026-06-23 10:13:53 +08:00
|
|
|
abort()
|
2026-06-24 08:30:33 +08:00
|
|
|
console.log('[SSE] Disconnected')
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async function refreshTokenAndReconnect(): Promise<void> {
|
|
|
|
|
if (isRefreshing) {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const accountStore = useAccountStore()
|
|
|
|
|
if (!accountStore.refreshToken) {
|
|
|
|
|
sseBus.emit('error', { message: 'Login expired. Please sign in again.', retryCount: 0 })
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
isRefreshing = true
|
|
|
|
|
try {
|
|
|
|
|
const newToken = await accountStore.refreshAccessToken()
|
|
|
|
|
if (newToken) {
|
|
|
|
|
retryCount = 0
|
|
|
|
|
await connect()
|
|
|
|
|
}
|
|
|
|
|
} catch {
|
|
|
|
|
sseBus.emit('error', {
|
|
|
|
|
message: 'Realtime connection failed. Please refresh the page.',
|
|
|
|
|
retryCount: 0
|
|
|
|
|
})
|
|
|
|
|
} finally {
|
|
|
|
|
isRefreshing = false
|
|
|
|
|
}
|
2026-06-22 13:46:36 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
isConnected,
|
|
|
|
|
connect,
|
|
|
|
|
disconnect
|
|
|
|
|
}
|
|
|
|
|
}
|