perf(auth): 降低会话校验请求与重复查库
This commit is contained in:
@@ -111,6 +111,11 @@ export async function fetchMe(options?: { silent?: boolean }) {
|
||||
return data.data
|
||||
}
|
||||
|
||||
export async function fetchSessionState(options?: { silent?: boolean }) {
|
||||
const { data } = await apiClient.get<ApiResponse<{ active: boolean }>>('/auth/session', options)
|
||||
return data.data
|
||||
}
|
||||
|
||||
export async function updateMe(payload: Pick<AuthUser, 'nickname' | 'avatar_url'>) {
|
||||
const { data } = await apiClient.put<ApiResponse<AuthUser>>('/me', payload)
|
||||
return data.data
|
||||
|
||||
@@ -1,19 +1,23 @@
|
||||
import { onBeforeUnmount, onMounted, watch } from 'vue'
|
||||
|
||||
import { fetchMe } from '@/features/auth/api/auth'
|
||||
import { getAccessToken, type AuthScope } from '@/shared/utils/authStorage'
|
||||
import { fetchSessionState } from '@/features/auth/api/auth'
|
||||
import { type AuthScope } from '@/shared/utils/authStorage'
|
||||
import { useSessionStore } from '@/stores/session'
|
||||
|
||||
const scope: AuthScope = 'user'
|
||||
const reconnectDelay = 3000
|
||||
const verificationInterval = 5000
|
||||
const reconnectBaseDelay = 3000
|
||||
const reconnectMaxDelay = 60_000
|
||||
const verificationInterval = 300_000
|
||||
const foregroundVerificationMinGap = 60_000
|
||||
|
||||
// 保持一个轻量级会话通道,使后台冻结能在没有页面请求时立即让用户退出。
|
||||
// SSE 负责即时撤销通知,低频会话校验只作为断线与异常场景的兜底。
|
||||
export function useSessionMonitor() {
|
||||
const session = useSessionStore()
|
||||
let source: EventSource | null = null
|
||||
let reconnectTimer: number | null = null
|
||||
let verificationTimer: number | null = null
|
||||
let reconnectAttempt = 0
|
||||
let lastVerifiedAt = 0
|
||||
let checking = false
|
||||
let stopped = false
|
||||
|
||||
@@ -24,17 +28,21 @@ export function useSessionMonitor() {
|
||||
|
||||
function scheduleReconnect() {
|
||||
if (stopped || reconnectTimer !== null || !session.isLoggedIn) return
|
||||
const exponentialDelay = Math.min(reconnectMaxDelay, reconnectBaseDelay * 2 ** reconnectAttempt)
|
||||
const jitteredDelay = Math.round(exponentialDelay * (0.8 + Math.random() * 0.4))
|
||||
reconnectAttempt = Math.min(reconnectAttempt + 1, 10)
|
||||
reconnectTimer = window.setTimeout(() => {
|
||||
reconnectTimer = null
|
||||
connect()
|
||||
}, reconnectDelay)
|
||||
}, jitteredDelay)
|
||||
}
|
||||
|
||||
async function verifySession() {
|
||||
if (stopped || checking || !session.isLoggedIn) return
|
||||
checking = true
|
||||
try {
|
||||
await fetchMe({ silent: true })
|
||||
const state = await fetchSessionState({ silent: true })
|
||||
if (state.active) lastVerifiedAt = Date.now()
|
||||
} catch {
|
||||
// 认证失败由 axios 拦截器清理令牌并跳转;网络错误等待下一次校验。
|
||||
} finally {
|
||||
@@ -44,13 +52,13 @@ export function useSessionMonitor() {
|
||||
|
||||
function connect() {
|
||||
if (stopped || source || !session.isLoggedIn) return
|
||||
const token = getAccessToken(scope)
|
||||
if (!token) return
|
||||
|
||||
source = new EventSource(`/api/auth/events?token=${encodeURIComponent(token)}`, {
|
||||
source = new EventSource('/api/auth/events', {
|
||||
withCredentials: true,
|
||||
})
|
||||
source.addEventListener('connected', () => undefined)
|
||||
source.addEventListener('connected', () => {
|
||||
reconnectAttempt = 0
|
||||
})
|
||||
source.onerror = () => {
|
||||
closeSource()
|
||||
void verifySession()
|
||||
@@ -58,6 +66,15 @@ export function useSessionMonitor() {
|
||||
}
|
||||
}
|
||||
|
||||
function startVerificationTimer() {
|
||||
if (verificationTimer !== null) {
|
||||
window.clearInterval(verificationTimer)
|
||||
verificationTimer = null
|
||||
}
|
||||
if (stopped || document.hidden || !session.isLoggedIn) return
|
||||
verificationTimer = window.setInterval(verifySession, verificationInterval)
|
||||
}
|
||||
|
||||
function stop() {
|
||||
closeSource()
|
||||
if (reconnectTimer !== null) {
|
||||
@@ -68,6 +85,7 @@ export function useSessionMonitor() {
|
||||
window.clearInterval(verificationTimer)
|
||||
verificationTimer = null
|
||||
}
|
||||
reconnectAttempt = 0
|
||||
}
|
||||
|
||||
function start() {
|
||||
@@ -75,7 +93,7 @@ export function useSessionMonitor() {
|
||||
if (!session.isLoggedIn) return
|
||||
connect()
|
||||
void verifySession()
|
||||
verificationTimer = window.setInterval(verifySession, verificationInterval)
|
||||
startVerificationTimer()
|
||||
}
|
||||
|
||||
function handleAuthStorageChanged(event: Event) {
|
||||
@@ -89,7 +107,17 @@ export function useSessionMonitor() {
|
||||
}
|
||||
|
||||
function handleVisibilityChange() {
|
||||
if (document.visibilityState === 'visible') void verifySession()
|
||||
if (document.hidden) {
|
||||
if (verificationTimer !== null) {
|
||||
window.clearInterval(verificationTimer)
|
||||
verificationTimer = null
|
||||
}
|
||||
return
|
||||
}
|
||||
if (Date.now() - lastVerifiedAt >= foregroundVerificationMinGap) {
|
||||
void verifySession()
|
||||
}
|
||||
startVerificationTimer()
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
|
||||
Reference in New Issue
Block a user