diff --git a/backend/internal/app/application.go b/backend/internal/app/application.go index f65b2166..b345102c 100644 --- a/backend/internal/app/application.go +++ b/backend/internal/app/application.go @@ -238,7 +238,7 @@ func New(ctx context.Context, cfg config.Config, logger *slog.Logger) (*Applicat accountSyncService := accountsyncapp.NewService(logger, accountService, accountService, accountService, modelService) accountSyncService.SetBulkPool(importPool) accountSyncService.UpdateConcurrency(cfg.Batch.ImportConcurrency) - egressService := egressapp.NewService(egressRepo, cipher, infraegress.DefaultUserAgent, cfg.Provider.Console.UserAgent) + egressService := egressapp.NewService(egressRepo, cipher, infraegress.DefaultUserAgent) 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()) dashboardService := dashboardapp.NewService(dashboardRepo) @@ -278,7 +278,6 @@ func New(ctx context.Context, cfg config.Config, logger *slog.Logger) (*Applicat }) webAdapter.UpdateConfig(webProviderConfig(next)) consoleAdapter.UpdateConfig(consoleProviderConfig(next)) - egressService.UpdateDefaults(infraegress.DefaultUserAgent, next.Provider.Console.UserAgent) mediaService.UpdateConfig(mediaConfig(next)) quotaRecoveryService.UpdateConfig(next.Provider.Web.RecoveryBackoffBase.Value(), next.Provider.Web.RecoveryBackoffMax.Value()) accountSyncService.UpdateConcurrency(next.Batch.ImportConcurrency) @@ -321,8 +320,7 @@ func webProviderConfig(cfg config.Config) webprovider.Config { func consoleProviderConfig(cfg config.Config) consoleprovider.Config { return consoleprovider.Config{ - BaseURL: cfg.Provider.Console.BaseURL, UserAgent: cfg.Provider.Console.UserAgent, - TimeoutSeconds: int(cfg.Provider.Console.ChatTimeout.Value().Seconds()), + BaseURL: cfg.Provider.Console.BaseURL, TimeoutSeconds: int(cfg.Provider.Console.ChatTimeout.Value().Seconds()), } } diff --git a/backend/internal/application/egress/service.go b/backend/internal/application/egress/service.go index 68d22e3a..89f3c222 100644 --- a/backend/internal/application/egress/service.go +++ b/backend/internal/application/egress/service.go @@ -6,7 +6,6 @@ import ( "fmt" "net/url" "strings" - "sync" domain "github.com/chenyme/grok2api/backend/internal/domain/egress" "github.com/chenyme/grok2api/backend/internal/infra/security" @@ -40,28 +39,17 @@ type Input struct { type Service struct { repository repository.EgressRepository cipher *security.Cipher - mu sync.RWMutex - webUA string - consoleUA string + browserUA string } -func NewService(repository repository.EgressRepository, cipher *security.Cipher, webUA, consoleUA string) *Service { - return &Service{repository: repository, cipher: cipher, webUA: strings.TrimSpace(webUA), consoleUA: strings.TrimSpace(consoleUA)} -} - -func (s *Service) UpdateDefaults(webUA, consoleUA string) { - s.mu.Lock() - defer s.mu.Unlock() - s.webUA = strings.TrimSpace(webUA) - s.consoleUA = strings.TrimSpace(consoleUA) +func NewService(repository repository.EgressRepository, cipher *security.Cipher, browserUA string) *Service { + return &Service{repository: repository, cipher: cipher, browserUA: strings.TrimSpace(browserUA)} } func (s *Service) DefaultUserAgents() map[string]string { - s.mu.RLock() - defer s.mu.RUnlock() return map[string]string{ - string(domain.ScopeBuild): "", string(domain.ScopeWeb): s.webUA, string(domain.ScopeConsole): s.consoleUA, - string(domain.ScopeWebAsset): s.webUA, + string(domain.ScopeBuild): "", string(domain.ScopeWeb): s.browserUA, string(domain.ScopeConsole): s.browserUA, + string(domain.ScopeWebAsset): s.browserUA, } } @@ -129,9 +117,7 @@ func (s *Service) applyInput(value domain.Node, input Input, create bool) (domai value.UserAgent = strings.TrimSpace(input.UserAgent) } if input.Scope != domain.ScopeBuild && value.UserAgent == "" { - s.mu.RLock() - value.UserAgent = s.defaultUserAgent(input.Scope) - s.mu.RUnlock() + value.UserAgent = s.browserUA } if len(value.UserAgent) > 512 { return domain.Node{}, fmt.Errorf("%w: User-Agent 过长", ErrInvalidInput) @@ -173,13 +159,6 @@ func (s *Service) applyInput(value domain.Node, input Input, create bool) (domai return value, nil } -func (s *Service) defaultUserAgent(scope domain.Scope) string { - if scope == domain.ScopeConsole { - return s.consoleUA - } - return s.webUA -} - func publicNode(value domain.Node) domain.PublicNode { userAgent := value.UserAgent if value.Scope == domain.ScopeBuild { diff --git a/backend/internal/application/egress/service_test.go b/backend/internal/application/egress/service_test.go index 2b4e18d7..5c7b691b 100644 --- a/backend/internal/application/egress/service_test.go +++ b/backend/internal/application/egress/service_test.go @@ -73,7 +73,7 @@ func TestBuildNodeAlwaysUsesProviderUserAgent(t *testing.T) { if err != nil { t.Fatal(err) } - service := NewService(nil, cipher, "web-agent", "console-agent") + service := NewService(nil, cipher, "browser-agent") value, err := service.applyInput(domain.Node{UserAgent: "legacy-build-agent"}, Input{ Name: "build", Scope: domain.ScopeBuild, Enabled: true, UserAgent: "custom-build-agent", }, false) @@ -83,22 +83,22 @@ func TestBuildNodeAlwaysUsesProviderUserAgent(t *testing.T) { if value.UserAgent != "" || publicNode(value).UserAgent != "" { t.Fatalf("build node userAgent = %q", value.UserAgent) } - if defaults := service.DefaultUserAgents(); defaults[string(domain.ScopeBuild)] != "" || defaults[string(domain.ScopeWeb)] != "web-agent" || defaults[string(domain.ScopeConsole)] != "console-agent" { + if defaults := service.DefaultUserAgents(); defaults[string(domain.ScopeBuild)] != "" || defaults[string(domain.ScopeWeb)] != "browser-agent" || defaults[string(domain.ScopeConsole)] != "browser-agent" { t.Fatalf("default user agents = %#v", defaults) } } -func TestConsoleNodeUsesConsoleDefaultUserAgent(t *testing.T) { +func TestConsoleNodeUsesBrowserDefaultUserAgent(t *testing.T) { cipher, err := security.NewCipher("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=") if err != nil { t.Fatal(err) } - service := NewService(nil, cipher, "web-agent", "console-agent") + service := NewService(nil, cipher, "browser-agent") value, err := service.applyInput(domain.Node{}, Input{Name: "console", Scope: domain.ScopeConsole, Enabled: true}, true) if err != nil { t.Fatal(err) } - if value.UserAgent != "console-agent" { + if value.UserAgent != "browser-agent" { t.Fatalf("console node userAgent = %q", value.UserAgent) } } diff --git a/backend/internal/application/gateway/prompt_cache.go b/backend/internal/application/gateway/prompt_cache.go index 24b069dd..6b3e3829 100644 --- a/backend/internal/application/gateway/prompt_cache.go +++ b/backend/internal/application/gateway/prompt_cache.go @@ -7,27 +7,42 @@ import ( "strings" accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account" - "github.com/chenyme/grok2api/backend/internal/domain/audit" ) -const promptCacheIdentityVersion = "v1" +const buildSessionIdentityVersion = "v2" -// resolvePromptCacheIdentity 将客户端缓存键或会话标识转换为固定长度的上游身份。 -// 客户端、Provider、上游模型和协议共同参与摘要,防止共享账号池中的跨租户碰撞。 -func resolvePromptCacheIdentity(clientKeyID uint64, provider accountdomain.Provider, upstreamModel string, operation audit.Operation, explicitKey, sessionSeed string) string { +type buildSessionIdentity struct { + upstreamID string + affinityKey string +} + +// resolveBuildSessionIdentity 将客户端缓存键或会话标识拆分为两种用途: +// upstreamID 在同一客户端会话内跨协议、跨模型保持稳定,用于上游缓存和 CLI 会话 Header; +// affinityKey 额外包含上游模型,用于账号粘滞,避免不同模型能力的账号相互覆盖绑定。 +func resolveBuildSessionIdentity(clientKeyID uint64, provider accountdomain.Provider, upstreamModel, explicitKey, sessionSeed string) buildSessionIdentity { seed := strings.TrimSpace(explicitKey) if seed == "" { seed = strings.TrimSpace(sessionSeed) } model := strings.ToLower(strings.TrimSpace(upstreamModel)) if clientKeyID == 0 || provider == "" || model == "" || seed == "" { - return "" + return buildSessionIdentity{} } - if operation == "" { - operation = audit.OperationResponses + upstreamSource := fmt.Sprintf("grok2api:build-session:%s:%d:%s:%s", buildSessionIdentityVersion, clientKeyID, provider, seed) + affinitySource := fmt.Sprintf("grok2api:build-affinity:%s:%d:%s:%s:%s", buildSessionIdentityVersion, clientKeyID, provider, model, seed) + return buildSessionIdentity{ + upstreamID: digestUUID(upstreamSource), + affinityKey: hexDigest(affinitySource), } - source := fmt.Sprintf("grok2api:prompt-cache:%s:%d:%s:%s:%s:%s", promptCacheIdentityVersion, clientKeyID, provider, model, operation, seed) +} + +func digestUUID(source string) string { digest := sha256.Sum256([]byte(source)) hexID := hex.EncodeToString(digest[:16]) return fmt.Sprintf("%s-%s-%s-%s-%s", hexID[0:8], hexID[8:12], hexID[12:16], hexID[16:20], hexID[20:32]) } + +func hexDigest(source string) string { + digest := sha256.Sum256([]byte(source)) + return hex.EncodeToString(digest[:]) +} diff --git a/backend/internal/application/gateway/prompt_cache_test.go b/backend/internal/application/gateway/prompt_cache_test.go index d6377500..4513e8c4 100644 --- a/backend/internal/application/gateway/prompt_cache_test.go +++ b/backend/internal/application/gateway/prompt_cache_test.go @@ -4,37 +4,45 @@ import ( "testing" accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account" - "github.com/chenyme/grok2api/backend/internal/domain/audit" ) -func TestResolvePromptCacheIdentityIsStableAndIsolated(t *testing.T) { - base := resolvePromptCacheIdentity(7, accountdomain.ProviderBuild, "grok-4.5", audit.OperationMessages, "", "session-1") - if len(base) != 36 || base != resolvePromptCacheIdentity(7, accountdomain.ProviderBuild, "grok-4.5", audit.OperationMessages, "", "session-1") { - t.Fatalf("unstable identity = %q", base) +func TestResolveBuildSessionIdentityIsStableAndTenantIsolated(t *testing.T) { + base := resolveBuildSessionIdentity(7, accountdomain.ProviderBuild, "grok-4.5", "", "session-1") + if len(base.upstreamID) != 36 || len(base.affinityKey) != 64 || base != resolveBuildSessionIdentity(7, accountdomain.ProviderBuild, "grok-4.5", "", "session-1") { + t.Fatalf("unstable identity = %#v", base) } - for name, value := range map[string]string{ - "client": resolvePromptCacheIdentity(8, accountdomain.ProviderBuild, "grok-4.5", audit.OperationMessages, "", "session-1"), - "provider": resolvePromptCacheIdentity(7, accountdomain.ProviderConsole, "grok-4.5", audit.OperationMessages, "", "session-1"), - "model": resolvePromptCacheIdentity(7, accountdomain.ProviderBuild, "grok-4.3", audit.OperationMessages, "", "session-1"), - "operation": resolvePromptCacheIdentity(7, accountdomain.ProviderBuild, "grok-4.5", audit.OperationResponses, "", "session-1"), - "session": resolvePromptCacheIdentity(7, accountdomain.ProviderBuild, "grok-4.5", audit.OperationMessages, "", "session-2"), + for name, value := range map[string]buildSessionIdentity{ + "client": resolveBuildSessionIdentity(8, accountdomain.ProviderBuild, "grok-4.5", "", "session-1"), + "provider": resolveBuildSessionIdentity(7, accountdomain.ProviderConsole, "grok-4.5", "", "session-1"), + "session": resolveBuildSessionIdentity(7, accountdomain.ProviderBuild, "grok-4.5", "", "session-2"), } { if value == base { - t.Fatalf("%s was not isolated: %q", name, value) + t.Fatalf("%s was not isolated: %#v", name, value) } } } -func TestResolvePromptCacheIdentityPrefersExplicitKey(t *testing.T) { - first := resolvePromptCacheIdentity(7, accountdomain.ProviderBuild, "grok-4.5", audit.OperationResponses, "client-key", "session-1") - second := resolvePromptCacheIdentity(7, accountdomain.ProviderBuild, "grok-4.5", audit.OperationResponses, "client-key", "session-2") - if first == "" || first != second { - t.Fatalf("explicit key did not take precedence: first=%q second=%q", first, second) +func TestResolveBuildSessionIdentitySeparatesAffinityFromUpstreamSession(t *testing.T) { + first := resolveBuildSessionIdentity(7, accountdomain.ProviderBuild, "grok-4.5", "", "session-1") + otherModel := resolveBuildSessionIdentity(7, accountdomain.ProviderBuild, "grok-4.3", "", "session-1") + if first.upstreamID == "" || first.upstreamID != otherModel.upstreamID { + t.Fatalf("upstream session changed with model: first=%#v other=%#v", first, otherModel) } - if resolvePromptCacheIdentity(0, accountdomain.ProviderBuild, "grok-4.5", audit.OperationResponses, "client-key", "") != "" { + if first.affinityKey == otherModel.affinityKey { + t.Fatalf("model-specific account affinity was not isolated: %#v", first) + } +} + +func TestResolveBuildSessionIdentityPrefersExplicitKey(t *testing.T) { + first := resolveBuildSessionIdentity(7, accountdomain.ProviderBuild, "grok-4.5", "client-key", "session-1") + second := resolveBuildSessionIdentity(7, accountdomain.ProviderBuild, "grok-4.5", "client-key", "session-2") + if first.upstreamID == "" || first != second { + t.Fatalf("explicit key did not take precedence: first=%#v second=%#v", first, second) + } + if value := resolveBuildSessionIdentity(0, accountdomain.ProviderBuild, "grok-4.5", "client-key", ""); value != (buildSessionIdentity{}) { t.Fatal("identity without client ownership should be empty") } - if resolvePromptCacheIdentity(7, accountdomain.ProviderBuild, "grok-4.5", audit.OperationResponses, "", "") != "" { + if value := resolveBuildSessionIdentity(7, accountdomain.ProviderBuild, "grok-4.5", "", ""); value != (buildSessionIdentity{}) { t.Fatal("identity without an explicit key or session should be empty") } } diff --git a/backend/internal/application/gateway/selector.go b/backend/internal/application/gateway/selector.go index c15e647d..120989fe 100644 --- a/backend/internal/application/gateway/selector.go +++ b/backend/internal/application/gateway/selector.go @@ -4,6 +4,7 @@ import ( "context" "crypto/sha256" "encoding/hex" + "errors" "fmt" "strings" "sync" @@ -140,9 +141,9 @@ func (s *Selector) routingConfig() (time.Duration, time.Duration, time.Duration, return s.stickyTTL, s.cooldownBase, s.cooldownMax, s.capacityWait } -func (s *Selector) Acquire(ctx context.Context, provider account.Provider, upstreamModel, quotaMode, promptCacheKey string, excluded map[uint64]bool, allowQuotaProbe bool) (*accountLease, error) { +func (s *Selector) Acquire(ctx context.Context, provider account.Provider, upstreamModel, quotaMode, affinityKey string, excluded map[uint64]bool, allowQuotaProbe bool) (*accountLease, error) { now := time.Now().UTC() - stickyKey := promptCacheStickyKey(promptCacheKey) + stickyKey := stickySessionKey(affinityKey) values, err := s.loadCandidates(ctx, provider, upstreamModel, quotaMode, now) if err != nil { return nil, err @@ -241,27 +242,63 @@ func (s *Selector) Acquire(ctx context.Context, provider account.Provider, upstr return lease, nil } } + var saturatedStickyID uint64 if stickyKey != "" { stickyID, ok, err := s.sticky.Get(ctx, stickyKey, now) if err != nil { return nil, fmt.Errorf("读取会话粘滞状态: %w", err) } if ok { - for _, candidate := range normalCandidates { - if candidate.Credential.ID == stickyID { - lease, acquireErr := s.claimAccountSlot(ctx, candidate.Credential) - if acquireErr != nil { - return nil, acquireErr - } - if lease != nil { + candidate, eligible := routingCandidateByID(normalCandidates, stickyID) + if eligible { + stickyTTL, _, _, _ := s.routingConfig() + boundID, bindErr := s.sticky.Bind(ctx, stickyKey, stickyID, now, now.Add(stickyTTL)) + if bindErr != nil { + return nil, fmt.Errorf("刷新会话粘滞状态: %w", bindErr) + } + if boundID != stickyID { + candidate, eligible = routingCandidateByID(normalCandidates, boundID) + stickyID = boundID + } + if eligible { + lease, acquireErr := s.acquirePinnedCapacity(ctx, candidate.Credential) + if acquireErr == nil { lease.Billing = candidate.Billing lease.QuotaMode = effectiveQuotaMode(candidate, quotaMode) return lease, nil } + if !isSelectionUnavailable(acquireErr, SelectionSaturated) { + return nil, acquireErr + } + saturatedStickyID = stickyID } } } } + // 粘性账号仅因并发满载而暂时不可用时,先等待该账号;超时后允许本次请求临时借用 + // 其他账号,但不覆盖原绑定,避免并行请求让活跃会话在账号池中来回抖动。 + if saturatedStickyID != 0 { + plan, err := s.planCandidates(ctx, normalCandidates, time.Now().UTC(), s.resolveTierOrder(provider, upstreamModel)) + if err != nil { + return nil, err + } + for candidate, ok := plan.Next(); ok; candidate, ok = plan.Next() { + if candidate.Credential.ID == saturatedStickyID { + continue + } + lease, claimErr := s.claimAccountSlot(ctx, candidate.Credential) + if claimErr != nil { + return nil, claimErr + } + if lease == nil { + continue + } + lease.Billing = candidate.Billing + lease.QuotaMode = effectiveQuotaMode(candidate, quotaMode) + return lease, nil + } + return nil, &SelectionUnavailableError{Reason: SelectionSaturated, RetryAfter: time.Second} + } _, _, _, capacityWait := s.routingConfig() waitDeadline := time.Now().Add(capacityWait) for { @@ -280,9 +317,29 @@ func (s *Selector) Acquire(ctx context.Context, provider account.Provider, upstr } if stickyKey != "" { stickyTTL, _, _, _ := s.routingConfig() - if err := s.sticky.Set(ctx, stickyKey, candidate.Credential.ID, currentTime.Add(stickyTTL)); err != nil { + boundID, bindErr := s.sticky.Bind(ctx, stickyKey, candidate.Credential.ID, currentTime, currentTime.Add(stickyTTL)) + if bindErr != nil { lease.Release() - return nil, fmt.Errorf("写入会话粘滞状态: %w", err) + return nil, fmt.Errorf("写入会话粘滞状态: %w", bindErr) + } + if boundID != candidate.Credential.ID { + if boundCandidate, eligible := routingCandidateByID(normalCandidates, boundID); eligible { + boundLease, boundErr := s.acquirePinnedCapacity(ctx, boundCandidate.Credential) + if boundErr == nil { + lease.Release() + boundLease.Billing = boundCandidate.Billing + boundLease.QuotaMode = effectiveQuotaMode(boundCandidate, quotaMode) + return boundLease, nil + } + if !isSelectionUnavailable(boundErr, SelectionSaturated) { + lease.Release() + return nil, boundErr + } + // 已绑定账号满载时保留原绑定,本次请求使用已获取的临时账号。 + } else if err := s.sticky.Set(ctx, stickyKey, candidate.Credential.ID, currentTime.Add(stickyTTL)); err != nil { + lease.Release() + return nil, fmt.Errorf("重建会话粘滞状态: %w", err) + } } } lease.Billing = candidate.Billing @@ -302,8 +359,8 @@ func (s *Selector) Acquire(ctx context.Context, provider account.Provider, upstr } } -// promptCacheStickyKey 将调用方缓存键压缩为固定长度,仅用于本地账号粘滞索引。 -func promptCacheStickyKey(value string) string { +// stickySessionKey 将调用方粘滞 identity 压缩为固定长度,仅用于账号粘滞索引。 +func stickySessionKey(value string) string { if value == "" { return "" } @@ -311,6 +368,20 @@ func promptCacheStickyKey(value string) string { return hex.EncodeToString(digest[:]) } +func routingCandidateByID(values []account.RoutingCandidate, accountID uint64) (account.RoutingCandidate, bool) { + for _, candidate := range values { + if candidate.Credential.ID == accountID { + return candidate, true + } + } + return account.RoutingCandidate{}, false +} + +func isSelectionUnavailable(err error, reason SelectionUnavailableReason) bool { + var unavailable *SelectionUnavailableError + return errors.As(err, &unavailable) && unavailable.Reason == reason +} + // AcquirePinned 为 previous_response_id 等账号归属请求获取指定账号租约。 func (s *Selector) AcquirePinned(ctx context.Context, provider account.Provider, accountID uint64, upstreamModel, quotaMode string, inference bool) (*accountLease, error) { now := time.Now().UTC() diff --git a/backend/internal/application/gateway/selector_test.go b/backend/internal/application/gateway/selector_test.go index 75e79765..8bd25157 100644 --- a/backend/internal/application/gateway/selector_test.go +++ b/backend/internal/application/gateway/selector_test.go @@ -5,6 +5,7 @@ import ( "errors" "path/filepath" "slices" + "sync" "testing" "time" @@ -373,15 +374,15 @@ func TestSelectorPropagatesConcurrencyStoreFailure(t *testing.T) { } } -func TestPromptCacheStickyKeyIsFixedLengthAndStable(t *testing.T) { - first := promptCacheStickyKey("cache-key") - if len(first) != 64 || first != promptCacheStickyKey("cache-key") { +func TestStickySessionKeyIsFixedLengthAndStable(t *testing.T) { + first := stickySessionKey("affinity-key") + if len(first) != 64 || first != stickySessionKey("affinity-key") { t.Fatalf("sticky key = %q", first) } - if first == promptCacheStickyKey("another-key") { + if first == stickySessionKey("another-key") { t.Fatal("different prompt cache keys produced the same sticky key") } - if promptCacheStickyKey("") != "" { + if stickySessionKey("") != "" { t.Fatal("empty prompt cache key should remain empty") } } @@ -571,6 +572,117 @@ func TestSelectorWaitsBrieflyForAccountCapacity(t *testing.T) { } } +func TestSelectorStickySessionWaitsForBoundAccountCapacity(t *testing.T) { + ctx := context.Background() + sticky := memory.NewStickyStore() + selector, primary, _ := newStickySelectorFixture(t, sticky, 300*time.Millisecond, true) + first, err := selector.Acquire(ctx, account.ProviderBuild, "model", "", "stable-affinity", nil, false) + if err != nil || first.Credential.ID != primary.ID { + t.Fatalf("first lease = %#v, err = %v", first, err) + } + type result struct { + lease *accountLease + err error + } + resultCh := make(chan result, 1) + go func() { + lease, acquireErr := selector.Acquire(ctx, account.ProviderBuild, "model", "", "stable-affinity", nil, false) + resultCh <- result{lease: lease, err: acquireErr} + }() + select { + case value := <-resultCh: + t.Fatalf("sticky request bypassed the bound account before capacity returned: %#v", value) + case <-time.After(30 * time.Millisecond): + } + first.Release() + select { + case value := <-resultCh: + if value.err != nil || value.lease == nil || value.lease.Credential.ID != primary.ID { + t.Fatalf("sticky lease = %#v, err = %v", value.lease, value.err) + } + value.lease.Release() + case <-time.After(time.Second): + t.Fatal("sticky request did not wake after bound capacity returned") + } +} + +func TestSelectorStickySessionTemporaryFallbackDoesNotRebind(t *testing.T) { + ctx := context.Background() + sticky := memory.NewStickyStore() + selector, primary, fallback := newStickySelectorFixture(t, sticky, 20*time.Millisecond, true) + first, err := selector.Acquire(ctx, account.ProviderBuild, "model", "", "stable-affinity", nil, false) + if err != nil || first.Credential.ID != primary.ID { + t.Fatalf("first lease = %#v, err = %v", first, err) + } + temporary, err := selector.Acquire(ctx, account.ProviderBuild, "model", "", "stable-affinity", nil, false) + if err != nil || temporary.Credential.ID != fallback.ID { + t.Fatalf("temporary lease = %#v, err = %v", temporary, err) + } + if boundID, ok, err := sticky.Get(ctx, stickySessionKey("stable-affinity"), time.Now().UTC()); err != nil || !ok || boundID != primary.ID { + t.Fatalf("sticky binding changed after temporary fallback: id=%d ok=%v err=%v", boundID, ok, err) + } + temporary.Release() + first.Release() + resumed, err := selector.Acquire(ctx, account.ProviderBuild, "model", "", "stable-affinity", nil, false) + if err != nil || resumed.Credential.ID != primary.ID { + t.Fatalf("resumed sticky lease = %#v, err = %v", resumed, err) + } + resumed.Release() +} + +func TestSelectorStickyHitRefreshesTTL(t *testing.T) { + ctx := context.Background() + sticky := newRecordingStickyStore() + selector, _, _ := newStickySelectorFixture(t, sticky, 0, false) + first, err := selector.Acquire(ctx, account.ProviderBuild, "model", "", "stable-affinity", nil, false) + if err != nil { + t.Fatal(err) + } + first.Release() + time.Sleep(time.Millisecond) + second, err := selector.Acquire(ctx, account.ProviderBuild, "model", "", "stable-affinity", nil, false) + if err != nil { + t.Fatal(err) + } + second.Release() + expiries := sticky.Expiries() + if len(expiries) < 2 || !expiries[len(expiries)-1].After(expiries[0]) { + t.Fatalf("sticky expiry was not refreshed: %v", expiries) + } +} + +func newStickySelectorFixture(t *testing.T, sticky repository.StickySessionRepository, capacityWait time.Duration, withFallback bool) (*Selector, account.Credential, account.Credential) { + t.Helper() + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "sticky-selector.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = database.Close() }) + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + accounts := relational.NewAccountRepository(database) + primary, _, err := accounts.UpsertByIdentity(ctx, account.Credential{ + Provider: account.ProviderBuild, Name: "primary", SourceKey: "primary", EncryptedAccessToken: "encrypted", + Enabled: true, AuthStatus: account.AuthStatusActive, Priority: 100, MaxConcurrent: 1, + }) + if err != nil { + t.Fatal(err) + } + var fallback account.Credential + if withFallback { + fallback, _, err = accounts.UpsertByIdentity(ctx, account.Credential{ + Provider: account.ProviderBuild, Name: "fallback", SourceKey: "fallback", EncryptedAccessToken: "encrypted", + Enabled: true, AuthStatus: account.AuthStatusActive, Priority: 1, MaxConcurrent: 1, + }) + if err != nil { + t.Fatal(err) + } + } + return NewSelector(accounts, memory.NewConcurrencyLimiter(), sticky, nil, time.Hour, time.Second, time.Minute, capacityWait), primary, fallback +} + func TestSelectorAppliesPersistedCooldownOnlyToMatchingModel(t *testing.T) { ctx := context.Background() database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "model-cooldown.db")) @@ -614,6 +726,29 @@ func TestSelectorAppliesPersistedCooldownOnlyToMatchingModel(t *testing.T) { type failingConcurrencyLimiter struct{ err error } +type recordingStickyStore struct { + *memory.StickyStore + mu sync.Mutex + expiries []time.Time +} + +func newRecordingStickyStore() *recordingStickyStore { + return &recordingStickyStore{StickyStore: memory.NewStickyStore()} +} + +func (s *recordingStickyStore) Bind(ctx context.Context, key string, accountID uint64, now, expiresAt time.Time) (uint64, error) { + s.mu.Lock() + s.expiries = append(s.expiries, expiresAt) + s.mu.Unlock() + return s.StickyStore.Bind(ctx, key, accountID, now, expiresAt) +} + +func (s *recordingStickyStore) Expiries() []time.Time { + s.mu.Lock() + defer s.mu.Unlock() + return append([]time.Time(nil), s.expiries...) +} + type batchConcurrencyLimiter struct { values map[string]int batchCalls int diff --git a/backend/internal/application/gateway/service.go b/backend/internal/application/gateway/service.go index d7e8dba9..890b6081 100644 --- a/backend/internal/application/gateway/service.go +++ b/backend/internal/application/gateway/service.go @@ -435,15 +435,17 @@ func (s *Service) createResponseAt(ctx context.Context, input Input, path string } return nil, clientkeyapp.ErrModelNotAllowed } + affinityKey := "" if route.Provider == accountdomain.ProviderBuild { - input.PromptCacheKey = resolvePromptCacheIdentity( + identity := resolveBuildSessionIdentity( input.ClientKey.ID, route.Provider, route.UpstreamModel, - operation, input.PromptCacheKey, input.PromptCacheSeed, ) + input.PromptCacheKey = identity.upstreamID + affinityKey = identity.affinityKey } adapter, ok := s.providers.Responses(route.Provider) if !ok { @@ -497,7 +499,7 @@ attemptLoop: if ownership != nil { lease, err = s.selector.AcquirePinned(ctx, route.Provider, ownership.AccountID, route.UpstreamModel, quotaMode, true) } else { - lease, err = s.selector.Acquire(ctx, route.Provider, route.UpstreamModel, quotaMode, input.PromptCacheKey, excluded, !quotaProbeAttempted) + lease, err = s.selector.Acquire(ctx, route.Provider, route.UpstreamModel, quotaMode, affinityKey, excluded, !quotaProbeAttempted) } timing.markSelection(time.Since(selectionStarted)) if err != nil { diff --git a/backend/internal/application/gateway/service_test.go b/backend/internal/application/gateway/service_test.go index db1e226d..e8f72b96 100644 --- a/backend/internal/application/gateway/service_test.go +++ b/backend/internal/application/gateway/service_test.go @@ -140,10 +140,14 @@ func TestGatewayFailsOverBeforeReturningBody(t *testing.T) { if len(adapter.attempts) != 2 || adapter.attempts[0] != first.ID || adapter.attempts[1] != second.ID { t.Fatalf("attempts = %#v", adapter.attempts) } - expectedCacheKey := resolvePromptCacheIdentity(clientKey.ID, account.ProviderBuild, "grok-test", audit.OperationResponses, "", "claude-session") + identity := resolveBuildSessionIdentity(clientKey.ID, account.ProviderBuild, "grok-test", "", "claude-session") + expectedCacheKey := identity.upstreamID if adapter.lastPromptCacheKey != expectedCacheKey { t.Fatalf("prompt cache key = %q, want %q", adapter.lastPromptCacheKey, expectedCacheKey) } + if boundID, ok, err := sticky.Get(ctx, stickySessionKey(identity.affinityKey), time.Now().UTC()); err != nil || !ok || boundID != second.ID { + t.Fatalf("failover sticky binding = %d, %v, err = %v; want account %d", boundID, ok, err, second.ID) + } observedAccount, err := accountRepo.Get(ctx, second.ID) if err != nil || observedAccount.ObservedModel != "grok-test-build-free" { t.Fatalf("observed account = %#v, err = %v", observedAccount, err) diff --git a/backend/internal/application/settings/service.go b/backend/internal/application/settings/service.go index 8bbcffc7..443f1441 100644 --- a/backend/internal/application/settings/service.go +++ b/backend/internal/application/settings/service.go @@ -52,7 +52,6 @@ type ProviderWebConfig struct { type ProviderConsoleConfig struct { BaseURL string - UserAgent string ChatTimeout string } @@ -277,8 +276,7 @@ func applyDomainConfig(base config.Config, value settingsdomain.Config) config.C // Console 是后续版本新增的完整配置段;旧 JSON 整段缺失时沿用代码默认值。 if value.ProviderConsole != (settingsdomain.ProviderConsoleConfig{}) { base.Provider.Console = config.ConsoleProviderConfig{ - BaseURL: value.ProviderConsole.BaseURL, UserAgent: value.ProviderConsole.UserAgent, - ChatTimeout: config.Duration(value.ProviderConsole.ChatTimeout), + BaseURL: value.ProviderConsole.BaseURL, ChatTimeout: config.Duration(value.ProviderConsole.ChatTimeout), } } randomDelay := time.Duration(-1) @@ -328,8 +326,7 @@ func toDomainConfig(value config.Config) settingsdomain.Config { RecoveryBackoffBase: value.Provider.Web.RecoveryBackoffBase.Value(), RecoveryBackoffMax: value.Provider.Web.RecoveryBackoffMax.Value(), }, ProviderConsole: settingsdomain.ProviderConsoleConfig{ - BaseURL: value.Provider.Console.BaseURL, UserAgent: value.Provider.Console.UserAgent, - ChatTimeout: value.Provider.Console.ChatTimeout.Value(), + BaseURL: value.Provider.Console.BaseURL, ChatTimeout: value.Provider.Console.ChatTimeout.Value(), }, Batch: settingsdomain.BatchConfig{ ImportConcurrency: value.Batch.ImportConcurrency, ConversionConcurrency: value.Batch.ConversionConcurrency, @@ -399,7 +396,6 @@ func mergeEditable(current config.Config, input EditableConfig) (config.Config, next.Provider.Web.MediaConcurrency = input.ProviderWeb.MediaConcurrency next.Provider.Web.AllowNSFW = input.ProviderWeb.AllowNSFW next.Provider.Console.BaseURL = strings.TrimSpace(input.ProviderConsole.BaseURL) - next.Provider.Console.UserAgent = strings.TrimSpace(input.ProviderConsole.UserAgent) next.Batch = config.BatchConfig{ ImportConcurrency: input.Batch.ImportConcurrency, ConversionConcurrency: input.Batch.ConversionConcurrency, SyncConcurrency: input.Batch.SyncConcurrency, RefreshConcurrency: input.Batch.RefreshConcurrency, @@ -466,8 +462,7 @@ func toEditable(cfg config.Config) EditableConfig { RecoveryBackoffBase: cfg.Provider.Web.RecoveryBackoffBase.String(), RecoveryBackoffMax: cfg.Provider.Web.RecoveryBackoffMax.String(), }, ProviderConsole: ProviderConsoleConfig{ - BaseURL: cfg.Provider.Console.BaseURL, UserAgent: cfg.Provider.Console.UserAgent, - ChatTimeout: cfg.Provider.Console.ChatTimeout.String(), + BaseURL: cfg.Provider.Console.BaseURL, ChatTimeout: cfg.Provider.Console.ChatTimeout.String(), }, Batch: BatchConfig{ ImportConcurrency: cfg.Batch.ImportConcurrency, ConversionConcurrency: cfg.Batch.ConversionConcurrency, diff --git a/backend/internal/application/settings/service_test.go b/backend/internal/application/settings/service_test.go index 2d74e4a3..68c91781 100644 --- a/backend/internal/application/settings/service_test.go +++ b/backend/internal/application/settings/service_test.go @@ -53,7 +53,6 @@ func TestUpdatePersistsAppliesAndReportsRestart(t *testing.T) { input.Media.CleanupInterval = "5m" input.Frontend.PublicAPIBaseURL = "https://public.example.com" input.ProviderConsole.BaseURL = "https://console.example.com" - input.ProviderConsole.UserAgent = "console-test-agent" input.ProviderConsole.ChatTimeout = "6m" input.Batch = BatchConfig{ImportConcurrency: 26, ConversionConcurrency: 27, SyncConcurrency: 28, RefreshConcurrency: 29, RandomDelay: "750ms"} @@ -76,7 +75,7 @@ func TestUpdatePersistsAppliesAndReportsRestart(t *testing.T) { if applied.Batch.ImportConcurrency != 26 || applied.Batch.ConversionConcurrency != 27 || applied.Batch.SyncConcurrency != 28 || applied.Batch.RefreshConcurrency != 29 || applied.Batch.RandomDelay.Value() != 750*time.Millisecond { t.Fatalf("batch configuration was not applied: %#v", applied.Batch) } - if applied.Provider.Console.BaseURL != "https://console.example.com" || applied.Provider.Console.UserAgent != "console-test-agent" || applied.Provider.Console.ChatTimeout.Value() != 6*time.Minute { + if applied.Provider.Console.BaseURL != "https://console.example.com" || applied.Provider.Console.ChatTimeout.Value() != 6*time.Minute { t.Fatalf("console configuration was not applied: %#v", applied.Provider.Console) } if len(snapshot.RestartRequired) != 1 || snapshot.RestartRequired[0] != "audit.bufferSize" { diff --git a/backend/internal/domain/settings/settings.go b/backend/internal/domain/settings/settings.go index c10216fd..c5d69b07 100644 --- a/backend/internal/domain/settings/settings.go +++ b/backend/internal/domain/settings/settings.go @@ -28,7 +28,6 @@ type FrontendConfig struct { type ProviderConsoleConfig struct { BaseURL string - UserAgent string ChatTimeout time.Duration } diff --git a/backend/internal/infra/config/config.go b/backend/internal/infra/config/config.go index 6c3184d1..c5a75b6f 100644 --- a/backend/internal/infra/config/config.go +++ b/backend/internal/infra/config/config.go @@ -149,9 +149,9 @@ type WebProviderConfig struct { } type ConsoleProviderConfig struct { - BaseURL string `yaml:"baseURL"` - UserAgent string `yaml:"userAgent"` - ChatTimeout Duration `yaml:"chatTimeout"` + BaseURL string `yaml:"baseURL"` + LegacyUserAgent string `yaml:"userAgent"` // Deprecated: 仅用于兼容旧配置文件,不参与请求。 + ChatTimeout Duration `yaml:"chatTimeout"` } // BatchConfig 定义可热加载的账号批量任务并发上限。 @@ -428,9 +428,6 @@ func (c Config) Validate() error { if err != nil || consoleURL.Scheme != "https" || consoleURL.Host == "" || consoleURL.User != nil { return errors.New("provider.console.baseURL 必须是无凭据的 HTTPS URL") } - if userAgent := strings.TrimSpace(c.Provider.Console.UserAgent); len(userAgent) < 1 || len(userAgent) > 512 { - return errors.New("provider.console.userAgent 长度必须在 1 到 512 个字符之间") - } if c.Provider.Console.ChatTimeout.Value() < 5*time.Second || c.Provider.Console.ChatTimeout.Value() > 30*time.Minute { return errors.New("provider.console.chatTimeout 必须在 5 秒到 30 分钟之间") } @@ -523,10 +520,7 @@ func defaultConfig() Config { MediaConcurrency: 4, RecoveryBackoffBase: Duration(30 * time.Second), RecoveryBackoffMax: Duration(30 * time.Minute), }, - Console: ConsoleProviderConfig{ - BaseURL: "https://console.x.ai", UserAgent: "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", - ChatTimeout: Duration(5 * time.Minute), - }, + Console: ConsoleProviderConfig{BaseURL: "https://console.x.ai", ChatTimeout: Duration(5 * time.Minute)}, }, Batch: BatchConfig{ ImportConcurrency: 25, ConversionConcurrency: 25, SyncConcurrency: 25, diff --git a/backend/internal/infra/config/config_test.go b/backend/internal/infra/config/config_test.go index 21305aa0..637e7c5d 100644 --- a/backend/internal/infra/config/config_test.go +++ b/backend/internal/infra/config/config_test.go @@ -80,11 +80,32 @@ func TestDefaultGrokBuildClientVersionMatchesLocalBaseline(t *testing.T) { func TestDefaultConsoleProviderConfig(t *testing.T) { console := defaultConfig().Provider.Console - if console.BaseURL != "https://console.x.ai" || console.UserAgent == "" || console.ChatTimeout.Value() != 5*time.Minute { + if console.BaseURL != "https://console.x.ai" || console.LegacyUserAgent != "" || console.ChatTimeout.Value() != 5*time.Minute { t.Fatalf("console defaults = %#v", console) } } +func TestLoadAcceptsLegacyConsoleUserAgent(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.yaml") + data := []byte(`provider: + console: + userAgent: "legacy-console-agent" +secrets: + jwtSecret: "12345678901234567890123456789012" + credentialEncryptionKey: "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=" +`) + if err := os.WriteFile(path, data, 0o600); err != nil { + t.Fatal(err) + } + cfg, err := Load(path) + if err != nil { + t.Fatal(err) + } + if cfg.Provider.Console.LegacyUserAgent != "legacy-console-agent" { + t.Fatalf("legacy userAgent = %q", cfg.Provider.Console.LegacyUserAgent) + } +} + func TestLoadAcceptsRuntimeDefaultsAndRejectsUnknownFields(t *testing.T) { path := filepath.Join(t.TempDir(), "config.yaml") data := []byte(`secrets: @@ -154,7 +175,6 @@ func TestValidateRejectsUnsafeRuntimeLimits(t *testing.T) { "batch limit": func(cfg *Config) { cfg.Batch.SyncConcurrency = 51 }, "batch jitter": func(cfg *Config) { cfg.Batch.RandomDelay = Duration(6 * time.Second) }, "console url": func(cfg *Config) { cfg.Provider.Console.BaseURL = "http://console.x.ai" }, - "console ua": func(cfg *Config) { cfg.Provider.Console.UserAgent = "" }, "console timeout": func(cfg *Config) { cfg.Provider.Console.ChatTimeout = Duration(time.Second) }, diff --git a/backend/internal/infra/provider/console/adapter.go b/backend/internal/infra/provider/console/adapter.go index b59dffda..ac40f2f4 100644 --- a/backend/internal/infra/provider/console/adapter.go +++ b/backend/internal/infra/provider/console/adapter.go @@ -22,7 +22,6 @@ import ( type Config struct { BaseURL string - UserAgent string TimeoutSeconds int } @@ -140,7 +139,7 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response cancel() return nil, err } - applyHeaders(upstream, token, cfg.UserAgent, lease) + applyHeaders(upstream, token, lease) if request.Streaming { upstream.Header.Set("Accept", "text/event-stream") } @@ -278,13 +277,10 @@ func consoleEndpoint(baseURL string) string { return baseURL + "/v1/responses" } -func applyHeaders(request *http.Request, token, configuredUserAgent string, lease *infraegress.Lease) { - userAgent := "" - if lease.NodeID != 0 { - userAgent = strings.TrimSpace(lease.UserAgent) - } +func applyHeaders(request *http.Request, token string, lease *infraegress.Lease) { + userAgent := strings.TrimSpace(lease.UserAgent) if userAgent == "" { - userAgent = strings.TrimSpace(configuredUserAgent) + userAgent = infraegress.DefaultUserAgent } request.Header.Set("Accept", "*/*") request.Header.Set("Accept-Encoding", "gzip, deflate, br, zstd") diff --git a/backend/internal/infra/provider/console/console_test.go b/backend/internal/infra/provider/console/console_test.go index 0e82767e..5e74aba2 100644 --- a/backend/internal/infra/provider/console/console_test.go +++ b/backend/internal/infra/provider/console/console_test.go @@ -306,6 +306,9 @@ func TestAdapterForwardsConsoleHeadersAndNormalizedBody(t *testing.T) { if request.Header.Get("Authorization") != "Bearer anonymous" || request.Header.Get("x-cluster") != "https://us-east-1.api.x.ai" || request.Header.Get("Accept") != "*/*" || request.Header.Get("Priority") != "u=1, i" { t.Errorf("headers = %#v", request.Header) } + if request.Header.Get("User-Agent") != infraegress.DefaultUserAgent { + t.Errorf("user-agent = %q", request.Header.Get("User-Agent")) + } cookie := request.Header.Get("Cookie") if !strings.Contains(cookie, "sso=test-sso") || !strings.Contains(cookie, "sso-rw=test-sso") { t.Errorf("cookie = %q", cookie) @@ -399,7 +402,7 @@ func newConsoleTestAdapter(t *testing.T, baseURL string) (*Adapter, account.Cred if err != nil { t.Fatal(err) } - adapter := NewAdapter(Config{BaseURL: baseURL, UserAgent: "console-test", TimeoutSeconds: 5}, infraegress.NewManager(consoleEgressRepositoryStub{}, cipher), cipher) + adapter := NewAdapter(Config{BaseURL: baseURL, TimeoutSeconds: 5}, infraegress.NewManager(consoleEgressRepositoryStub{}, cipher), cipher) credential := account.Credential{ID: 1, Provider: account.ProviderConsole, AuthType: account.AuthTypeSSO, EncryptedAccessToken: encrypted} return adapter, credential } diff --git a/backend/internal/infra/runtime/memory/store.go b/backend/internal/infra/runtime/memory/store.go index 65b8efca..20df4ca3 100644 --- a/backend/internal/infra/runtime/memory/store.go +++ b/backend/internal/infra/runtime/memory/store.go @@ -207,32 +207,54 @@ func NewStickyStore() *StickyStore { return store } -func (s *StickyStore) Get(_ context.Context, promptCacheKey string, now time.Time) (uint64, bool, error) { - shard := &s.shards[shardIndex(promptCacheKey)] +func (s *StickyStore) Get(_ context.Context, affinityKey string, now time.Time) (uint64, bool, error) { + shard := &s.shards[shardIndex(affinityKey)] shard.mu.Lock() defer shard.mu.Unlock() - binding, ok := shard.bindings[promptCacheKey] + binding, ok := shard.bindings[affinityKey] if !ok { return 0, false, nil } if !now.Before(binding.expiresAt) { - delete(shard.bindings, promptCacheKey) + delete(shard.bindings, affinityKey) return 0, false, nil } return binding.accountID, true, nil } -func (s *StickyStore) Set(_ context.Context, promptCacheKey string, accountID uint64, expiresAt time.Time) error { - if promptCacheKey == "" { - return nil +func (s *StickyStore) Bind(_ context.Context, affinityKey string, proposedAccountID uint64, now, expiresAt time.Time) (uint64, error) { + if affinityKey == "" || proposedAccountID == 0 || !now.Before(expiresAt) { + return proposedAccountID, nil } - shard := &s.shards[shardIndex(promptCacheKey)] + shard := &s.shards[shardIndex(affinityKey)] shard.mu.Lock() defer shard.mu.Unlock() - shard.bindings[promptCacheKey] = stickyBinding{accountID: accountID, expiresAt: expiresAt} + if binding, ok := shard.bindings[affinityKey]; ok && now.Before(binding.expiresAt) { + binding.expiresAt = expiresAt + shard.bindings[affinityKey] = binding + return binding.accountID, nil + } + shard.bindings[affinityKey] = stickyBinding{accountID: proposedAccountID, expiresAt: expiresAt} + pruneStickyBindingsLocked(shard, now) + return proposedAccountID, nil +} + +func (s *StickyStore) Set(_ context.Context, affinityKey string, accountID uint64, expiresAt time.Time) error { + if affinityKey == "" { + return nil + } + shard := &s.shards[shardIndex(affinityKey)] + shard.mu.Lock() + defer shard.mu.Unlock() + shard.bindings[affinityKey] = stickyBinding{accountID: accountID, expiresAt: expiresAt} + pruneStickyBindingsLocked(shard, time.Now()) + return nil +} + +func pruneStickyBindingsLocked(shard *stickyShard, now time.Time) { if len(shard.bindings) > maxEntriesPerShard() { for key, binding := range shard.bindings { - if time.Now().After(binding.expiresAt) { + if !now.Before(binding.expiresAt) { delete(shard.bindings, key) } } @@ -248,7 +270,6 @@ func (s *StickyStore) Set(_ context.Context, promptCacheKey string, accountID ui delete(shard.bindings, oldestKey) } } - return nil } func (s *StickyStore) DeleteByAccount(_ context.Context, accountID uint64) error { diff --git a/backend/internal/infra/runtime/memory/store_test.go b/backend/internal/infra/runtime/memory/store_test.go index e60165d5..4d3bf7be 100644 --- a/backend/internal/infra/runtime/memory/store_test.go +++ b/backend/internal/infra/runtime/memory/store_test.go @@ -85,6 +85,26 @@ func TestStickyStoreExpires(t *testing.T) { } } +func TestStickyStoreBindPreservesExistingAccountAndRefreshesExpiry(t *testing.T) { + ctx := context.Background() + store := NewStickyStore() + now := time.Now().UTC() + bound, err := store.Bind(ctx, "session", 42, now, now.Add(time.Minute)) + if err != nil || bound != 42 { + t.Fatalf("first bind = %d, err = %v", bound, err) + } + bound, err = store.Bind(ctx, "session", 99, now.Add(30*time.Second), now.Add(90*time.Second)) + if err != nil || bound != 42 { + t.Fatalf("existing bind = %d, err = %v", bound, err) + } + if id, ok, err := store.Get(ctx, "session", now.Add(75*time.Second)); err != nil || !ok || id != 42 { + t.Fatalf("refreshed bind = %d, %v, err = %v", id, ok, err) + } + if _, ok, err := store.Get(ctx, "session", now.Add(100*time.Second)); err != nil || ok { + t.Fatalf("expired refreshed bind remains available: ok=%v err=%v", ok, err) + } +} + func TestDeviceSessionStoreCleansExpiredAndStaysBounded(t *testing.T) { ctx := context.Background() store := NewDeviceSessionStore() diff --git a/backend/internal/infra/runtime/redis/store.go b/backend/internal/infra/runtime/redis/store.go index e251743c..784931fc 100644 --- a/backend/internal/infra/runtime/redis/store.go +++ b/backend/internal/infra/runtime/redis/store.go @@ -65,6 +65,25 @@ if redis.call('PTTL', KEYS[2]) < tonumber(ARGV[2]) then redis.call('PEXPIRE', KE return 1 `) +var bindStickyScript = redisclient.NewScript(` +local selected = redis.call('GET', KEYS[1]) +if not selected then selected = ARGV[1] end +local accountSetKey = ARGV[3] .. selected +redis.call('SET', KEYS[1], selected, 'PX', ARGV[2]) +redis.call('ZREMRANGEBYSCORE', accountSetKey, '-inf', ARGV[4]) +redis.call('ZADD', accountSetKey, ARGV[5], KEYS[1]) +local excess = redis.call('ZCARD', accountSetKey) - tonumber(ARGV[6]) +if excess > 0 then + local stale = redis.call('ZRANGE', accountSetKey, 0, excess - 1) + for _, key in ipairs(stale) do + if redis.call('GET', key) == selected then redis.call('DEL', key) end + redis.call('ZREM', accountSetKey, key) + end +end +if redis.call('PTTL', accountSetKey) < tonumber(ARGV[2]) then redis.call('PEXPIRE', accountSetKey, ARGV[2]) end +return selected +`) + var deleteStickyByAccountScript = redisclient.NewScript(` local members = redis.call('ZRANGE', KEYS[1], 0, -1) local deleted = 0 @@ -292,6 +311,32 @@ func (s *Store) Get(ctx context.Context, key string, now time.Time) (uint64, boo return id, err == nil, err } +func (s *Store) Bind(ctx context.Context, key string, proposedAccountID uint64, now, expiresAt time.Time) (uint64, error) { + if key == "" || proposedAccountID == 0 { + return proposedAccountID, nil + } + ttl := time.Until(expiresAt) + if ttl <= 0 { + return proposedAccountID, nil + } + id := strconv.FormatUint(proposedAccountID, 10) + value, err := bindStickyScript.Run( + ctx, + s.client, + []string{s.key("sticky", key)}, + id, + ttl.Milliseconds(), + s.prefix+"sticky-account:", + now.UnixMilli(), + expiresAt.UnixMilli(), + maxStickyBindingsPerAccount, + ).Uint64() + if err != nil { + return 0, err + } + return value, nil +} + func (s *Store) Set(ctx context.Context, key string, accountID uint64, expiresAt time.Time) error { ttl := time.Until(expiresAt) if ttl <= 0 { diff --git a/backend/internal/infra/runtime/redis/store_integration_test.go b/backend/internal/infra/runtime/redis/store_integration_test.go index 1f4c146f..2f359513 100644 --- a/backend/internal/infra/runtime/redis/store_integration_test.go +++ b/backend/internal/infra/runtime/redis/store_integration_test.go @@ -3,6 +3,7 @@ package redis import ( "context" "os" + "sync" "testing" "time" @@ -45,7 +46,56 @@ func TestRedisRuntimeStoreIntegration(t *testing.T) { if id, ok, err := store.Get(ctx, "sticky", time.Now().UTC()); err != nil || !ok || id != 42 { t.Fatalf("sticky = %d, %v, %v", id, ok, err) } - if err := store.DeleteByAccount(ctx, 42); err != nil { + if id, err := store.Bind(ctx, "sticky", 7, time.Now().UTC(), time.Now().UTC().Add(2*time.Minute)); err != nil || id != 42 { + t.Fatalf("atomic sticky bind = %d, err = %v", id, err) + } + if err := store.Set(ctx, "sticky", 7, time.Now().UTC().Add(time.Minute)); err != nil { + t.Fatal(err) + } + if err := store.DeleteByAccount(ctx, 7); err != nil { + t.Fatal(err) + } + if _, ok, err := store.Get(ctx, "sticky", time.Now().UTC()); err != nil || ok { + t.Fatalf("deleted sticky remains available: ok=%v err=%v", ok, err) + } + + const bindWorkers = 16 + start := make(chan struct{}) + results := make(chan uint64, bindWorkers) + errors := make(chan error, bindWorkers) + var bindGroup sync.WaitGroup + for index := range bindWorkers { + bindGroup.Add(1) + go func(accountID uint64) { + defer bindGroup.Done() + <-start + id, err := store.Bind(ctx, "sticky-race", accountID, time.Now().UTC(), time.Now().UTC().Add(time.Minute)) + results <- id + errors <- err + }(uint64(index + 1)) + } + close(start) + bindGroup.Wait() + close(results) + close(errors) + var winner uint64 + for err := range errors { + if err != nil { + t.Fatal(err) + } + } + for id := range results { + if winner == 0 { + winner = id + } + if id != winner { + t.Fatalf("concurrent bind returned multiple accounts: first=%d current=%d", winner, id) + } + } + if winner == 0 { + t.Fatal("concurrent bind did not select an account") + } + if err := store.DeleteByAccount(ctx, winner); err != nil { t.Fatal(err) } diff --git a/backend/internal/repository/runtime.go b/backend/internal/repository/runtime.go index 10ce99ea..c855599e 100644 --- a/backend/internal/repository/runtime.go +++ b/backend/internal/repository/runtime.go @@ -23,10 +23,13 @@ type ConcurrencySnapshotReader interface { CurrentMany(ctx context.Context, keys []string) (map[string]int, error) } -// StickySessionRepository 定义有过期时间的 prompt_cache_key 账号粘滞状态。 +// StickySessionRepository 定义有过期时间的会话账号粘滞状态。 type StickySessionRepository interface { - Get(ctx context.Context, promptCacheKey string, now time.Time) (uint64, bool, error) - Set(ctx context.Context, promptCacheKey string, accountID uint64, expiresAt time.Time) error + Get(ctx context.Context, affinityKey string, now time.Time) (uint64, bool, error) + // Bind 原子保留已有有效绑定并刷新有效期;仅在绑定不存在或已过期时采用 proposedAccountID。 + Bind(ctx context.Context, affinityKey string, proposedAccountID uint64, now, expiresAt time.Time) (accountID uint64, err error) + // Set 强制替换绑定,仅用于原账号已经确定不再适合当前请求时重新绑定。 + Set(ctx context.Context, affinityKey string, accountID uint64, expiresAt time.Time) error DeleteByAccount(ctx context.Context, accountID uint64) error } diff --git a/backend/internal/transport/http/inference/prompt_cache.go b/backend/internal/transport/http/inference/prompt_cache.go index 23ed17cf..8669a4fe 100644 --- a/backend/internal/transport/http/inference/prompt_cache.go +++ b/backend/internal/transport/http/inference/prompt_cache.go @@ -13,12 +13,19 @@ func extractPromptCacheSeed(headers http.Header, body []byte) string { if seed := normalizePromptCacheSeed(headers.Get("X-Claude-Code-Session-Id")); seed != "" { return seed } + for _, name := range []string{"X-Session-ID", "Session-Id", "Session_id"} { + if seed := normalizePromptCacheSeed(headers.Get(name)); seed != "" { + return seed + } + } var payload struct { Metadata struct { SessionID string `json:"session_id"` SessionIDCamel string `json:"sessionId"` UserID string `json:"user_id"` } `json:"metadata"` + ConversationID string `json:"conversation_id"` + ConversationIDCamel string `json:"conversationId"` } if json.Unmarshal(body, &payload) != nil { return "" @@ -29,7 +36,13 @@ func extractPromptCacheSeed(headers http.Header, body []byte) string { if seed := normalizePromptCacheSeed(payload.Metadata.SessionIDCamel); seed != "" { return seed } - return promptCacheSeedFromUserID(payload.Metadata.UserID) + if seed := promptCacheSeedFromUserID(payload.Metadata.UserID); seed != "" { + return seed + } + if seed := normalizePromptCacheSeed(payload.ConversationID); seed != "" { + return seed + } + return normalizePromptCacheSeed(payload.ConversationIDCamel) } func promptCacheSeedFromUserID(userID string) string { diff --git a/backend/internal/transport/http/inference/prompt_cache_test.go b/backend/internal/transport/http/inference/prompt_cache_test.go index 10674fea..032a36c4 100644 --- a/backend/internal/transport/http/inference/prompt_cache_test.go +++ b/backend/internal/transport/http/inference/prompt_cache_test.go @@ -13,11 +13,17 @@ func TestExtractPromptCacheSeedSupportsClaudeCodeForms(t *testing.T) { body string want string }{ - {name: "header", headers: http.Header{"X-Claude-Code-Session-Id": {"header-session"}}, body: `{"metadata":{"session_id":"body-session"}}`, want: "header-session"}, + {name: "claude header", headers: http.Header{"X-Claude-Code-Session-Id": {"claude-session"}, "X-Session-Id": {"generic-session"}}, body: `{"metadata":{"session_id":"body-session"}}`, want: "claude-session"}, + {name: "generic header", headers: http.Header{"X-Session-Id": {"generic-session"}}, want: "generic-session"}, + {name: "codex hyphen header", headers: http.Header{"Session-Id": {"codex-session"}}, want: "codex-session"}, + {name: "codex underscore header", headers: http.Header{"Session_id": {"legacy-codex-session"}}, want: "legacy-codex-session"}, {name: "metadata snake case", body: `{"metadata":{"session_id":"snake-session"}}`, want: "snake-session"}, {name: "metadata camel case", body: `{"metadata":{"sessionId":"camel-session"}}`, want: "camel-session"}, {name: "embedded json user id", body: `{"metadata":{"user_id":"{\"device_id\":\"d1\",\"session_id\":\"embedded-session\"}"}}`, want: "embedded-session"}, {name: "suffix user id", body: `{"metadata":{"user_id":"user_account_session_123e4567-e89b-12d3-a456-426614174000"}}`, want: "123e4567-e89b-12d3-a456-426614174000"}, + {name: "conversation snake case", body: `{"conversation_id":"conversation-session"}`, want: "conversation-session"}, + {name: "conversation camel case", body: `{"conversationId":"camel-conversation"}`, want: "camel-conversation"}, + {name: "per request id ignored", headers: http.Header{"X-Client-Request-Id": {"request-123"}}, want: ""}, {name: "ordinary user id", body: `{"metadata":{"user_id":"user-123"}}`, want: ""}, } for _, test := range tests { diff --git a/backend/internal/transport/http/settings/handler.go b/backend/internal/transport/http/settings/handler.go index a7404db9..f8e8238e 100644 --- a/backend/internal/transport/http/settings/handler.go +++ b/backend/internal/transport/http/settings/handler.go @@ -39,7 +39,6 @@ type serverConfigDTO struct { type providerConsoleConfigDTO struct { BaseURL string `json:"baseURL"` - UserAgent string `json:"userAgent"` ChatTimeout string `json:"chatTimeout"` } @@ -170,8 +169,7 @@ func (value settingsConfigDTO) toApplication() settingsapp.EditableConfig { RecoveryBackoffBase: value.ProviderWeb.RecoveryBackoffBase, RecoveryBackoffMax: value.ProviderWeb.RecoveryBackoffMax, }, ProviderConsole: settingsapp.ProviderConsoleConfig{ - BaseURL: value.ProviderConsole.BaseURL, UserAgent: value.ProviderConsole.UserAgent, - ChatTimeout: value.ProviderConsole.ChatTimeout, + BaseURL: value.ProviderConsole.BaseURL, ChatTimeout: value.ProviderConsole.ChatTimeout, }, Batch: settingsapp.BatchConfig{ ImportConcurrency: value.Batch.ImportConcurrency, ConversionConcurrency: value.Batch.ConversionConcurrency, @@ -219,8 +217,7 @@ func newSettingsResponse(value settingsapp.Snapshot) settingsResponse { RecoveryBackoffBase: config.ProviderWeb.RecoveryBackoffBase, RecoveryBackoffMax: config.ProviderWeb.RecoveryBackoffMax, }, ProviderConsole: providerConsoleConfigDTO{ - BaseURL: config.ProviderConsole.BaseURL, UserAgent: config.ProviderConsole.UserAgent, - ChatTimeout: config.ProviderConsole.ChatTimeout, + BaseURL: config.ProviderConsole.BaseURL, ChatTimeout: config.ProviderConsole.ChatTimeout, }, Batch: batchConfigDTO{ ImportConcurrency: config.Batch.ImportConcurrency, ConversionConcurrency: config.Batch.ConversionConcurrency, diff --git a/frontend/src/features/settings/settings-api.ts b/frontend/src/features/settings/settings-api.ts index f5240013..f4dfe85e 100644 --- a/frontend/src/features/settings/settings-api.ts +++ b/frontend/src/features/settings/settings-api.ts @@ -11,7 +11,7 @@ export type SettingsConfigDTO = { mediaConcurrency: number; allowNSFW: boolean; recoveryBackoffBase: string; recoveryBackoffMax: string; }; - providerConsole: { baseURL: string; userAgent: string; chatTimeout: string }; + providerConsole: { baseURL: string; chatTimeout: string }; batch: { importConcurrency: number; conversionConcurrency: number; syncConcurrency: number; refreshConcurrency: number; randomDelay: string }; media: { maxImageBytes: number; maxTotalBytes: number; cleanupThresholdPercent: number; @@ -53,7 +53,7 @@ const settingsConfigValidator = hasShape({ statsigMode: isOneOf("manual", "url"), statsigManualValue: isOptional(isString), statsigManualConfigured: isBoolean, statsigSignerURL: isString, mediaConcurrency: isNumber, allowNSFW: isBoolean, recoveryBackoffBase: isString, recoveryBackoffMax: isString, }), - providerConsole: hasShape({ baseURL: isString, userAgent: isString, chatTimeout: isString }), + providerConsole: hasShape({ baseURL: isString, chatTimeout: isString }), batch: hasShape({ importConcurrency: isNumber, conversionConcurrency: isNumber, syncConcurrency: isNumber, refreshConcurrency: isNumber, randomDelay: isString }), media: hasShape({ maxImageBytes: isNumber, maxTotalBytes: isNumber, cleanupThresholdPercent: isNumber, cleanupInterval: isString }), frontend: hasShape({ publicApiBaseURL: isString }), diff --git a/frontend/src/features/settings/settings-model.ts b/frontend/src/features/settings/settings-model.ts index 75aa5fd3..ea73ed85 100644 --- a/frontend/src/features/settings/settings-model.ts +++ b/frontend/src/features/settings/settings-model.ts @@ -78,7 +78,6 @@ export const settingsSchema = z.object({ }), providerConsole: z.object({ baseURL: z.url().refine((value) => value.startsWith("https://")), - userAgent: z.string().trim().min(1).max(512), chatTimeout: consoleChatDuration, }), batch: z.object({ diff --git a/frontend/src/features/settings/settings-page.tsx b/frontend/src/features/settings/settings-page.tsx index 7edfe25e..73b22599 100644 --- a/frontend/src/features/settings/settings-page.tsx +++ b/frontend/src/features/settings/settings-page.tsx @@ -131,7 +131,6 @@ export function SettingsPage() {
- } />
diff --git a/frontend/src/shared/i18n/index.ts b/frontend/src/shared/i18n/index.ts index e2415b4f..d6f22470 100644 --- a/frontend/src/shared/i18n/index.ts +++ b/frontend/src/shared/i18n/index.ts @@ -48,7 +48,6 @@ const resources = { accountBreakdown: "Build {{build}} · Web {{web}} · Console {{console}}", availableBreakdown: "Build {{build}} · Web {{web}} · Console {{console}} 可用", baseURL: "上游地址", - userAgent: "User-Agent", chatTimeout: "聊天超时", }, accountCredential: { @@ -882,7 +881,6 @@ const resources = { accountBreakdown: "Build {{build}} · Web {{web}} · Console {{console}}", availableBreakdown: "Build {{build}} · Web {{web}} · Console {{console}} available", baseURL: "Upstream URL", - userAgent: "User-Agent", chatTimeout: "Chat timeout", }, accountCredential: {