mirror of
https://github.com/chenyme/grok2api.git
synced 2026-12-06 16:01:07 +00:00
Merge remote-tracking branch 'origin/main' into high_concurrency
# Conflicts: # backend/internal/infra/egress/manager.go
This commit is contained in:
commit
87f58a231e
17 files changed
+1055
-32
No files matched your search
@@ -31,6 +31,10 @@
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td width="200" align="center" valign="middle"><a href="https://www.krill-ai.com/register?invite=KJ2VGIRVAE"><img src="https://raw.githubusercontent.com/Krill-ai-org/krill-ai-static/refs/heads/main/krill-logo/Eng/250x150.png" alt="Krill AI" width="160"></a></td>
|
||||
<td valign="middle">Thanks to Krill AI for sponsoring this project! Krill provides fast, stable official API access to GPT, Claude, Gemini, and a wide range of Chinese models, along with enterprise customization, invoicing, and dedicated 7×16-hour technical support. Its specially adapted WebSocket connection also delivers exceptionally fast time to first token. Krill offers this project an exclusive discount: register through <a href="https://www.krill-ai.com/register?invite=KJ2VGIRVAE">this link</a> and enter the coupon code “grok2api” when ordering to receive 23% off your first Codex package purchase.</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="200" align="center" valign="middle"><a href="https://github.com/DEEIX-AI/DEEIX-Chat"><img src="frontend/public/sponner/deeix-chat_deeix-ai.png" alt="DEEIX AI / DEEIX Chat" width="160"></a></td>
|
||||
<td valign="middle">DEEIX-Chat is an open-source, self-hostable AI Chat platform for individuals, teams, and enterprises that need stable, long-term, unified access to multiple models. It brings models, conversations, files, tool calling, and administration together in one deployable and extensible system. Click <a href="https://github.com/DEEIX-AI/DEEIX-Chat">here</a> to start deploying.</td>
|
||||
</tr>
|
||||
|
||||
@@ -32,6 +32,10 @@
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td width="200" align="center" valign="middle"><a href="https://www.krill-ai.com/register?invite=KJ2VGIRVAE"><img src="https://raw.githubusercontent.com/Krill-ai-org/krill-ai-static/refs/heads/main/krill-logo/Eng/250x150.png" alt="Krill AI" width="160"></a></td>
|
||||
<td valign="middle">感谢 Krill AI 赞助了本项目!Krill 提供 GPT / Claude / Gemini / 多款国产模型的官方稳定极速的 API 中转服务,支持企业级定制、报销开票、7×16h 专属技术支持。更有独家适配的 WebSocket 链接方式,让您畅享极速首字速度。Krill 为本项目提供了特别优惠,使用<a href="https://www.krill-ai.com/register?invite=KJ2VGIRVAE">此链接</a>注册并在下订单时填写“grok2api”优惠码,首次购买套餐可以享受 Codex 77 折优惠!</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="200" align="center" valign="middle"><a href="https://github.com/DEEIX-AI/DEEIX-Chat"><img src="frontend/public/sponner/deeix-chat_deeix-ai.png" alt="DEEIX AI / DEEIX Chat" width="160"></a></td>
|
||||
<td valign="middle">DEEIX-Chat 是一款开源可部署的 AI Chat 平台,面向需要长期、稳定、统一使用多模型能力的个人、团队与企业,将模型、对话、文件、工具调用与后台管理整合为一套可部署、可扩展的系统。点击 <a href="https://github.com/DEEIX-AI/DEEIX-Chat">此处</a> 开始部署!</td>
|
||||
</tr>
|
||||
|
||||
@@ -286,6 +286,7 @@ func New(ctx context.Context, cfg config.Config, logger *slog.Logger) (*Applicat
|
||||
egressService := egressapp.NewService(egressRepo, cipher, infraegress.DefaultUserAgent, accountRepo)
|
||||
egressService.SetClearanceManager(egressManager)
|
||||
egressService.SetNodeProber(egressManager)
|
||||
egressService.SetOperationsConfigInvalidator(egressManager)
|
||||
clientKeyService := clientkeyapp.NewService(clientKeyRepo, rateLimiter, concurrency, cfg.ClientKeyDefaults.RPMLimit, cfg.ClientKeyDefaults.MaxConcurrent, cipher)
|
||||
auditService := auditapp.NewService(auditRepo, logger, cfg.Audit.BufferSize, cfg.Audit.BatchSize, cfg.Audit.FlushInterval.Value())
|
||||
auditService.UpdateWriterConfig(cfg.Audit.BatchSize, cfg.Audit.FlushInterval.Value(), cfg.Audit.CommitDelay.Value())
|
||||
|
||||
@@ -47,6 +47,10 @@ type NodeProber interface {
|
||||
ProbeEgressNode(context.Context, uint64) (domain.ProbeResult, error)
|
||||
}
|
||||
|
||||
type OperationsConfigInvalidator interface {
|
||||
InvalidateOperationsConfig()
|
||||
}
|
||||
|
||||
type SubscriptionSourceInput struct {
|
||||
Name string
|
||||
Scope domain.Scope
|
||||
@@ -80,6 +84,12 @@ type OperationsConfigInput struct {
|
||||
AutoAssignEnabled bool
|
||||
AutoBalanceEnabled bool
|
||||
AssignmentIntervalSeconds int
|
||||
Fallbacks map[domain.Scope]FallbackConfigInput
|
||||
}
|
||||
|
||||
type FallbackConfigInput struct {
|
||||
Mode domain.FallbackMode
|
||||
NodeID uint64
|
||||
}
|
||||
|
||||
func (s *Service) operationsRepository() (OperationsRepository, error) {
|
||||
@@ -95,6 +105,21 @@ func (s *Service) SetNodeProber(value NodeProber) {
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
func (s *Service) SetOperationsConfigInvalidator(value OperationsConfigInvalidator) {
|
||||
s.mu.Lock()
|
||||
s.operationsCache = value
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
func (s *Service) invalidateOperationsConfig() {
|
||||
s.mu.RLock()
|
||||
value := s.operationsCache
|
||||
s.mu.RUnlock()
|
||||
if value != nil {
|
||||
value.InvalidateOperationsConfig()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) nodeProber() NodeProber {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
@@ -332,10 +357,91 @@ func (s *Service) UpdateOperationsConfig(ctx context.Context, input OperationsCo
|
||||
if input.ProbeIntervalSeconds < 60 || input.ProbeIntervalSeconds > 86400 || input.AssignmentIntervalSeconds < 60 || input.AssignmentIntervalSeconds > 86400 {
|
||||
return domain.OperationsConfig{}, fmt.Errorf("%w: 自动任务间隔必须在 60 到 86400 秒之间", ErrInvalidInput)
|
||||
}
|
||||
return operations.SaveEgressOperationsConfig(ctx, domain.OperationsConfig{
|
||||
current, err := operations.GetEgressOperationsConfig(ctx)
|
||||
if err != nil {
|
||||
return domain.OperationsConfig{}, err
|
||||
}
|
||||
fallbacks := current.Fallbacks
|
||||
if input.Fallbacks != nil {
|
||||
fallbacks, err = s.validateFallbacks(ctx, current, input.Fallbacks)
|
||||
if err != nil {
|
||||
return domain.OperationsConfig{}, err
|
||||
}
|
||||
}
|
||||
saved, err := operations.SaveEgressOperationsConfig(ctx, domain.OperationsConfig{
|
||||
ProbeIntervalSeconds: input.ProbeIntervalSeconds, AutoAssignEnabled: input.AutoAssignEnabled,
|
||||
AutoBalanceEnabled: input.AutoBalanceEnabled, AssignmentIntervalSeconds: input.AssignmentIntervalSeconds, UpdatedAt: time.Now().UTC(),
|
||||
AutoBalanceEnabled: input.AutoBalanceEnabled, AssignmentIntervalSeconds: input.AssignmentIntervalSeconds,
|
||||
Fallbacks: fallbacks, UpdatedAt: time.Now().UTC(),
|
||||
})
|
||||
if err == nil {
|
||||
s.invalidateOperationsConfig()
|
||||
}
|
||||
return saved, err
|
||||
}
|
||||
|
||||
func (s *Service) validateFallbacks(ctx context.Context, current domain.OperationsConfig, input map[domain.Scope]FallbackConfigInput) (map[domain.Scope]domain.FallbackConfig, error) {
|
||||
result := make(map[domain.Scope]domain.FallbackConfig, 4)
|
||||
for _, scope := range []domain.Scope{domain.ScopeBuild, domain.ScopeWeb, domain.ScopeConsole, domain.ScopeWebAsset} {
|
||||
result[scope] = current.FallbackFor(scope)
|
||||
}
|
||||
for scope, fallback := range input {
|
||||
if !validScope(scope) {
|
||||
return nil, fmt.Errorf("%w: 回退作用域无效", ErrInvalidInput)
|
||||
}
|
||||
mode := fallback.Mode.Normalized()
|
||||
if !mode.IsValid() {
|
||||
return nil, fmt.Errorf("%w: 回退模式无效", ErrInvalidInput)
|
||||
}
|
||||
switch mode {
|
||||
case domain.FallbackModeNone, domain.FallbackModeDirect:
|
||||
if fallback.NodeID != 0 {
|
||||
return nil, fmt.Errorf("%w: 仅固定代理回退可以指定节点", ErrInvalidInput)
|
||||
}
|
||||
case domain.FallbackModeFixed:
|
||||
if fallback.NodeID == 0 {
|
||||
return nil, fmt.Errorf("%w: 固定代理回退必须指定节点", ErrInvalidInput)
|
||||
}
|
||||
node, err := s.repository.GetEgressNode(ctx, fallback.NodeID)
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, fmt.Errorf("%w: 固定回退节点不存在", ErrInvalidInput)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.validateFixedFallbackNode(scope, node, true); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
result[scope] = domain.FallbackConfig{Mode: mode, NodeID: fallback.NodeID}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (s *Service) validateFixedFallbackNode(scope domain.Scope, node domain.Node, rejectCooldown bool) error {
|
||||
if !domain.SupportsScope(node.Scope, scope) {
|
||||
return fmt.Errorf("%w: 固定回退节点与 %s 作用域不兼容", ErrInvalidInput, scope)
|
||||
}
|
||||
if !node.Enabled || strings.TrimSpace(node.EncryptedProxyURL) == "" {
|
||||
return fmt.Errorf("%w: 固定回退节点必须启用且配置代理地址", ErrInvalidInput)
|
||||
}
|
||||
if node.ProxyPool {
|
||||
return fmt.Errorf("%w: 固定回退节点不能使用代理池模式", ErrInvalidInput)
|
||||
}
|
||||
if rejectCooldown && node.CooldownUntil != nil && time.Now().UTC().Before(*node.CooldownUntil) {
|
||||
return fmt.Errorf("%w: 固定回退节点正在冷却", ErrInvalidInput)
|
||||
}
|
||||
proxyURL, err := s.cipher.Decrypt(node.EncryptedProxyURL)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: 固定回退节点代理配置无效", ErrInvalidInput)
|
||||
}
|
||||
proxyURL, err = NormalizeProxyURL(proxyURL)
|
||||
if err != nil || proxyURL == "" {
|
||||
return fmt.Errorf("%w: 固定回退节点代理地址无效", ErrInvalidInput)
|
||||
}
|
||||
if strings.Contains(proxyURL, ProxyAccountPlaceholder) {
|
||||
return fmt.Errorf("%w: 固定回退节点不能使用账号代理模板", ErrInvalidInput)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) applySourceInput(value domain.SubscriptionSource, input SubscriptionSourceInput, create bool) (domain.SubscriptionSource, error) {
|
||||
|
||||
@@ -51,6 +51,7 @@ type Service struct {
|
||||
browserUA string
|
||||
clearance ClearanceManager
|
||||
prober NodeProber
|
||||
operationsCache OperationsConfigInvalidator
|
||||
assignmentMu sync.Mutex
|
||||
lastAssignmentRun time.Time
|
||||
assignmentRunning bool
|
||||
@@ -153,6 +154,9 @@ func (s *Service) Update(ctx context.Context, id uint64, input Input) (domain.Pu
|
||||
if err != nil {
|
||||
return domain.PublicNode{}, err
|
||||
}
|
||||
if err := s.validateFallbackNodeUpdate(ctx, value); err != nil {
|
||||
return domain.PublicNode{}, err
|
||||
}
|
||||
if previousScope != value.Scope {
|
||||
if err := s.validateNodeBindingScope(ctx, value.ID, value.Scope); err != nil {
|
||||
return domain.PublicNode{}, err
|
||||
@@ -165,6 +169,26 @@ func (s *Service) Update(ctx context.Context, id uint64, input Input) (domain.Pu
|
||||
return s.publicNode(updated), err
|
||||
}
|
||||
|
||||
func (s *Service) validateFallbackNodeUpdate(ctx context.Context, node domain.Node) error {
|
||||
if s.operations == nil {
|
||||
return nil
|
||||
}
|
||||
config, err := s.operations.GetEgressOperationsConfig(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, scope := range []domain.Scope{domain.ScopeBuild, domain.ScopeWeb, domain.ScopeConsole, domain.ScopeWebAsset} {
|
||||
fallback := config.FallbackFor(scope)
|
||||
if fallback.Mode != domain.FallbackModeFixed || fallback.NodeID != node.ID {
|
||||
continue
|
||||
}
|
||||
if err := s.validateFixedFallbackNode(scope, node, false); err != nil {
|
||||
return fmt.Errorf("节点已配置为 %s 固定回退,无法应用当前修改: %w", scope, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) Delete(ctx context.Context, id uint64) error {
|
||||
err := s.repository.DeleteEgressNode(ctx, id)
|
||||
if errors.Is(err, repository.ErrNotFound) {
|
||||
@@ -172,6 +196,7 @@ func (s *Service) Delete(ctx context.Context, id uint64) error {
|
||||
}
|
||||
if err == nil {
|
||||
s.forgetClearance(id)
|
||||
s.invalidateOperationsConfig()
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -192,6 +217,7 @@ func (s *Service) DeleteMany(ctx context.Context, nodeIDs []uint64) (int, error)
|
||||
for _, id := range ids {
|
||||
s.forgetClearance(id)
|
||||
}
|
||||
s.invalidateOperationsConfig()
|
||||
return deleted, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -66,6 +66,7 @@ func (s *Service) syncSource(ctx context.Context, operations OperationsRepositor
|
||||
recordFailure()
|
||||
return ImportResult{}, ErrSubscriptionSync
|
||||
}
|
||||
s.invalidateOperationsConfig()
|
||||
if err := operations.UpdateEgressSourceSync(ctx, source.ID, now, nextSyncAt, imported, ""); err != nil {
|
||||
return ImportResult{}, err
|
||||
}
|
||||
|
||||
@@ -135,16 +135,76 @@ type PublicSubscriptionSource struct {
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
// OperationsConfig controls background probe and account assignment work. It
|
||||
// defaults to a conservative disabled state for assignment mutations.
|
||||
// FallbackMode controls what happens when no primary egress node can be
|
||||
// acquired for a request scope. The default is deliberately none so upgrades
|
||||
// preserve the existing fail-closed behavior.
|
||||
type FallbackMode string
|
||||
|
||||
const (
|
||||
FallbackModeNone FallbackMode = "none"
|
||||
FallbackModeDirect FallbackMode = "direct"
|
||||
FallbackModeFixed FallbackMode = "fixed"
|
||||
)
|
||||
|
||||
func (value FallbackMode) IsValid() bool {
|
||||
switch value {
|
||||
case FallbackModeNone, FallbackModeDirect, FallbackModeFixed:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// Normalized maps the zero value left by pre-fallback database rows to the
|
||||
// conservative disabled mode.
|
||||
func (value FallbackMode) Normalized() FallbackMode {
|
||||
if value == "" {
|
||||
return FallbackModeNone
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
type FallbackConfig struct {
|
||||
Mode FallbackMode
|
||||
NodeID uint64
|
||||
}
|
||||
|
||||
// OperationsConfig controls background probe, account assignment, and egress
|
||||
// fallback work. It defaults to a conservative disabled state for mutations
|
||||
// and fallback routing.
|
||||
type OperationsConfig struct {
|
||||
ProbeIntervalSeconds int
|
||||
AutoAssignEnabled bool
|
||||
AutoBalanceEnabled bool
|
||||
AssignmentIntervalSeconds int
|
||||
Fallbacks map[Scope]FallbackConfig
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
func DefaultOperationsConfig() OperationsConfig {
|
||||
return OperationsConfig{
|
||||
ProbeIntervalSeconds: 900,
|
||||
AssignmentIntervalSeconds: 300,
|
||||
Fallbacks: map[Scope]FallbackConfig{
|
||||
ScopeBuild: {Mode: FallbackModeNone},
|
||||
ScopeWeb: {Mode: FallbackModeNone},
|
||||
ScopeConsole: {Mode: FallbackModeNone},
|
||||
ScopeWebAsset: {Mode: FallbackModeNone},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// FallbackFor always returns a canonical, safe fallback value. It accepts
|
||||
// sparse maps so older callers and historical records remain compatible.
|
||||
func (value OperationsConfig) FallbackFor(scope Scope) FallbackConfig {
|
||||
fallback := value.Fallbacks[scope]
|
||||
fallback.Mode = fallback.Mode.Normalized()
|
||||
if fallback.Mode != FallbackModeFixed {
|
||||
fallback.NodeID = 0
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
// SupportsScope reports whether a node can serve requests for the supplied
|
||||
// scope. Console may intentionally reuse a Web browser proxy, and Web assets
|
||||
// inherit a Web node when no asset-specific node is required.
|
||||
|
||||
@@ -27,6 +27,7 @@ import (
|
||||
|
||||
const DefaultUserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36"
|
||||
const nodeSnapshotTTL = time.Second
|
||||
const operationsConfigSnapshotTTL = time.Second
|
||||
const proxyPoolRetryLimit = 2
|
||||
const clientCacheIdleTTL = 30 * time.Minute
|
||||
const clientCacheCleanupInterval = time.Minute
|
||||
@@ -90,6 +91,7 @@ type Manager struct {
|
||||
nodeMu sync.RWMutex
|
||||
clientMu sync.RWMutex
|
||||
clearanceMu sync.Mutex
|
||||
operationsMu sync.RWMutex
|
||||
clients map[clientCacheKey]cachedClient
|
||||
inflight sync.Map
|
||||
nodes map[domain.Scope]cachedNodeSnapshot
|
||||
@@ -99,6 +101,9 @@ type Manager struct {
|
||||
clientLoads singleflight.Group
|
||||
clientVersions map[uint64]uint64
|
||||
clientGeneration uint64
|
||||
operationsConfig cachedOperationsConfig
|
||||
operationsConfigLoad singleflight.Group
|
||||
operationsConfigVer uint64
|
||||
lastClientCleanup time.Time
|
||||
clearanceLoads singleflight.Group
|
||||
clearanceConfig ClearanceConfig
|
||||
@@ -129,6 +134,13 @@ type egressStateRepository interface {
|
||||
UpdateEgressNodeLastError(context.Context, uint64, string) error
|
||||
}
|
||||
|
||||
// operationsConfigRepository is optional so lightweight routing repositories
|
||||
// retain their narrow contract. The relational implementation supplies it,
|
||||
// allowing fallback policy to be read only when primary selection fails.
|
||||
type operationsConfigRepository interface {
|
||||
GetEgressOperationsConfig(context.Context) (domain.OperationsConfig, error)
|
||||
}
|
||||
|
||||
type cachedClient struct {
|
||||
client requestClient
|
||||
browser *browserClient
|
||||
@@ -146,6 +158,11 @@ type cachedNodeSnapshot struct {
|
||||
expiresAt time.Time
|
||||
}
|
||||
|
||||
type cachedOperationsConfig struct {
|
||||
value domain.OperationsConfig
|
||||
expiresAt time.Time
|
||||
}
|
||||
|
||||
func NewManager(repository repository.EgressRepository, cipher *security.Cipher) *Manager {
|
||||
return &Manager{
|
||||
repository: repository, cipher: cipher,
|
||||
@@ -315,23 +332,39 @@ func (m *Manager) acquire(ctx context.Context, scope domain.Scope, affinity stri
|
||||
if boundNodeID != 0 {
|
||||
selected, err := m.repository.GetEgressNode(ctx, boundNodeID)
|
||||
if err != nil {
|
||||
return nil, true, fmt.Errorf("读取绑定出口节点: %w", err)
|
||||
primaryErr := fmt.Errorf("读取绑定出口节点: %w", err)
|
||||
if !errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, true, primaryErr
|
||||
}
|
||||
return m.acquireUnavailableFallback(ctx, scope, affinity, allowDirect, encryptedCredentialCookies, managedClearance, primaryErr)
|
||||
}
|
||||
if !domain.SupportsScope(selected.Scope, scope) {
|
||||
return nil, true, fmt.Errorf("绑定出口节点 %d 与 %s 作用域不兼容", boundNodeID, scope)
|
||||
return m.acquireUnavailableFallback(ctx, scope, affinity, allowDirect, encryptedCredentialCookies, managedClearance, fmt.Errorf("绑定出口节点 %d 与 %s 作用域不兼容", boundNodeID, scope))
|
||||
}
|
||||
if !selected.Enabled {
|
||||
return nil, true, fmt.Errorf("绑定出口节点 %d 已禁用", boundNodeID)
|
||||
return m.acquireUnavailableFallback(ctx, scope, affinity, allowDirect, encryptedCredentialCookies, managedClearance, fmt.Errorf("绑定出口节点 %d 已禁用", boundNodeID))
|
||||
}
|
||||
if strings.TrimSpace(selected.EncryptedProxyURL) == "" {
|
||||
return nil, true, fmt.Errorf("绑定出口节点 %d 未配置代理地址", boundNodeID)
|
||||
return m.acquireUnavailableFallback(ctx, scope, affinity, allowDirect, encryptedCredentialCookies, managedClearance, fmt.Errorf("绑定出口节点 %d 未配置代理地址", boundNodeID))
|
||||
}
|
||||
proxyPool := m.isProxyPoolNode(selected)
|
||||
if !proxyPool && selected.CooldownUntil != nil && now.Before(*selected.CooldownUntil) {
|
||||
return nil, true, fmt.Errorf("绑定出口节点 %d 正在冷却", boundNodeID)
|
||||
return m.acquireUnavailableFallback(ctx, scope, affinity, allowDirect, encryptedCredentialCookies, managedClearance, fmt.Errorf("绑定出口节点 %d 正在冷却", boundNodeID))
|
||||
}
|
||||
return m.leaseForNode(ctx, scope, affinity, encryptedCredentialCookies, managedClearance, selected)
|
||||
}
|
||||
fallbackConfig, fallbackSupported, fallbackConfigErr := m.loadOperationsConfig(ctx, now)
|
||||
fallback := domain.FallbackConfig{Mode: domain.FallbackModeNone}
|
||||
reservedFallbackNodes := make(map[uint64]struct{}, 4)
|
||||
if fallbackConfigErr == nil && fallbackSupported {
|
||||
fallback = fallbackConfig.FallbackFor(scope)
|
||||
for _, fallbackScope := range []domain.Scope{domain.ScopeBuild, domain.ScopeWeb, domain.ScopeConsole, domain.ScopeWebAsset} {
|
||||
configuredFallback := fallbackConfig.FallbackFor(fallbackScope)
|
||||
if configuredFallback.Mode == domain.FallbackModeFixed && configuredFallback.NodeID != 0 {
|
||||
reservedFallbackNodes[configuredFallback.NodeID] = struct{}{}
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, candidateScope := range fallbackScopes(scope) {
|
||||
nodes, err := m.listNodes(ctx, candidateScope, now)
|
||||
if err != nil {
|
||||
@@ -342,6 +375,11 @@ func (m *Manager) acquire(ctx context.Context, scope domain.Scope, affinity stri
|
||||
if !node.Enabled {
|
||||
continue
|
||||
}
|
||||
// A fixed fallback is a reserved last resort, not another member of
|
||||
// the primary pool. It is validated again immediately before use.
|
||||
if _, reserved := reservedFallbackNodes[node.ID]; reserved {
|
||||
continue
|
||||
}
|
||||
configured = true
|
||||
proxyPool := m.isProxyPoolNode(node)
|
||||
if node.CooldownUntil == nil || !now.Before(*node.CooldownUntil) || proxyPool {
|
||||
@@ -357,8 +395,19 @@ func (m *Manager) acquire(ctx context.Context, scope domain.Scope, affinity stri
|
||||
}
|
||||
}
|
||||
if len(available) == 0 {
|
||||
primaryErr := error(nil)
|
||||
if configured {
|
||||
return nil, false, fmt.Errorf("当前没有可用的 %s 出口节点", scope)
|
||||
primaryErr = fmt.Errorf("当前没有可用的 %s 出口节点", scope)
|
||||
}
|
||||
lease, fallbackConfigured, applied, err := m.applyFallback(ctx, scope, affinity, allowDirect, encryptedCredentialCookies, managedClearance, primaryErr, fallback, fallbackSupported, fallbackConfigErr)
|
||||
if err != nil {
|
||||
return nil, fallbackConfigured, err
|
||||
}
|
||||
if applied {
|
||||
return lease, fallbackConfigured, nil
|
||||
}
|
||||
if primaryErr != nil {
|
||||
return nil, false, primaryErr
|
||||
}
|
||||
if !allowDirect {
|
||||
recordSelection(ctx, Selection{NodeName: "direct", Scope: scope})
|
||||
@@ -371,6 +420,154 @@ func (m *Manager) acquire(ctx context.Context, scope domain.Scope, affinity stri
|
||||
return m.leaseForNode(ctx, scope, affinity, encryptedCredentialCookies, managedClearance, selected)
|
||||
}
|
||||
|
||||
// acquireUnavailableFallback keeps the primary selection error when fallback
|
||||
// is disabled. A fixed fallback is never silently replaced with direct traffic
|
||||
// when it is invalid or unavailable.
|
||||
func (m *Manager) acquireUnavailableFallback(ctx context.Context, scope domain.Scope, affinity string, allowDirect bool, encryptedCredentialCookies string, managedClearance bool, primaryErr error) (*Lease, bool, error) {
|
||||
lease, configured, applied, err := m.acquireFallback(ctx, scope, affinity, allowDirect, encryptedCredentialCookies, managedClearance, primaryErr)
|
||||
if err != nil {
|
||||
return nil, configured, err
|
||||
}
|
||||
if applied {
|
||||
return lease, configured, nil
|
||||
}
|
||||
return nil, true, primaryErr
|
||||
}
|
||||
|
||||
// acquireFallback is called before an upstream request is written. Transport
|
||||
// failures are intentionally not retried through this path because replaying
|
||||
// a non-idempotent upstream request on a different IP can duplicate work.
|
||||
func (m *Manager) acquireFallback(ctx context.Context, scope domain.Scope, affinity string, allowDirect bool, encryptedCredentialCookies string, managedClearance bool, primaryErr error) (*Lease, bool, bool, error) {
|
||||
fallback, supported, err := m.fallbackFor(ctx, scope, time.Now().UTC())
|
||||
return m.applyFallback(ctx, scope, affinity, allowDirect, encryptedCredentialCookies, managedClearance, primaryErr, fallback, supported, err)
|
||||
}
|
||||
|
||||
func (m *Manager) applyFallback(ctx context.Context, scope domain.Scope, affinity string, allowDirect bool, encryptedCredentialCookies string, managedClearance bool, primaryErr error, fallback domain.FallbackConfig, supported bool, configErr error) (*Lease, bool, bool, error) {
|
||||
if configErr != nil {
|
||||
return nil, false, false, fallbackError(primaryErr, fmt.Errorf("读取出口回退配置: %w", configErr))
|
||||
}
|
||||
if !supported {
|
||||
return nil, false, false, nil
|
||||
}
|
||||
switch fallback.Mode {
|
||||
case domain.FallbackModeNone:
|
||||
return nil, false, false, nil
|
||||
case domain.FallbackModeDirect:
|
||||
if !allowDirect {
|
||||
recordSelection(ctx, Selection{NodeName: "direct", Scope: scope})
|
||||
return nil, false, true, nil
|
||||
}
|
||||
lease, _, err := m.leaseForNode(ctx, scope, affinity, encryptedCredentialCookies, managedClearance, domain.Node{ID: 0, Name: "direct", Scope: scope, Enabled: true, Health: 1})
|
||||
if err != nil {
|
||||
return nil, false, false, fallbackError(primaryErr, fmt.Errorf("获取本地直连回退: %w", err))
|
||||
}
|
||||
return lease, false, true, nil
|
||||
case domain.FallbackModeFixed:
|
||||
selected, err := m.fixedFallbackNode(ctx, scope, fallback.NodeID)
|
||||
if err != nil {
|
||||
return nil, false, false, fallbackError(primaryErr, err)
|
||||
}
|
||||
lease, _, err := m.leaseForNode(ctx, scope, affinity, encryptedCredentialCookies, managedClearance, selected)
|
||||
if err != nil {
|
||||
return nil, false, false, fallbackError(primaryErr, fmt.Errorf("获取固定回退节点 %d: %w", selected.ID, err))
|
||||
}
|
||||
return lease, true, true, nil
|
||||
default:
|
||||
return nil, false, false, fallbackError(primaryErr, fmt.Errorf("出口回退模式 %q 无效", fallback.Mode))
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Manager) fallbackFor(ctx context.Context, scope domain.Scope, now time.Time) (domain.FallbackConfig, bool, error) {
|
||||
config, supported, err := m.loadOperationsConfig(ctx, now)
|
||||
if err != nil || !supported {
|
||||
return domain.FallbackConfig{Mode: domain.FallbackModeNone}, supported, err
|
||||
}
|
||||
return config.FallbackFor(scope), true, nil
|
||||
}
|
||||
|
||||
func (m *Manager) loadOperationsConfig(ctx context.Context, now time.Time) (domain.OperationsConfig, bool, error) {
|
||||
configRepository, ok := m.repository.(operationsConfigRepository)
|
||||
if !ok {
|
||||
return domain.OperationsConfig{}, false, nil
|
||||
}
|
||||
m.operationsMu.RLock()
|
||||
cached := m.operationsConfig
|
||||
m.operationsMu.RUnlock()
|
||||
if !cached.expiresAt.IsZero() && now.Before(cached.expiresAt) {
|
||||
return cached.value, true, nil
|
||||
}
|
||||
loaded, err, _ := m.operationsConfigLoad.Do("operations", func() (any, error) {
|
||||
checkTime := time.Now().UTC()
|
||||
m.operationsMu.RLock()
|
||||
cached := m.operationsConfig
|
||||
m.operationsMu.RUnlock()
|
||||
if !cached.expiresAt.IsZero() && checkTime.Before(cached.expiresAt) {
|
||||
return cached.value, nil
|
||||
}
|
||||
m.operationsMu.RLock()
|
||||
version := m.operationsConfigVer
|
||||
m.operationsMu.RUnlock()
|
||||
value, err := configRepository.GetEgressOperationsConfig(ctx)
|
||||
if err != nil {
|
||||
return domain.OperationsConfig{}, err
|
||||
}
|
||||
m.operationsMu.Lock()
|
||||
if version == m.operationsConfigVer {
|
||||
m.operationsConfig = cachedOperationsConfig{value: value, expiresAt: checkTime.Add(operationsConfigSnapshotTTL)}
|
||||
}
|
||||
m.operationsMu.Unlock()
|
||||
return value, nil
|
||||
})
|
||||
if err != nil {
|
||||
return domain.OperationsConfig{}, true, err
|
||||
}
|
||||
return loaded.(domain.OperationsConfig), true, nil
|
||||
}
|
||||
|
||||
func (m *Manager) fixedFallbackNode(ctx context.Context, scope domain.Scope, nodeID uint64) (domain.Node, error) {
|
||||
if nodeID == 0 {
|
||||
return domain.Node{}, errors.New("固定回退节点未指定")
|
||||
}
|
||||
selected, err := m.repository.GetEgressNode(ctx, nodeID)
|
||||
if err != nil {
|
||||
return domain.Node{}, fmt.Errorf("读取固定回退节点 %d: %w", nodeID, err)
|
||||
}
|
||||
if !domain.SupportsScope(selected.Scope, scope) {
|
||||
return domain.Node{}, fmt.Errorf("固定回退节点 %d 与 %s 作用域不兼容", nodeID, scope)
|
||||
}
|
||||
if !selected.Enabled {
|
||||
return domain.Node{}, fmt.Errorf("固定回退节点 %d 已禁用", nodeID)
|
||||
}
|
||||
if selected.ProxyPool {
|
||||
return domain.Node{}, fmt.Errorf("固定回退节点 %d 使用代理池模式", nodeID)
|
||||
}
|
||||
if strings.TrimSpace(selected.EncryptedProxyURL) == "" {
|
||||
return domain.Node{}, fmt.Errorf("固定回退节点 %d 未配置代理地址", nodeID)
|
||||
}
|
||||
if selected.CooldownUntil != nil && time.Now().UTC().Before(*selected.CooldownUntil) {
|
||||
return domain.Node{}, fmt.Errorf("固定回退节点 %d 正在冷却", nodeID)
|
||||
}
|
||||
proxyURL, err := m.cipher.Decrypt(selected.EncryptedProxyURL)
|
||||
if err != nil {
|
||||
return domain.Node{}, fmt.Errorf("读取固定回退节点 %d 代理配置: %w", nodeID, err)
|
||||
}
|
||||
proxyURL, err = application.NormalizeProxyURL(proxyURL)
|
||||
if err != nil || proxyURL == "" {
|
||||
return domain.Node{}, fmt.Errorf("固定回退节点 %d 代理地址无效", nodeID)
|
||||
}
|
||||
if strings.Contains(proxyURL, application.ProxyAccountPlaceholder) {
|
||||
return domain.Node{}, fmt.Errorf("固定回退节点 %d 使用账号代理模板", nodeID)
|
||||
}
|
||||
return selected, nil
|
||||
}
|
||||
|
||||
func fallbackError(primaryErr, fallbackErr error) error {
|
||||
if primaryErr == nil {
|
||||
return fallbackErr
|
||||
}
|
||||
return fmt.Errorf("%w;出口回退不可用: %v", primaryErr, fallbackErr)
|
||||
}
|
||||
|
||||
func (m *Manager) leaseForNode(ctx context.Context, scope domain.Scope, affinity, encryptedCredentialCookies string, managedClearance bool, selected domain.Node) (*Lease, bool, error) {
|
||||
credentialCookies := ""
|
||||
if !managedClearance && scope != domain.ScopeBuild && strings.TrimSpace(encryptedCredentialCookies) != "" {
|
||||
@@ -584,6 +781,13 @@ func (m *Manager) replaceNodeSnapshotLocked(scope domain.Scope, values []domain.
|
||||
m.nodes[scope] = cachedNodeSnapshot{values: append([]domain.Node(nil), values...), expiresAt: expiresAt}
|
||||
}
|
||||
|
||||
func (m *Manager) InvalidateOperationsConfig() {
|
||||
m.operationsMu.Lock()
|
||||
m.operationsConfig = cachedOperationsConfig{}
|
||||
m.operationsConfigVer++
|
||||
m.operationsMu.Unlock()
|
||||
}
|
||||
|
||||
func fallbackScopes(scope domain.Scope) []domain.Scope {
|
||||
if scope == domain.ScopeWebAsset {
|
||||
return []domain.Scope{domain.ScopeWebAsset, domain.ScopeWeb}
|
||||
|
||||
@@ -334,6 +334,88 @@ func TestConfiguredCoolingAppNodesNeverFallBackToDirect(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnavailablePrimaryUsesConfiguredDirectFallback(t *testing.T) {
|
||||
cipher, err := security.NewCipher("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
until := time.Now().Add(time.Minute)
|
||||
config := domain.DefaultOperationsConfig()
|
||||
config.Fallbacks[domain.ScopeWeb] = domain.FallbackConfig{Mode: domain.FallbackModeDirect}
|
||||
manager := NewManager(fallbackEgressRepository{
|
||||
egressRepositoryTestStub: egressRepositoryTestStub{nodes: []domain.Node{{
|
||||
ID: 1, Name: "cooling", Scope: domain.ScopeWeb, Enabled: true, CooldownUntil: &until,
|
||||
}}},
|
||||
config: config,
|
||||
}, cipher)
|
||||
ctx, trace := WithTrace(context.Background())
|
||||
lease, err := manager.Acquire(ctx, domain.ScopeWeb, "account")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer lease.Release()
|
||||
if lease.NodeID != 0 || lease.NodeName != "direct" || lease.ProxyURL != "" {
|
||||
t.Fatalf("direct fallback lease = %#v", lease)
|
||||
}
|
||||
selection, ok := trace.Selection(domain.ScopeWeb)
|
||||
if !ok || selection.NodeID != 0 || selection.NodeName != "direct" || selection.Proxied {
|
||||
t.Fatalf("direct fallback selection = %#v, ok=%v", selection, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnavailableBuildPrimaryUsesConfiguredDirectFallbackTransport(t *testing.T) {
|
||||
until := time.Now().Add(time.Minute)
|
||||
config := domain.DefaultOperationsConfig()
|
||||
config.Fallbacks[domain.ScopeBuild] = domain.FallbackConfig{Mode: domain.FallbackModeDirect}
|
||||
manager := NewManager(fallbackEgressRepository{
|
||||
egressRepositoryTestStub: egressRepositoryTestStub{nodes: []domain.Node{{
|
||||
ID: 1, Name: "cooling", Scope: domain.ScopeBuild, Enabled: true, CooldownUntil: &until,
|
||||
}}},
|
||||
config: config,
|
||||
}, nil)
|
||||
ctx, trace := WithTrace(context.Background())
|
||||
lease, configured, err := manager.AcquireIfConfigured(ctx, domain.ScopeBuild, "account")
|
||||
if err != nil || configured || lease != nil {
|
||||
t.Fatalf("direct fallback transport lease=%#v configured=%v err=%v", lease, configured, err)
|
||||
}
|
||||
selection, ok := trace.Selection(domain.ScopeBuild)
|
||||
if !ok || selection.NodeID != 0 || selection.NodeName != "direct" || selection.Proxied {
|
||||
t.Fatalf("direct fallback selection = %#v, ok=%v", selection, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFixedFallbackIsReservedFromPrimarySelection(t *testing.T) {
|
||||
cipher, err := security.NewCipher("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
primaryURL, err := cipher.Encrypt("http://primary.example:8080")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fallbackURL, err := cipher.Encrypt("http://fallback.example:8080")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
config := domain.DefaultOperationsConfig()
|
||||
config.Fallbacks[domain.ScopeBuild] = domain.FallbackConfig{Mode: domain.FallbackModeFixed, NodeID: 2}
|
||||
manager := NewManager(fallbackEgressRepository{
|
||||
egressRepositoryTestStub: egressRepositoryTestStub{nodes: []domain.Node{
|
||||
{ID: 1, Name: "primary", Scope: domain.ScopeBuild, Enabled: true, Health: 1, EncryptedProxyURL: primaryURL},
|
||||
{ID: 2, Name: "fallback", Scope: domain.ScopeBuild, Enabled: true, Health: 1, EncryptedProxyURL: fallbackURL},
|
||||
}},
|
||||
config: config,
|
||||
}, cipher)
|
||||
lease, configured, err := manager.AcquireIfConfigured(context.Background(), domain.ScopeBuild, "reserved-fallback")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer lease.Release()
|
||||
if !configured || lease.NodeID != 1 {
|
||||
t.Fatalf("primary lease=%#v configured=%v", lease, configured)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDisabledConfiguredNodesAllowDirectFallback(t *testing.T) {
|
||||
manager := NewManager(egressRepositoryTestStub{nodes: []domain.Node{{
|
||||
ID: 1, Name: "disabled-proxy", Scope: domain.ScopeBuild, Enabled: false, Health: 1,
|
||||
@@ -547,6 +629,36 @@ func TestAcquireCredentialDoesNotFallbackWhenBoundNodeIsUnavailable(t *testing.T
|
||||
}
|
||||
}
|
||||
|
||||
func TestAcquireCredentialUsesConfiguredFixedFallbackWhenBoundNodeIsUnavailable(t *testing.T) {
|
||||
cipher, err := security.NewCipher("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
proxyURL, err := cipher.Encrypt("http://fixed-fallback.example:8080")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
config := domain.DefaultOperationsConfig()
|
||||
config.Fallbacks[domain.ScopeBuild] = domain.FallbackConfig{Mode: domain.FallbackModeFixed, NodeID: 2}
|
||||
manager := NewManager(fallbackEgressRepository{
|
||||
egressRepositoryTestStub: egressRepositoryTestStub{nodes: []domain.Node{
|
||||
{ID: 1, Name: "disabled", Scope: domain.ScopeBuild, Enabled: false},
|
||||
{ID: 2, Name: "fixed-fallback", Scope: domain.ScopeBuild, Enabled: true, Health: 1, EncryptedProxyURL: proxyURL},
|
||||
}},
|
||||
config: config,
|
||||
}, cipher)
|
||||
lease, err := manager.AcquireCredential(context.Background(), domain.ScopeBuild, accountdomain.Credential{
|
||||
ID: 42, Provider: accountdomain.ProviderBuild, EgressNodeID: 1,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer lease.Release()
|
||||
if lease.NodeID != 2 || lease.NodeName != "fixed-fallback" || lease.ProxyURL != "http://fixed-fallback.example:8080" {
|
||||
t.Fatalf("fixed fallback lease = %#v", lease)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFlareSolverrModeIgnoresCredentialCookie(t *testing.T) {
|
||||
cipher, err := security.NewCipher("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=")
|
||||
if err != nil {
|
||||
@@ -1369,8 +1481,64 @@ func TestEgressNodeSnapshotAvoidsRepeatedRepositoryReads(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestOperationsConfigSnapshotAvoidsRepeatedRepositoryReads(t *testing.T) {
|
||||
repository := &countingFallbackRepository{config: domain.DefaultOperationsConfig()}
|
||||
manager := NewManager(repository, nil)
|
||||
for range 2 {
|
||||
lease, configured, err := manager.AcquireIfConfigured(context.Background(), domain.ScopeBuild, "")
|
||||
if err != nil || configured || lease != nil {
|
||||
t.Fatalf("lease=%#v configured=%v err=%v", lease, configured, err)
|
||||
}
|
||||
}
|
||||
if repository.configCalls != 1 {
|
||||
t.Fatalf("operations config reads = %d, want 1", repository.configCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOperationsConfigSnapshotCanBeInvalidated(t *testing.T) {
|
||||
repository := &countingFallbackRepository{config: domain.DefaultOperationsConfig()}
|
||||
manager := NewManager(repository, nil)
|
||||
first, _, err := manager.fallbackFor(context.Background(), domain.ScopeWeb, time.Now().UTC())
|
||||
if err != nil || first.Mode != domain.FallbackModeNone {
|
||||
t.Fatalf("first fallback=%#v err=%v", first, err)
|
||||
}
|
||||
repository.config.Fallbacks[domain.ScopeWeb] = domain.FallbackConfig{Mode: domain.FallbackModeDirect}
|
||||
manager.InvalidateOperationsConfig()
|
||||
second, _, err := manager.fallbackFor(context.Background(), domain.ScopeWeb, time.Now().UTC())
|
||||
if err != nil || second.Mode != domain.FallbackModeDirect {
|
||||
t.Fatalf("second fallback=%#v err=%v", second, err)
|
||||
}
|
||||
if repository.configCalls != 2 {
|
||||
t.Fatalf("operations config reads = %d, want 2", repository.configCalls)
|
||||
}
|
||||
}
|
||||
|
||||
type egressRepositoryTestStub struct{ nodes []domain.Node }
|
||||
|
||||
type fallbackEgressRepository struct {
|
||||
egressRepositoryTestStub
|
||||
config domain.OperationsConfig
|
||||
configErr error
|
||||
}
|
||||
|
||||
type countingFallbackRepository struct {
|
||||
egressRepositoryTestStub
|
||||
config domain.OperationsConfig
|
||||
configCalls int
|
||||
}
|
||||
|
||||
func (r *countingFallbackRepository) GetEgressOperationsConfig(context.Context) (domain.OperationsConfig, error) {
|
||||
r.configCalls++
|
||||
return r.config, nil
|
||||
}
|
||||
|
||||
func (r fallbackEgressRepository) GetEgressOperationsConfig(context.Context) (domain.OperationsConfig, error) {
|
||||
if r.configErr != nil {
|
||||
return domain.OperationsConfig{}, r.configErr
|
||||
}
|
||||
return r.config, nil
|
||||
}
|
||||
|
||||
func managerHasClientForNode(manager *Manager, nodeID uint64) bool {
|
||||
manager.clientMu.Lock()
|
||||
defer manager.clientMu.Unlock()
|
||||
|
||||
@@ -577,6 +577,158 @@ func TestEgressOperationsMaintenanceRetriesAssignmentAfterFailure(t *testing.T)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEgressOperationsConfigPersistsFixedFallback(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database := openTestDatabase(t)
|
||||
nodes := NewEgressRepository(database)
|
||||
cipher := egressOperationsCipher(t)
|
||||
fixed := createHealthyEgressNode(t, ctx, nodes, cipher, "fixed-fallback", 0)
|
||||
service := egressapp.NewService(nodes, cipher, "test-browser")
|
||||
|
||||
saved, err := service.UpdateOperationsConfig(ctx, egressapp.OperationsConfigInput{
|
||||
ProbeIntervalSeconds: 900, AssignmentIntervalSeconds: 300,
|
||||
Fallbacks: map[egress.Scope]egressapp.FallbackConfigInput{
|
||||
egress.ScopeBuild: {Mode: egress.FallbackModeFixed, NodeID: fixed.ID},
|
||||
egress.ScopeWeb: {Mode: egress.FallbackModeDirect},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if fallback := saved.FallbackFor(egress.ScopeBuild); fallback.Mode != egress.FallbackModeFixed || fallback.NodeID != fixed.ID {
|
||||
t.Fatalf("saved Build fallback = %#v", fallback)
|
||||
}
|
||||
if fallback := saved.FallbackFor(egress.ScopeWeb); fallback.Mode != egress.FallbackModeDirect || fallback.NodeID != 0 {
|
||||
t.Fatalf("saved Web fallback = %#v", fallback)
|
||||
}
|
||||
if fallback := saved.FallbackFor(egress.ScopeConsole); fallback.Mode != egress.FallbackModeNone || fallback.NodeID != 0 {
|
||||
t.Fatalf("default Console fallback = %#v", fallback)
|
||||
}
|
||||
|
||||
stored, err := nodes.GetEgressOperationsConfig(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if fallback := stored.FallbackFor(egress.ScopeBuild); fallback.Mode != egress.FallbackModeFixed || fallback.NodeID != fixed.ID {
|
||||
t.Fatalf("stored Build fallback = %#v", fallback)
|
||||
}
|
||||
if fallback := stored.FallbackFor(egress.ScopeWeb); fallback.Mode != egress.FallbackModeDirect || fallback.NodeID != 0 {
|
||||
t.Fatalf("stored Web fallback = %#v", fallback)
|
||||
}
|
||||
updated, err := service.UpdateOperationsConfig(ctx, egressapp.OperationsConfigInput{
|
||||
ProbeIntervalSeconds: 900, AssignmentIntervalSeconds: 300,
|
||||
Fallbacks: map[egress.Scope]egressapp.FallbackConfigInput{
|
||||
egress.ScopeBuild: {Mode: egress.FallbackModeNone},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if fallback := updated.FallbackFor(egress.ScopeWeb); fallback.Mode != egress.FallbackModeDirect {
|
||||
t.Fatalf("sparse update reset Web fallback = %#v", fallback)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFixedFallbackReferenceIsProtectedAndClearedOnDelete(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database := openTestDatabase(t)
|
||||
nodes := NewEgressRepository(database)
|
||||
cipher := egressOperationsCipher(t)
|
||||
fixed := createHealthyEgressNode(t, ctx, nodes, cipher, "fixed-fallback", 0)
|
||||
service := egressapp.NewService(nodes, cipher, "test-browser")
|
||||
if _, err := service.UpdateOperationsConfig(ctx, egressapp.OperationsConfigInput{
|
||||
ProbeIntervalSeconds: 900, AssignmentIntervalSeconds: 300,
|
||||
Fallbacks: map[egress.Scope]egressapp.FallbackConfigInput{
|
||||
egress.ScopeBuild: {Mode: egress.FallbackModeFixed, NodeID: fixed.ID},
|
||||
},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := service.Update(ctx, fixed.ID, egressapp.Input{
|
||||
Name: fixed.Name, Scope: fixed.Scope, Enabled: false,
|
||||
}); !errors.Is(err, egressapp.ErrInvalidInput) || !strings.Contains(err.Error(), "固定回退") {
|
||||
t.Fatalf("disable fixed fallback error = %v", err)
|
||||
}
|
||||
if err := service.Delete(ctx, fixed.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stored, err := nodes.GetEgressOperationsConfig(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if fallback := stored.FallbackFor(egress.ScopeBuild); fallback.Mode != egress.FallbackModeNone || fallback.NodeID != 0 {
|
||||
t.Fatalf("deleted fallback reference = %#v", fallback)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubscriptionSyncClearsStaleFixedFallbackReference(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database := openTestDatabase(t)
|
||||
nodes := NewEgressRepository(database)
|
||||
cipher := egressOperationsCipher(t)
|
||||
source, err := nodes.CreateEgressSource(ctx, egress.SubscriptionSource{
|
||||
Name: "source", Scope: egress.ScopeBuild, Enabled: true, RefreshIntervalSeconds: 900,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
encryptedProxy, err := cipher.Encrypt("http://subscription.example:8080")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := nodes.UpsertEgressNodesFromSource(ctx, source.ID, []egress.Node{{
|
||||
Name: "subscription", Scope: egress.ScopeBuild, Enabled: true, SourceID: source.ID,
|
||||
SourceKey: "one", EncryptedProxyURL: encryptedProxy, Health: 1,
|
||||
}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
listed, err := nodes.ListEgressNodes(ctx, egress.ScopeBuild, repository.SortQuery{})
|
||||
if err != nil || len(listed) != 1 {
|
||||
t.Fatalf("subscription nodes=%#v err=%v", listed, err)
|
||||
}
|
||||
service := egressapp.NewService(nodes, cipher, "test-browser")
|
||||
if _, err := service.UpdateOperationsConfig(ctx, egressapp.OperationsConfigInput{
|
||||
ProbeIntervalSeconds: 900, AssignmentIntervalSeconds: 300,
|
||||
Fallbacks: map[egress.Scope]egressapp.FallbackConfigInput{
|
||||
egress.ScopeBuild: {Mode: egress.FallbackModeFixed, NodeID: listed[0].ID},
|
||||
},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := nodes.UpsertEgressNodesFromSource(ctx, source.ID, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stored, err := nodes.GetEgressOperationsConfig(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if fallback := stored.FallbackFor(egress.ScopeBuild); fallback.Mode != egress.FallbackModeNone || fallback.NodeID != 0 {
|
||||
t.Fatalf("stale subscription fallback reference = %#v", fallback)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEgressOperationsConfigRejectsUnsafeFixedFallback(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database := openTestDatabase(t)
|
||||
nodes := NewEgressRepository(database)
|
||||
cipher := egressOperationsCipher(t)
|
||||
pool := createHealthyEgressNode(t, ctx, nodes, cipher, "pool-fallback", 0)
|
||||
pool.ProxyPool = true
|
||||
if _, err := nodes.UpdateEgressNode(ctx, pool); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service := egressapp.NewService(nodes, cipher, "test-browser")
|
||||
_, err := service.UpdateOperationsConfig(ctx, egressapp.OperationsConfigInput{
|
||||
ProbeIntervalSeconds: 900, AssignmentIntervalSeconds: 300,
|
||||
Fallbacks: map[egress.Scope]egressapp.FallbackConfigInput{
|
||||
egress.ScopeBuild: {Mode: egress.FallbackModeFixed, NodeID: pool.ID},
|
||||
},
|
||||
})
|
||||
if !errors.Is(err, egressapp.ErrInvalidInput) || !strings.Contains(err.Error(), "代理池") {
|
||||
t.Fatalf("pool fallback error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
type retryingAssignmentRepository struct {
|
||||
*AccountRepository
|
||||
failNext bool
|
||||
|
||||
@@ -305,6 +305,9 @@ func (r *EgressRepository) UpsertEgressNodesFromSource(ctx context.Context, sour
|
||||
}).Error; err != nil {
|
||||
return mapError(err)
|
||||
}
|
||||
if err := clearInvalidEgressFallbackNodeReferences(tx); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return returned, err
|
||||
@@ -314,7 +317,7 @@ func (r *EgressRepository) GetEgressOperationsConfig(ctx context.Context) (egres
|
||||
var row egressOperationsConfigModel
|
||||
if err := r.db.db.WithContext(ctx).First(&row, 1).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return egress.OperationsConfig{ProbeIntervalSeconds: 900, AssignmentIntervalSeconds: 300}, nil
|
||||
return egress.DefaultOperationsConfig(), nil
|
||||
}
|
||||
return egress.OperationsConfig{}, mapError(err)
|
||||
}
|
||||
@@ -338,6 +341,9 @@ func (r *EgressRepository) DeleteEgressNode(ctx context.Context, id uint64) erro
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
if err := clearEgressFallbackNodeReferences(tx, []uint64{id}); err != nil {
|
||||
return err
|
||||
}
|
||||
result = tx.Delete(&egressNodeModel{}, id)
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
@@ -368,6 +374,9 @@ func (r *EgressRepository) DeleteEgressNodes(ctx context.Context, ids []uint64)
|
||||
}); result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
if err := clearEgressFallbackNodeReferences(tx, batch); err != nil {
|
||||
return err
|
||||
}
|
||||
result := tx.Where("id IN ?", batch).Delete(&egressNodeModel{})
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
@@ -379,6 +388,64 @@ func (r *EgressRepository) DeleteEgressNodes(ctx context.Context, ids []uint64)
|
||||
return int(deleted), mapError(err)
|
||||
}
|
||||
|
||||
func clearEgressFallbackNodeReferences(tx *gorm.DB, ids []uint64) error {
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
for _, columns := range [][2]string{
|
||||
{"build_fallback_mode", "build_fallback_node_id"},
|
||||
{"web_fallback_mode", "web_fallback_node_id"},
|
||||
{"console_fallback_mode", "console_fallback_node_id"},
|
||||
{"web_asset_fallback_mode", "web_asset_fallback_node_id"},
|
||||
} {
|
||||
if err := tx.Model(&egressOperationsConfigModel{}).
|
||||
Where("id = ? AND "+columns[1]+" IN ?", 1, ids).
|
||||
Updates(map[string]any{columns[0]: string(egress.FallbackModeNone), columns[1]: 0}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func clearInvalidEgressFallbackNodeReferences(tx *gorm.DB) error {
|
||||
var config egressOperationsConfigModel
|
||||
if err := tx.First(&config, 1).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
for _, fallback := range []struct {
|
||||
scope egress.Scope
|
||||
mode string
|
||||
nodeID uint64
|
||||
modeColumn, idColumn string
|
||||
}{
|
||||
{egress.ScopeBuild, config.BuildFallbackMode, config.BuildFallbackNodeID, "build_fallback_mode", "build_fallback_node_id"},
|
||||
{egress.ScopeWeb, config.WebFallbackMode, config.WebFallbackNodeID, "web_fallback_mode", "web_fallback_node_id"},
|
||||
{egress.ScopeConsole, config.ConsoleFallbackMode, config.ConsoleFallbackNodeID, "console_fallback_mode", "console_fallback_node_id"},
|
||||
{egress.ScopeWebAsset, config.WebAssetFallbackMode, config.WebAssetFallbackNodeID, "web_asset_fallback_mode", "web_asset_fallback_node_id"},
|
||||
} {
|
||||
if egress.FallbackMode(fallback.mode).Normalized() != egress.FallbackModeFixed {
|
||||
continue
|
||||
}
|
||||
var node egressNodeModel
|
||||
err := tx.First(&node, fallback.nodeID).Error
|
||||
valid := err == nil && node.Enabled && !node.ProxyPool && node.EncryptedProxyURL != "" && egress.SupportsScope(egress.Scope(node.Scope), fallback.scope)
|
||||
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return err
|
||||
}
|
||||
if valid {
|
||||
continue
|
||||
}
|
||||
if err := tx.Model(&egressOperationsConfigModel{}).Where("id = ?", 1).
|
||||
Updates(map[string]any{fallback.modeColumn: string(egress.FallbackModeNone), fallback.idColumn: 0}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *EgressRepository) assignedAccountCounts(ctx context.Context) (map[uint64]int, error) {
|
||||
type row struct {
|
||||
NodeID uint64
|
||||
@@ -452,13 +519,29 @@ func fromEgressSubscriptionSourceDomain(value egress.SubscriptionSource) egressS
|
||||
func toEgressOperationsConfigDomain(row egressOperationsConfigModel) egress.OperationsConfig {
|
||||
return egress.OperationsConfig{
|
||||
ProbeIntervalSeconds: row.ProbeIntervalSeconds, AutoAssignEnabled: row.AutoAssignEnabled, AutoBalanceEnabled: row.AutoBalanceEnabled,
|
||||
AssignmentIntervalSeconds: row.AssignmentIntervalSeconds, UpdatedAt: row.UpdatedAt,
|
||||
AssignmentIntervalSeconds: row.AssignmentIntervalSeconds,
|
||||
Fallbacks: map[egress.Scope]egress.FallbackConfig{
|
||||
egress.ScopeBuild: {Mode: egress.FallbackMode(row.BuildFallbackMode).Normalized(), NodeID: row.BuildFallbackNodeID},
|
||||
egress.ScopeWeb: {Mode: egress.FallbackMode(row.WebFallbackMode).Normalized(), NodeID: row.WebFallbackNodeID},
|
||||
egress.ScopeConsole: {Mode: egress.FallbackMode(row.ConsoleFallbackMode).Normalized(), NodeID: row.ConsoleFallbackNodeID},
|
||||
egress.ScopeWebAsset: {Mode: egress.FallbackMode(row.WebAssetFallbackMode).Normalized(), NodeID: row.WebAssetFallbackNodeID},
|
||||
},
|
||||
UpdatedAt: row.UpdatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func fromEgressOperationsConfigDomain(value egress.OperationsConfig) egressOperationsConfigModel {
|
||||
buildFallback := value.FallbackFor(egress.ScopeBuild)
|
||||
webFallback := value.FallbackFor(egress.ScopeWeb)
|
||||
consoleFallback := value.FallbackFor(egress.ScopeConsole)
|
||||
webAssetFallback := value.FallbackFor(egress.ScopeWebAsset)
|
||||
return egressOperationsConfigModel{
|
||||
ID: 1, ProbeIntervalSeconds: value.ProbeIntervalSeconds, AutoAssignEnabled: value.AutoAssignEnabled,
|
||||
AutoBalanceEnabled: value.AutoBalanceEnabled, AssignmentIntervalSeconds: value.AssignmentIntervalSeconds, UpdatedAt: value.UpdatedAt,
|
||||
AutoBalanceEnabled: value.AutoBalanceEnabled, AssignmentIntervalSeconds: value.AssignmentIntervalSeconds,
|
||||
BuildFallbackMode: string(buildFallback.Mode), BuildFallbackNodeID: buildFallback.NodeID,
|
||||
WebFallbackMode: string(webFallback.Mode), WebFallbackNodeID: webFallback.NodeID,
|
||||
ConsoleFallbackMode: string(consoleFallback.Mode), ConsoleFallbackNodeID: consoleFallback.NodeID,
|
||||
WebAssetFallbackMode: string(webAssetFallback.Mode), WebAssetFallbackNodeID: webAssetFallback.NodeID,
|
||||
UpdatedAt: value.UpdatedAt,
|
||||
}
|
||||
}
|
||||
@@ -514,6 +514,14 @@ type egressOperationsConfigModel struct {
|
||||
AutoAssignEnabled bool `gorm:"not null;default:false"`
|
||||
AutoBalanceEnabled bool `gorm:"not null;default:false"`
|
||||
AssignmentIntervalSeconds int `gorm:"not null;default:300;check:chk_egress_operations_config_assignment_interval,assignment_interval_seconds BETWEEN 60 AND 86400"`
|
||||
BuildFallbackMode string `gorm:"size:16;not null;default:none"`
|
||||
BuildFallbackNodeID uint64 `gorm:"not null;default:0"`
|
||||
WebFallbackMode string `gorm:"size:16;not null;default:none"`
|
||||
WebFallbackNodeID uint64 `gorm:"not null;default:0"`
|
||||
ConsoleFallbackMode string `gorm:"size:16;not null;default:none"`
|
||||
ConsoleFallbackNodeID uint64 `gorm:"not null;default:0"`
|
||||
WebAssetFallbackMode string `gorm:"size:16;not null;default:none"`
|
||||
WebAssetFallbackNodeID uint64 `gorm:"not null;default:0"`
|
||||
UpdatedAt time.Time `gorm:"not null"`
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ package egress
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -328,18 +329,55 @@ type probeBatchRequest struct {
|
||||
}
|
||||
|
||||
type operationsConfigRequest struct {
|
||||
ProbeIntervalSeconds int `json:"probeIntervalSeconds"`
|
||||
AutoAssignEnabled bool `json:"autoAssignEnabled"`
|
||||
AutoBalanceEnabled bool `json:"autoBalanceEnabled"`
|
||||
AssignmentIntervalSeconds int `json:"assignmentIntervalSeconds"`
|
||||
ProbeIntervalSeconds int `json:"probeIntervalSeconds"`
|
||||
AutoAssignEnabled bool `json:"autoAssignEnabled"`
|
||||
AutoBalanceEnabled bool `json:"autoBalanceEnabled"`
|
||||
AssignmentIntervalSeconds int `json:"assignmentIntervalSeconds"`
|
||||
Fallbacks map[string]operationsFallbackRequest `json:"fallbacks"`
|
||||
}
|
||||
|
||||
type operationsFallbackRequest struct {
|
||||
Mode string `json:"mode"`
|
||||
NodeID string `json:"nodeId"`
|
||||
}
|
||||
|
||||
type operationsConfigResponse struct {
|
||||
ProbeIntervalSeconds int `json:"probeIntervalSeconds"`
|
||||
AutoAssignEnabled bool `json:"autoAssignEnabled"`
|
||||
AutoBalanceEnabled bool `json:"autoBalanceEnabled"`
|
||||
AssignmentIntervalSeconds int `json:"assignmentIntervalSeconds"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
ProbeIntervalSeconds int `json:"probeIntervalSeconds"`
|
||||
AutoAssignEnabled bool `json:"autoAssignEnabled"`
|
||||
AutoBalanceEnabled bool `json:"autoBalanceEnabled"`
|
||||
AssignmentIntervalSeconds int `json:"assignmentIntervalSeconds"`
|
||||
Fallbacks map[string]operationsFallbackResponse `json:"fallbacks"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
type operationsFallbackResponse struct {
|
||||
Mode string `json:"mode"`
|
||||
NodeID string `json:"nodeId,omitempty"`
|
||||
}
|
||||
|
||||
func (value operationsConfigRequest) input() (egressapp.OperationsConfigInput, error) {
|
||||
result := egressapp.OperationsConfigInput{
|
||||
ProbeIntervalSeconds: value.ProbeIntervalSeconds, AutoAssignEnabled: value.AutoAssignEnabled,
|
||||
AutoBalanceEnabled: value.AutoBalanceEnabled, AssignmentIntervalSeconds: value.AssignmentIntervalSeconds,
|
||||
}
|
||||
if value.Fallbacks == nil {
|
||||
return result, nil
|
||||
}
|
||||
result.Fallbacks = make(map[egressdomain.Scope]egressapp.FallbackConfigInput, len(value.Fallbacks))
|
||||
for rawScope, fallback := range value.Fallbacks {
|
||||
nodeID := uint64(0)
|
||||
if strings.TrimSpace(fallback.NodeID) != "" {
|
||||
parsed, err := strconv.ParseUint(fallback.NodeID, 10, 64)
|
||||
if err != nil || parsed == 0 {
|
||||
return egressapp.OperationsConfigInput{}, fmt.Errorf("%w: 固定回退节点 ID 无效", egressapp.ErrInvalidInput)
|
||||
}
|
||||
nodeID = parsed
|
||||
}
|
||||
result.Fallbacks[egressdomain.Scope(rawScope)] = egressapp.FallbackConfigInput{
|
||||
Mode: egressdomain.FallbackMode(strings.TrimSpace(fallback.Mode)), NodeID: nodeID,
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (value sourceRequest) input() egressapp.SubscriptionSourceInput {
|
||||
@@ -358,9 +396,19 @@ func newSourceResponse(value egressdomain.PublicSubscriptionSource) sourceRespon
|
||||
}
|
||||
|
||||
func newOperationsConfigResponse(value egressdomain.OperationsConfig) operationsConfigResponse {
|
||||
fallbacks := make(map[string]operationsFallbackResponse, 4)
|
||||
for _, scope := range []egressdomain.Scope{egressdomain.ScopeBuild, egressdomain.ScopeWeb, egressdomain.ScopeConsole, egressdomain.ScopeWebAsset} {
|
||||
fallback := value.FallbackFor(scope)
|
||||
item := operationsFallbackResponse{Mode: string(fallback.Mode)}
|
||||
if fallback.NodeID != 0 {
|
||||
item.NodeID = strconv.FormatUint(fallback.NodeID, 10)
|
||||
}
|
||||
fallbacks[string(scope)] = item
|
||||
}
|
||||
return operationsConfigResponse{
|
||||
ProbeIntervalSeconds: value.ProbeIntervalSeconds, AutoAssignEnabled: value.AutoAssignEnabled,
|
||||
AutoBalanceEnabled: value.AutoBalanceEnabled, AssignmentIntervalSeconds: value.AssignmentIntervalSeconds, UpdatedAt: value.UpdatedAt,
|
||||
AutoBalanceEnabled: value.AutoBalanceEnabled, AssignmentIntervalSeconds: value.AssignmentIntervalSeconds,
|
||||
Fallbacks: fallbacks, UpdatedAt: value.UpdatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -497,10 +545,12 @@ func (h *Handler) updateOperationsConfig(c *gin.Context) {
|
||||
response.Error(c, http.StatusBadRequest, "invalidRequest", "请求参数无效")
|
||||
return
|
||||
}
|
||||
value, err := h.service.UpdateOperationsConfig(c.Request.Context(), egressapp.OperationsConfigInput{
|
||||
ProbeIntervalSeconds: request.ProbeIntervalSeconds, AutoAssignEnabled: request.AutoAssignEnabled,
|
||||
AutoBalanceEnabled: request.AutoBalanceEnabled, AssignmentIntervalSeconds: request.AssignmentIntervalSeconds,
|
||||
})
|
||||
input, err := request.input()
|
||||
if err != nil {
|
||||
h.writeError(c, err)
|
||||
return
|
||||
}
|
||||
value, err := h.service.UpdateOperationsConfig(c.Request.Context(), input)
|
||||
if err != nil {
|
||||
h.writeError(c, err)
|
||||
return
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package egress
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
egressapp "github.com/chenyme/grok2api/backend/internal/application/egress"
|
||||
egressdomain "github.com/chenyme/grok2api/backend/internal/domain/egress"
|
||||
)
|
||||
|
||||
func TestOperationsConfigRequestParsesFallbacks(t *testing.T) {
|
||||
input, err := (operationsConfigRequest{
|
||||
ProbeIntervalSeconds: 900, AssignmentIntervalSeconds: 300,
|
||||
Fallbacks: map[string]operationsFallbackRequest{
|
||||
"grok_build": {Mode: "fixed", NodeID: "42"},
|
||||
"grok_web": {Mode: "direct"},
|
||||
},
|
||||
}).input()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if fallback := input.Fallbacks[egressdomain.ScopeBuild]; fallback.Mode != egressdomain.FallbackModeFixed || fallback.NodeID != 42 {
|
||||
t.Fatalf("Build fallback = %#v", fallback)
|
||||
}
|
||||
if fallback := input.Fallbacks[egressdomain.ScopeWeb]; fallback.Mode != egressdomain.FallbackModeDirect || fallback.NodeID != 0 {
|
||||
t.Fatalf("Web fallback = %#v", fallback)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOperationsConfigRequestRejectsInvalidFallbackNodeID(t *testing.T) {
|
||||
_, err := (operationsConfigRequest{
|
||||
Fallbacks: map[string]operationsFallbackRequest{"grok_build": {Mode: "fixed", NodeID: "zero"}},
|
||||
}).input()
|
||||
if !errors.Is(err, egressapp.ErrInvalidInput) {
|
||||
t.Fatalf("invalid node ID error = %v", err)
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,9 @@ import {
|
||||
testEgressNodes,
|
||||
updateEgressOperationsConfig,
|
||||
updateEgressSource,
|
||||
type EgressFallbackConfigDTO,
|
||||
type EgressFallbackMode,
|
||||
type EgressNodeDTO,
|
||||
type EgressOperationsConfigDTO,
|
||||
type EgressScope,
|
||||
type EgressSourceDTO,
|
||||
@@ -46,17 +49,40 @@ const emptyImport: ImportForm = { name: "", scope: "grok_build", accountCapacity
|
||||
// Eight probes run concurrently and each can take up to 15 seconds. Keeping a
|
||||
// request to 32 nodes leaves enough headroom for the admin HTTP timeout.
|
||||
const egressProbeBatchSize = 32;
|
||||
const fallbackScopes: EgressScope[] = ["grok_build", "grok_web", "grok_console", "grok_web_asset"];
|
||||
const fallbackDescriptionKeys: Record<EgressScope, string> = {
|
||||
grok_build: "settings.egress.fallbackBuildHelp",
|
||||
grok_web: "settings.egress.fallbackWebHelp",
|
||||
grok_console: "settings.egress.fallbackConsoleHelp",
|
||||
grok_web_asset: "settings.egress.fallbackWebAssetHelp",
|
||||
};
|
||||
|
||||
function defaultFallbacks(): Record<EgressScope, EgressFallbackConfigDTO> {
|
||||
return {
|
||||
grok_build: { mode: "none" }, grok_web: { mode: "none" },
|
||||
grok_console: { mode: "none" }, grok_web_asset: { mode: "none" },
|
||||
};
|
||||
}
|
||||
|
||||
const defaultOperationsForm: Omit<EgressOperationsConfigDTO, "updatedAt"> = {
|
||||
probeIntervalSeconds: 900, autoAssignEnabled: false, autoBalanceEnabled: false, assignmentIntervalSeconds: 300,
|
||||
probeIntervalSeconds: 900, autoAssignEnabled: false, autoBalanceEnabled: false, assignmentIntervalSeconds: 300, fallbacks: defaultFallbacks(),
|
||||
};
|
||||
|
||||
function operationsFormFrom(value?: EgressOperationsConfigDTO): Omit<EgressOperationsConfigDTO, "updatedAt"> {
|
||||
if (!value) return defaultOperationsForm;
|
||||
if (!value) return { ...defaultOperationsForm, fallbacks: defaultFallbacks() };
|
||||
|
||||
const defaults = defaultFallbacks();
|
||||
return {
|
||||
probeIntervalSeconds: value.probeIntervalSeconds,
|
||||
autoAssignEnabled: value.autoAssignEnabled,
|
||||
autoBalanceEnabled: value.autoBalanceEnabled,
|
||||
assignmentIntervalSeconds: value.assignmentIntervalSeconds,
|
||||
fallbacks: {
|
||||
grok_build: { ...defaults.grok_build, ...value.fallbacks.grok_build },
|
||||
grok_web: { ...defaults.grok_web, ...value.fallbacks.grok_web },
|
||||
grok_console: { ...defaults.grok_console, ...value.fallbacks.grok_console },
|
||||
grok_web_asset: { ...defaults.grok_web_asset, ...value.fallbacks.grok_web_asset },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -83,6 +109,7 @@ export function EgressOperations({ scopeLabel }: { scopeLabel: (scope: EgressSco
|
||||
const [operationsDraft, setOperationsDraft] = useState<Omit<EgressOperationsConfigDTO, "updatedAt"> | null>(null);
|
||||
const sourcesQuery = useQuery({ queryKey: ["egress-sources"], queryFn: listEgressSources });
|
||||
const operationsQuery = useQuery({ queryKey: ["egress-operations"], queryFn: getEgressOperationsConfig });
|
||||
const nodesQuery = useQuery({ queryKey: ["egress-nodes", "fallback-options"], queryFn: () => listEgressNodes() });
|
||||
const operationsForm = operationsDraft ?? operationsFormFrom(operationsQuery.data);
|
||||
|
||||
const invalidate = () => {
|
||||
@@ -142,6 +169,20 @@ export function EgressOperations({ scopeLabel }: { scopeLabel: (scope: EgressSco
|
||||
setSourceEditing(value);
|
||||
}
|
||||
|
||||
function setFallback(scope: EgressScope, fallback: EgressFallbackConfigDTO) {
|
||||
setOperationsDraft({ ...operationsForm, fallbacks: { ...operationsForm.fallbacks, [scope]: fallback } });
|
||||
}
|
||||
|
||||
function setFallbackMode(scope: EgressScope, mode: EgressFallbackMode) {
|
||||
const candidates = fallbackNodeCandidates(nodesQuery.data?.items ?? [], scope);
|
||||
const current = operationsForm.fallbacks[scope];
|
||||
const currentCandidate = candidates.find((node) => node.id === current.nodeId);
|
||||
setFallback(scope, {
|
||||
mode,
|
||||
nodeId: mode === "fixed" ? (currentCandidate?.id ?? candidates[0]?.id) : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="space-y-8">
|
||||
<div className="space-y-3">
|
||||
@@ -165,6 +206,49 @@ export function EgressOperations({ scopeLabel }: { scopeLabel: (scope: EgressSco
|
||||
<AutomationRow controlId="egress-auto-balance" label={t("settings.egress.autoBalance")} description={t("settings.egress.autoBalanceHelp")}>
|
||||
<div className="flex h-8 items-center"><Switch id="egress-auto-balance" checked={operationsForm.autoBalanceEnabled} onCheckedChange={(autoBalanceEnabled) => setOperationsDraft({ ...operationsForm, autoBalanceEnabled })} /></div>
|
||||
</AutomationRow>
|
||||
<div className="pt-4">
|
||||
<div className="flex items-center gap-1.5 px-0.5">
|
||||
<h3 className="text-sm font-medium tracking-tight">{t("settings.egress.fallback")}</h3>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild><button type="button" className="text-muted-foreground transition-colors hover:text-foreground" aria-label={t("settings.egress.fallbackHelp")}><CircleHelp className="size-3.5" /></button></TooltipTrigger>
|
||||
<TooltipContent className="max-w-80">{t("settings.egress.fallbackHelp")}</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
<div className="mt-3 space-y-2">
|
||||
{fallbackScopes.map((scope) => {
|
||||
const fallback = operationsForm.fallbacks[scope];
|
||||
const candidates = fallbackNodeCandidates(nodesQuery.data?.items ?? [], scope);
|
||||
const selectedAvailable = candidates.some((node) => node.id === fallback.nodeId);
|
||||
return (
|
||||
<div className="grid min-w-0 gap-2.5 py-1 sm:grid-cols-[minmax(0,2fr)_minmax(0,1fr)] sm:items-center sm:gap-8" key={scope}>
|
||||
<div className="min-w-0">
|
||||
<div className="flex min-h-5 items-center"><Label className="text-xs font-medium">{scopeLabel(scope)}</Label></div>
|
||||
<p className="mt-1 max-w-xl text-xs leading-5 text-muted-foreground">{t(fallbackDescriptionKeys[scope])}</p>
|
||||
</div>
|
||||
<div className={fallback.mode === "fixed" ? "grid min-w-0 gap-2 sm:grid-cols-2" : "grid min-w-0"}>
|
||||
<Select value={fallback.mode} onValueChange={(mode) => setFallbackMode(scope, mode as EgressFallbackMode)}>
|
||||
<SelectTrigger aria-label={t("settings.egress.fallbackMode", { scope: scopeLabel(scope) })}><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="none">{t("settings.egress.fallbackNone")}</SelectItem>
|
||||
<SelectItem value="direct">{t("settings.egress.fallbackDirect")}</SelectItem>
|
||||
<SelectItem value="fixed" disabled={candidates.length === 0}>{t("settings.egress.fallbackFixed")}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{fallback.mode === "fixed" ? (
|
||||
<Select value={selectedAvailable ? (fallback.nodeId ?? "unavailable") : "unavailable"} disabled={candidates.length === 0} onValueChange={(nodeId) => setFallback(scope, { mode: "fixed", nodeId })}>
|
||||
<SelectTrigger aria-label={t("settings.egress.fallbackNode", { scope: scopeLabel(scope) })}><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
{!selectedAvailable ? <SelectItem value="unavailable" disabled>{t("settings.egress.fallbackNodeUnavailable")}</SelectItem> : null}
|
||||
{candidates.map((node) => <SelectItem key={node.id} value={node.id}>{node.name} ({scopeLabel(node.scope)})</SelectItem>)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -236,6 +320,18 @@ export function EgressOperations({ scopeLabel }: { scopeLabel: (scope: EgressSco
|
||||
);
|
||||
}
|
||||
|
||||
function fallbackNodeCandidates(nodes: EgressNodeDTO[], scope: EgressScope): EgressNodeDTO[] {
|
||||
return nodes.filter((node) => node.enabled && node.proxyConfigured && !node.proxyPool && !node.accountBoundProxy && !nodeCooling(node) && supportsFallbackScope(node.scope, scope));
|
||||
}
|
||||
|
||||
function nodeCooling(node: EgressNodeDTO): boolean {
|
||||
return node.cooldownUntil !== undefined && Date.parse(node.cooldownUntil) > Date.now();
|
||||
}
|
||||
|
||||
function supportsFallbackScope(nodeScope: EgressScope, requestScope: EgressScope): boolean {
|
||||
return nodeScope === requestScope || ((requestScope === "grok_console" || requestScope === "grok_web_asset") && nodeScope === "grok_web");
|
||||
}
|
||||
|
||||
function ScopeSelect({ value, onChange, scopeLabel }: { value: EgressScope; onChange: (value: EgressScope) => void; scopeLabel: (scope: EgressScope) => string }) {
|
||||
return <Select value={value} onValueChange={(next) => onChange(next as EgressScope)}><SelectTrigger><SelectValue /></SelectTrigger><SelectContent>{(["grok_build", "grok_web", "grok_console", "grok_web_asset"] as EgressScope[]).map((scope) => <SelectItem key={scope} value={scope}>{scopeLabel(scope)}</SelectItem>)}</SelectContent></Select>;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { apiRequest } from "@/shared/api/client";
|
||||
import { createObjectDecoder, decodeBooleanResult, hasShape, isArrayOf, isBoolean, isNumber, isOneOf, isOptional, isString } from "@/shared/api/decoder";
|
||||
import { createObjectDecoder, decodeBooleanResult, hasShape, isArrayOf, isBoolean, isNumber, isOneOf, isOptional, isRecordOf, isString } from "@/shared/api/decoder";
|
||||
import type { SortOrder } from "@/shared/lib/table-sort";
|
||||
|
||||
export type SettingsConfigDTO = {
|
||||
@@ -48,6 +48,8 @@ export type EgressNodeInput = {
|
||||
};
|
||||
|
||||
export type EgressScope = "grok_build" | "grok_web" | "grok_console" | "grok_web_asset";
|
||||
export type EgressFallbackMode = "none" | "direct" | "fixed";
|
||||
export type EgressFallbackConfigDTO = { mode: EgressFallbackMode; nodeId?: string };
|
||||
export type EgressNodeListDTO = { items: EgressNodeDTO[]; defaultUserAgents: Record<EgressScope, string> };
|
||||
export type EgressSourceDTO = {
|
||||
id: string; name: string; scope: EgressScope; enabled: boolean; urlConfigured: boolean;
|
||||
@@ -60,7 +62,7 @@ export type EgressSourceInput = {
|
||||
};
|
||||
export type EgressOperationsConfigDTO = {
|
||||
probeIntervalSeconds: number; autoAssignEnabled: boolean; autoBalanceEnabled: boolean;
|
||||
assignmentIntervalSeconds: number; updatedAt: string;
|
||||
assignmentIntervalSeconds: number; fallbacks: Record<EgressScope, EgressFallbackConfigDTO>; updatedAt: string;
|
||||
};
|
||||
export type EgressImportResultDTO = { imported: number; skipped: number };
|
||||
export type EgressProbeResultDTO = { status: "unknown" | "healthy" | "unhealthy"; testedAt: string; latencyMs: number; exitIp?: string; error?: string };
|
||||
@@ -176,8 +178,10 @@ const decodeEgressSourceList = createObjectDecoder<{ items: EgressSourceDTO[] }>
|
||||
const decodeEgressImportResult = createObjectDecoder<EgressImportResultDTO>("egress import result", { imported: isNumber, skipped: isNumber });
|
||||
const decodeEgressProbeBatchResult = createObjectDecoder<EgressProbeBatchResultDTO>("egress probe result", { requested: isNumber, healthy: isNumber, unhealthy: isNumber });
|
||||
const decodeEgressRebalanceResult = createObjectDecoder<EgressRebalanceResultDTO>("egress rebalance result", { assigned: isNumber, rebalanced: isNumber, unplaced: isNumber });
|
||||
const egressFallbackConfigValidator = hasShape({ mode: isOneOf("none", "direct", "fixed"), nodeId: isOptional(isString) });
|
||||
const decodeEgressOperationsConfig = createObjectDecoder<EgressOperationsConfigDTO>("egress operations config", {
|
||||
probeIntervalSeconds: isNumber, autoAssignEnabled: isBoolean, autoBalanceEnabled: isBoolean, assignmentIntervalSeconds: isNumber, updatedAt: isString,
|
||||
probeIntervalSeconds: isNumber, autoAssignEnabled: isBoolean, autoBalanceEnabled: isBoolean, assignmentIntervalSeconds: isNumber,
|
||||
fallbacks: isRecordOf(egressFallbackConfigValidator), updatedAt: isString,
|
||||
});
|
||||
|
||||
export function getSettings(): Promise<SettingsSnapshotDTO> {
|
||||
|
||||
@@ -1486,6 +1486,13 @@ Object.assign(resources.en.translation.settings.egress as unknown as Record<stri
|
||||
assignmentInterval: "Account assignment interval", assignmentIntervalHelp: "How often to check account bindings and available node capacity.",
|
||||
autoAssign: "Automatically bind accounts", autoAssignHelp: "Assign accounts without a proxy binding to available nodes automatically.",
|
||||
autoBalance: "Automatically balance accounts", autoBalanceHelp: "Redistribute automatically bound accounts across available nodes; manual bindings remain unchanged.",
|
||||
fallback: "Egress fallback", fallbackHelp: "Used only when no primary node can be acquired before an upstream request is sent. Fixed fallback nodes must be enabled, non-pool proxies.",
|
||||
fallbackBuildHelp: "Fallback used when no Grok Build primary egress is available.",
|
||||
fallbackWebHelp: "Fallback used when no Grok Web primary egress is available.",
|
||||
fallbackConsoleHelp: "Fallback used when no Grok Console primary egress is available.",
|
||||
fallbackWebAssetHelp: "Fallback used when no Grok Web asset egress is available.",
|
||||
fallbackMode: "Fallback mode for {{scope}}", fallbackNone: "Do not fall back", fallbackDirect: "Local direct", fallbackFixed: "Fixed proxy",
|
||||
fallbackNode: "Fixed fallback proxy for {{scope}}", fallbackNodeUnavailable: "Configured node is unavailable",
|
||||
refreshInterval: "Subscription refresh interval (seconds)", proxyList: "Proxy list",
|
||||
search: "Search proxy nodes", assigned: "Assigned", unassigned: "Unassigned", noMatches: "No proxy nodes match the current filters", selectVisible: "Select filtered proxy nodes",
|
||||
batchDeleted: "Deleted {{deleted}} proxy nodes", batchDeleteTitle: "Delete {{count}} selected proxy nodes?", batchDeleteDescription: "This deletes the selected nodes and unbinds {{accounts}} associated accounts. This cannot be undone.",
|
||||
@@ -1516,6 +1523,18 @@ Object.assign(resources["zh-CN"].translation.settings.egress as unknown as Recor
|
||||
autoAssignHelp: "将尚未绑定代理的账号自动分配到可用节点。",
|
||||
autoBalance: "自动均衡账号",
|
||||
autoBalanceHelp: "在可用节点之间重新分配自动绑定的账号;手动绑定不受影响。",
|
||||
fallback: "出口回退",
|
||||
fallbackHelp: "仅在请求尚未发往上游且没有可获取的主节点时使用。固定回退节点必须已启用且不是代理池。",
|
||||
fallbackBuildHelp: "Grok Build 没有可用主出口时使用的回退方式。",
|
||||
fallbackWebHelp: "Grok Web 没有可用主出口时使用的回退方式。",
|
||||
fallbackConsoleHelp: "Grok Console 没有可用主出口时使用的回退方式。",
|
||||
fallbackWebAssetHelp: "Grok Web 资源请求没有可用出口时使用的回退方式。",
|
||||
fallbackMode: "{{scope}} 的回退方式",
|
||||
fallbackNone: "不回退",
|
||||
fallbackDirect: "本地直连",
|
||||
fallbackFixed: "固定代理",
|
||||
fallbackNode: "{{scope}} 的固定回退代理",
|
||||
fallbackNodeUnavailable: "已配置节点不可用",
|
||||
search: "搜索代理节点",
|
||||
healthy: "可用",
|
||||
assigned: "已分配账号",
|
||||
|
||||
Reference in new issue
Block a user