bug处理

This commit is contained in:
truewhile
2026-10-16 14:54:06 +08:00
parent d112e8e4db
commit 43cfeabea1
13 changed files with 965 additions and 43 deletions
+3 -28
View File
@@ -1,38 +1,13 @@
import { useEffect, useRef } from 'react'
import { useAuthStore } from '../stores/auth'
import { isAccessTokenStale } from '../utils/authRefresh'
// 前 5 次沿用原快速退避间隔;之后进入 60s 慢速重试并不再放弃,
// 服务重启或网络恢复后仍能自动重连(清理函数可随时取消定时器)。
const FAST_RECONNECT_ATTEMPTS = 5
const SLOW_RECONNECT_INTERVAL = 60_000
// token 过期前 30 秒即视为失效,给刷新留出余量。
const TOKEN_EXPIRY_SKEW_MS = 30_000
// decodeJwtExpiryMs 解析 JWT 的 exp 声明并换算成毫秒时间戳。
// 解析失败(非 JWT / 结构异常)返回 null,调用方据此放行重连。
function decodeJwtExpiryMs(token: string): number | null {
const segment = token.split('.')[1]
if (!segment) return null
try {
// JWT 使用 base64url 编码,需先还原字符集并补齐 padding。
const normalized = segment.replace(/-/g, '+').replace(/_/g, '/')
const padded = normalized.padEnd(Math.ceil(normalized.length / 4) * 4, '=')
const claims = JSON.parse(atob(padded)) as { exp?: unknown }
return typeof claims.exp === 'number' ? claims.exp * 1000 : null
} catch {
return null
}
}
// isTokenExpired 判断 token 是否已过期或即将过期。
function isTokenExpired(token: string): boolean {
const expiry = decodeJwtExpiryMs(token)
if (expiry === null) return false
return Date.now() >= expiry - TOKEN_EXPIRY_SKEW_MS
}
// useWebSocket opens a single connection to /api/ws and dispatches every
// message to the supplied handler. Auto-reconnects with back-off while the
// auth token is present; after the fast retries are exhausted it keeps a
@@ -68,7 +43,7 @@ export function useWebSocket(onEvent: (topic: string, payload: unknown) => void)
const open = () => {
if (closed) return
if (isTokenExpired(token)) {
if (isAccessTokenStale(token)) {
refreshExpiredToken()
return
}
@@ -92,7 +67,7 @@ export function useWebSocket(onEvent: (topic: string, payload: unknown) => void)
ws.onclose = () => {
if (closed) return
// token 过期时不要继续退避重试,交给刷新流程处理。
if (isTokenExpired(token)) {
if (isAccessTokenStale(token)) {
refreshExpiredToken()
return
}