feat: session 添加节流检查

This commit is contained in:
zdl
2025-10-24 17:09:42 +08:00
parent a92d556486
commit 72a009e1ae

View File

@@ -29,10 +29,32 @@ export const AuthProvider = ({ children }) => {
// ⚡ 使用 ref 保存最新的 isAuthenticated 值,避免事件监听器重复注册 // ⚡ 使用 ref 保存最新的 isAuthenticated 值,避免事件监听器重复注册
const isAuthenticatedRef = React.useRef(isAuthenticated); const isAuthenticatedRef = React.useRef(isAuthenticated);
// ⚡ 请求节流:记录上次请求时间,防止短时间内重复请求
const lastCheckTimeRef = React.useRef(0);
const MIN_CHECK_INTERVAL = 1000; // 最少间隔1秒
// 检查Session状态 // 检查Session状态
const checkSession = async () => { const checkSession = async () => {
// 节流检查
const now = Date.now();
const timeSinceLastCheck = now - lastCheckTimeRef.current;
if (timeSinceLastCheck < MIN_CHECK_INTERVAL) {
logger.warn('AuthContext', 'checkSession 请求被节流(防止频繁请求)', {
timeSinceLastCheck: `${timeSinceLastCheck}ms`,
minInterval: `${MIN_CHECK_INTERVAL}ms`,
reason: '距离上次请求间隔太短'
});
return;
}
lastCheckTimeRef.current = now;
try { try {
logger.debug('AuthContext', '检查Session状态'); logger.debug('AuthContext', '开始检查Session状态', {
timestamp: new Date().toISOString(),
timeSinceLastCheck: timeSinceLastCheck > 0 ? `${timeSinceLastCheck}ms` : '首次请求'
});
// 创建超时控制器 // 创建超时控制器
const controller = new AbortController(); const controller = new AbortController();