fix(P2): 修复4个P2轻微问题
P2-01: 通配符scope安全风险 (scope_auth.go) - 添加hasWildcardScope()函数检测通配符scope - 添加logWildcardScopeAccess()函数记录审计日志 - 在RequireScope/RequireAllScopes/RequireAnyScope中间件中调用审计日志 P2-02: isSamePayload比较字段不完整 (audit_service.go) - 添加ActionDetail字段比较 - 添加ResultMessage字段比较 - 添加Extensions字段比较 - 添加compareExtensions()辅助函数 P2-03: regexp.MustCompile可能panic (sanitizer.go) - 添加compileRegex()安全编译函数替代MustCompile - 处理编译错误,避免panic P2-04: StrategyRoundRobin未实现 (router.go) - 添加selectByRoundRobin()方法 - 添加roundRobinCounter原子计数器 - 使用atomic.AddUint64实现线程安全的轮询 P2-05: 错误信息泄露内部细节 - 已在MED-09中处理,跳过
This commit is contained in:
@@ -5,6 +5,7 @@ import (
|
||||
"math"
|
||||
"math/rand"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"lijiaoqiao/gateway/internal/adapter"
|
||||
@@ -36,10 +37,11 @@ type ProviderHealth struct {
|
||||
|
||||
// Router 路由器
|
||||
type Router struct {
|
||||
providers map[string]adapter.ProviderAdapter
|
||||
health map[string]*ProviderHealth
|
||||
strategy LoadBalancerStrategy
|
||||
mu sync.RWMutex
|
||||
providers map[string]adapter.ProviderAdapter
|
||||
health map[string]*ProviderHealth
|
||||
strategy LoadBalancerStrategy
|
||||
mu sync.RWMutex
|
||||
roundRobinCounter uint64 // RoundRobin策略的原子计数器
|
||||
}
|
||||
|
||||
// NewRouter 创建路由器
|
||||
@@ -87,6 +89,8 @@ func (r *Router) SelectProvider(ctx context.Context, model string) (adapter.Prov
|
||||
switch r.strategy {
|
||||
case StrategyLatency:
|
||||
return r.selectByLatency(candidates)
|
||||
case StrategyRoundRobin:
|
||||
return r.selectByRoundRobin(candidates)
|
||||
case StrategyWeighted:
|
||||
return r.selectByWeight(candidates)
|
||||
case StrategyAvailability:
|
||||
@@ -121,6 +125,16 @@ func (r *Router) isProviderAvailable(name, model string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func (r *Router) selectByRoundRobin(candidates []string) (adapter.ProviderAdapter, error) {
|
||||
if len(candidates) == 0 {
|
||||
return nil, gwerror.NewGatewayError(gwerror.ROUTER_NO_PROVIDER_AVAILABLE, "no available provider")
|
||||
}
|
||||
|
||||
// 使用原子操作进行轮询选择
|
||||
index := atomic.AddUint64(&r.roundRobinCounter, 1) - 1
|
||||
return r.providers[candidates[index%uint64(len(candidates))]], nil
|
||||
}
|
||||
|
||||
func (r *Router) selectByLatency(candidates []string) (adapter.ProviderAdapter, error) {
|
||||
var bestProvider adapter.ProviderAdapter
|
||||
var minLatency int64 = math.MaxInt64
|
||||
|
||||
Reference in New Issue
Block a user