fix: 修复6个代码质量问题
P1-01: 提取重复的角色层级定义为包级常量 - 将 roleHierarchy 提取为 roleHierarchyLevels 包级变量 - 消除重复定义 P1-02: 修复伪随机数用于加权选择 - 使用 math/rand 的线程安全随机数生成器替代时间戳 - 确保加权路由的均匀分布 P1-03: 修复 FailureRate 初始化计算错误 - 将成功时的恢复因子从 0.9 改为 0.5 - 加速失败后的恢复过程 P1-04: 为 DefaultIAMService 添加并发控制 - 添加 sync.RWMutex 保护 map 操作 - 确保所有服务方法的线程安全 P1-05: 修复 IP 伪造漏洞 - 添加 TrustedProxies 配置 - 只在来自可信代理时才使用 X-Forwarded-For P1-06: 修复限流 key 提取逻辑错误 - 从 Authorization header 中提取 Bearer token - 避免使用完整的 header 作为限流 key
This commit is contained in:
@@ -3,6 +3,7 @@ package router
|
||||
import (
|
||||
"context"
|
||||
"math"
|
||||
"math/rand"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -10,6 +11,9 @@ import (
|
||||
gwerror "lijiaoqiao/gateway/pkg/error"
|
||||
)
|
||||
|
||||
// 全局随机数生成器(线程安全)
|
||||
var globalRand = rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||
|
||||
// LoadBalancerStrategy 负载均衡策略
|
||||
type LoadBalancerStrategy string
|
||||
|
||||
@@ -142,7 +146,7 @@ func (r *Router) selectByWeight(candidates []string) (adapter.ProviderAdapter, e
|
||||
totalWeight += r.health[name].Weight
|
||||
}
|
||||
|
||||
randVal := float64(time.Now().UnixNano()) / float64(math.MaxInt64) * totalWeight
|
||||
randVal := globalRand.Float64() * totalWeight
|
||||
var cumulative float64
|
||||
|
||||
for _, name := range candidates {
|
||||
@@ -215,11 +219,17 @@ func (r *Router) RecordResult(ctx context.Context, providerName string, success
|
||||
|
||||
// 更新失败率
|
||||
if success {
|
||||
if health.FailureRate > 0 {
|
||||
health.FailureRate = health.FailureRate * 0.9 // 下降
|
||||
// 成功时快速恢复:使用0.5的下降因子加速恢复
|
||||
health.FailureRate = health.FailureRate * 0.5
|
||||
if health.FailureRate < 0.01 {
|
||||
health.FailureRate = 0
|
||||
}
|
||||
} else {
|
||||
health.FailureRate = health.FailureRate*0.9 + 0.1 // 上升
|
||||
// 失败时逐步上升
|
||||
health.FailureRate = health.FailureRate*0.9 + 0.1
|
||||
if health.FailureRate > 1 {
|
||||
health.FailureRate = 1
|
||||
}
|
||||
}
|
||||
|
||||
// 检查是否应该标记为不可用
|
||||
|
||||
Reference in New Issue
Block a user