Merge remote-tracking branch 'origin/main' into pr4241-fix

This commit is contained in:
shaw committed 2026-07-15 16:11:28 +08:00
commit bdb5be1c42
243 files changed
+31305 -1726

No files matched your search

+18 -6
View File
@@ -163,6 +163,12 @@ Model authenticity: no content intervention or secondary filtering — experienc
</td>
</tr>
<tr>
<td width="180"><a href="http://aimzoon.com"><img src="assets/partners/logos/aimzoon.jpg" alt="aimzoon" width="150"></a></td>
<td>Thanks to Aimzoon for sponsoring this project! <a href="http://aimzoon.com">Aimzoon</a> provides stable, cost-effective AI API access services, enabling developers to quickly connect popular AI services to coding tools such as Codex, Claude Code, and Gemini CLI. No complex configuration — faster onboarding, more stable calls, and lower costs. Ongoing promotions including discounted Codex rates and special pricing, with free trial credits upon registration, bringing AI coding into your daily workflow. <a href="http://aimzoon.com">Click here</a> to register and try it out!
</td>
</tr>
</table>
## Overview
@@ -605,12 +611,19 @@ per-turn user and account concurrency slots, which are released between turns.
```yaml
gateway:
openai_ws:
# Total time to receive and decompress the first client message.
client_first_message_timeout_seconds: 30
# Close a client socket idle between completed turns; 0 disables this safeguard.
ingress_inter_turn_idle_timeout_seconds: 300
# Distributed API-key limit for live client ingress sessions; 0 disables it.
max_ingress_connections_per_api_key: 64
```
The first-message timeout is a total read deadline. Deployments that accept
large contexts or image-heavy requests over slower links can raise it to
120-300 seconds. It expires before HTTP bridge routing, so bridge mode does not
override this limit.
The connection cap is coordinated through Redis using a 60-second lease that
is refreshed every 20 seconds. A process that cannot confirm a lease for a
full lease lifetime closes its local WebSocket rather than continuing outside
@@ -728,14 +741,13 @@ For API-key accounts, select **Grok → API Key** in the create-account dialog.
```toml
[models]
default = "sub2api-grok"
web_search = "sub2api-grok"
default = "grok"
web_search = "grok"
[model."sub2api-grok"]
[model."grok"]
model = "grok-4.5"
base_url = "https://your-sub2api.example.com/v1"
name = "Grok 4.5 via Sub2API"
description = "Grok 4.5 through a Sub2API Grok group"
name = "Grok 4.5"
api_key = "sk-your-sub2api-key"
api_backend = "responses"
context_window = 1000000
@@ -746,7 +758,7 @@ Back up an existing `config.toml` before merging the entry. The file contains a
```bash
grok inspect
grok -p "Reply with sub2api-ok" -m sub2api-grok
grok -p "Reply with sub2api-ok" -m grok
```
The `base_url` above is the public Sub2API URL ending in `/v1`, not `api.x.ai` or the internal xAI OAuth proxy URL.
+5
View File
@@ -166,6 +166,11 @@
</td>
</tr>
<tr>
<td width="180"><a href="http://aimzoon.com"><img src="assets/partners/logos/aimzoon.jpg" alt="aimzoon" width="150"></a></td>
<td>感谢 Aimzoon 对本项目的赞助! <a href="http://aimzoon.com">Aimzoon</a> 提供稳定、高性价比的 AI API 接入服务,支持开发者将常用 AI 服务快速接入 Codex、Claude Code、Gemini CLI 等编程工具。无需复杂配置,更快接入,更稳调用,更省成本。codex倍率优惠,特价倍率等促销不断,注册即送免费体验额度,让 AI 编程真正进入日常工作流。<a href="http://aimzoon.com">点击这里</a>注册体验!
</td>
</tr>
</table>
+6
View File
@@ -161,6 +161,12 @@
</td>
</tr>
<tr>
<td width="180"><a href="http://aimzoon.com"><img src="assets/partners/logos/aimzoon.jpg" alt="aimzoon" width="150"></a></td>
<td>Aimzoon のご支援に感謝します!<a href="http://aimzoon.com">Aimzoon</a> は安定してコストパフォーマンスに優れた AI API 接続サービスを提供し、開発者が主要な AI サービスを Codex、Claude Code、Gemini CLI などのコーディングツールへ素早く接続できるようにします。複雑な設定は不要で、より速い接続、より安定した呼び出し、より低いコストを実現。Codex レート割引や特価レートなどのキャンペーンも随時開催中、登録するだけで無料お試しクレジットをプレゼント。AI コーディングを日常のワークフローへ。<a href="http://aimzoon.com">こちら</a>から登録してお試しください!
</td>
</tr>
</table>
## 概要
Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

+1 -1
View File
@@ -1 +1 @@
0.1.153
0.1.155
+15 -14
View File
@@ -70,6 +70,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
concurrencyCache := repository.ProvideConcurrencyCache(redisClient, configConfig)
schedulerCache := repository.ProvideSchedulerCache(redisClient, configConfig)
accountRepository := repository.NewAccountRepository(client, db, schedulerCache)
adminAccountRepository := repository.NewAdminAccountRepository(client, db, schedulerCache)
concurrencyService := service.ProvideConcurrencyService(concurrencyCache, accountRepository, configConfig)
apiKeyService := service.ProvideAPIKeyService(apiKeyRepository, userRepository, groupRepository, userSubscriptionRepository, userGroupRateRepository, apiKeyCache, configConfig, billingCacheService, concurrencyService)
apiKeyAuthCacheInvalidator := service.ProvideAPIKeyAuthCacheInvalidator(apiKeyService)
@@ -96,9 +97,6 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
usageLogRepository := repository.NewUsageLogRepository(client, db)
usageService := service.NewUsageService(usageLogRepository, userRepository, client, apiKeyAuthCacheInvalidator)
opsRepository := repository.NewOpsRepository(db)
batchImageRepository := repository.NewBatchImageRepository(db)
batchImageQueue := repository.NewBatchImageQueue(redisClient, configConfig)
batchImageDownloadLimiter := repository.NewBatchImageDownloadLimiter(redisClient, configConfig)
usageBillingRepository := repository.NewUsageBillingRepository(client, db)
gatewayCache := repository.NewGatewayCache(redisClient)
schedulerOutboxRepository := repository.NewSchedulerOutboxRepository(db)
@@ -137,11 +135,6 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
channelRepository := repository.NewChannelRepository(db)
channelService := service.NewChannelService(channelRepository, groupRepository, apiKeyAuthCacheInvalidator, pricingService)
modelPricingResolver := service.NewModelPricingResolver(channelService, billingService)
batchImageModelPricingResolver := service.ProvideBatchImageModelPricingResolver(modelPricingResolver)
batchImagePublicService := service.NewBatchImagePublicService(batchImageRepository, accountRepository, groupRepository, userGroupRateRepository, batchImageQueue, batchImageModelPricingResolver, usageBillingRepository, apiKeyAuthCacheInvalidator, configConfig)
batchImageDownloadService := service.NewBatchImageDownloadService(batchImageRepository, accountRepository, batchImageDownloadLimiter, configConfig)
batchImageCleanupService := service.ProvideBatchImageCleanupService(batchImageRepository, accountRepository, configConfig)
batchImageWorkerRuntime := service.ProvideBatchImageWorkerRuntime(batchImageRepository, accountRepository, batchImageQueue, usageBillingRepository, usageLogRepository, batchImageModelPricingResolver, apiKeyAuthCacheInvalidator, configConfig)
notificationEmailService := service.NewNotificationEmailService(settingRepository, emailService)
balanceNotifyService := service.ProvideBalanceNotifyService(emailService, settingRepository, accountRepository, notificationEmailService)
gatewayService := service.NewGatewayService(accountRepository, groupRepository, usageLogRepository, usageBillingRepository, userRepository, userSubscriptionRepository, userGroupRateRepository, gatewayCache, configConfig, schedulerSnapshotService, concurrencyService, billingService, rateLimitService, billingCacheService, identityService, httpUpstream, deferredService, claudeTokenProvider, sessionLimitCache, rpmCache, digestSessionStore, settingService, tlsFingerprintProfileService, channelService, modelPricingResolver, balanceNotifyService, serviceUserPlatformQuotaRepository)
@@ -183,7 +176,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
dashboardHandler := admin.NewDashboardHandler(dashboardService, dashboardAggregationService)
proxyExitInfoProber := repository.NewProxyExitInfoProber(configConfig)
proxyLatencyCache := repository.NewProxyLatencyCache(redisClient)
adminService := service.NewAdminService(userRepository, groupRepository, accountRepository, proxyRepository, apiKeyRepository, redeemCodeRepository, userGroupRateRepository, userRPMCache, billingCacheService, proxyExitInfoProber, proxyLatencyCache, apiKeyAuthCacheInvalidator, client, settingService, subscriptionService, userSubscriptionRepository, privacyClientFactory, openAIGatewayService)
adminService := service.NewAdminService(userRepository, groupRepository, adminAccountRepository, proxyRepository, apiKeyRepository, redeemCodeRepository, userGroupRateRepository, userRPMCache, billingCacheService, proxyExitInfoProber, proxyLatencyCache, apiKeyAuthCacheInvalidator, client, settingService, subscriptionService, userSubscriptionRepository, privacyClientFactory, openAIGatewayService)
adminUserHandler := admin.NewUserHandler(adminService, concurrencyService, serviceUserPlatformQuotaRepository, billingCache)
groupCapacityService := service.NewGroupCapacityService(accountRepository, groupRepository, concurrencyService, sessionLimitCache, rpmCache)
groupHandler := admin.NewGroupHandler(adminService, dashboardService, groupCapacityService)
@@ -191,10 +184,10 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
antigravityQuotaFetcher := service.NewAntigravityQuotaFetcher(proxyRepository)
grokQuotaFetcher := service.NewGrokQuotaFetcher()
grokQuotaService := service.ProvideGrokQuotaService(accountRepository, proxyRepository, grokTokenProvider, httpUpstream, usageLogRepository)
openAIQuotaService := service.ProvideOpenAIQuotaService(accountRepository, proxyRepository, openAITokenProvider, privacyClientFactory)
openAIQuotaService := service.ProvideOpenAIQuotaService(accountRepository, proxyRepository, openAITokenProvider, privacyClientFactory, openAIGatewayService)
usageCache := service.NewUsageCache()
accountUsageService := service.NewAccountUsageService(accountRepository, usageLogRepository, claudeUsageFetcher, geminiQuotaService, antigravityQuotaFetcher, grokQuotaFetcher, grokQuotaService, openAIQuotaService, usageCache, identityCache, tlsFingerprintProfileService)
accountTestService := service.NewAccountTestService(accountRepository, geminiTokenProvider, claudeTokenProvider, grokTokenProvider, antigravityGatewayService, httpUpstream, configConfig, tlsFingerprintProfileService)
accountUsageService := service.ProvideAccountUsageService(accountRepository, usageLogRepository, claudeUsageFetcher, geminiQuotaService, antigravityQuotaFetcher, grokQuotaFetcher, grokQuotaService, openAIQuotaService, usageCache, identityCache, tlsFingerprintProfileService, openAIGatewayService)
accountTestService := service.ProvideAccountTestService(accountRepository, geminiTokenProvider, claudeTokenProvider, grokTokenProvider, antigravityGatewayService, httpUpstream, configConfig, tlsFingerprintProfileService, openAIGatewayService)
crsSyncService := service.NewCRSSyncService(accountRepository, proxyRepository, oAuthService, openAIOAuthService, geminiOAuthService, configConfig)
accountHandler := admin.ProvideAccountHandler(adminService, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, grokOAuthService, rateLimitService, accountUsageService, accountTestService, concurrencyService, crsSyncService, sessionLimitCache, rpmCache, compositeTokenCacheInvalidator, grokQuotaService)
adminAnnouncementHandler := admin.NewAnnouncementHandler(announcementService)
@@ -208,7 +201,8 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
openAIOAuthHandler := admin.NewOpenAIOAuthHandler(openAIOAuthService, adminService, openAIQuotaService)
geminiOAuthHandler := admin.NewGeminiOAuthHandler(geminiOAuthService)
antigravityOAuthHandler := admin.NewAntigravityOAuthHandler(antigravityOAuthService)
grokOAuthHandler := admin.NewGrokOAuthHandler(grokOAuthService, adminService, grokQuotaService)
tokenRefreshService := service.ProvideTokenRefreshService(accountRepository, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, grokOAuthService, compositeTokenCacheInvalidator, schedulerCache, configConfig, tempUnschedCache, privacyClientFactory, proxyRepository, oAuthRefreshAPI, openAIGatewayService)
grokOAuthHandler := admin.NewGrokOAuthHandler(grokOAuthService, adminService, grokQuotaService, tokenRefreshService)
proxyHandler := admin.NewProxyHandler(adminService)
adminRedeemHandler := admin.NewRedeemHandler(adminService, redeemService)
promoHandler := admin.NewPromoHandler(promoService)
@@ -267,6 +261,13 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
handlerPaymentHandler := handler.NewPaymentHandler(paymentService, paymentConfigService)
paymentWebhookHandler := handler.NewPaymentWebhookHandler(paymentService, registry)
availableChannelHandler := handler.NewAvailableChannelHandler(channelService, apiKeyService, settingService)
batchImageRepository := repository.NewBatchImageRepository(db)
batchImageQueue := repository.NewBatchImageQueue(redisClient, configConfig)
batchImageModelPricingResolver := service.ProvideBatchImageModelPricingResolver(modelPricingResolver)
batchImagePublicService := service.NewBatchImagePublicService(batchImageRepository, accountRepository, groupRepository, userGroupRateRepository, batchImageQueue, batchImageModelPricingResolver, usageBillingRepository, apiKeyAuthCacheInvalidator, configConfig)
batchImageDownloadLimiter := repository.NewBatchImageDownloadLimiter(redisClient, configConfig)
batchImageDownloadService := service.NewBatchImageDownloadService(batchImageRepository, accountRepository, batchImageDownloadLimiter, configConfig)
batchImageCleanupService := service.ProvideBatchImageCleanupService(batchImageRepository, accountRepository, configConfig)
batchImageHandler := handler.NewBatchImageHandler(batchImagePublicService, batchImageDownloadService, batchImageCleanupService)
idempotencyCoordinator := service.ProvideIdempotencyCoordinator(idempotencyRepository, configConfig)
idempotencyCleanupService := service.ProvideIdempotencyCleanupService(idempotencyRepository, configConfig)
@@ -281,10 +282,10 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
opsAlertEvaluatorService := service.ProvideOpsAlertEvaluatorService(opsService, opsRepository, emailService, redisClient, configConfig, proxyRepository)
opsCleanupService := service.ProvideOpsCleanupService(opsRepository, db, redisClient, configConfig, channelMonitorService, settingRepository, opsService)
opsScheduledReportService := service.ProvideOpsScheduledReportService(opsService, userService, emailService, redisClient, configConfig)
tokenRefreshService := service.ProvideTokenRefreshService(accountRepository, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, grokOAuthService, compositeTokenCacheInvalidator, schedulerCache, configConfig, tempUnschedCache, privacyClientFactory, proxyRepository, oAuthRefreshAPI, openAIGatewayService)
accountExpiryService := service.ProvideAccountExpiryService(accountRepository)
proxyExpiryService := service.ProvideProxyExpiryService(proxyRepository)
subscriptionExpiryService := service.ProvideSubscriptionExpiryService(userSubscriptionRepository, settingRepository, notificationEmailService, leaderLockCache, db)
batchImageWorkerRuntime := service.ProvideBatchImageWorkerRuntime(batchImageRepository, accountRepository, batchImageQueue, usageBillingRepository, usageLogRepository, batchImageModelPricingResolver, apiKeyAuthCacheInvalidator, configConfig)
scheduledTestRunnerService := service.ProvideScheduledTestRunnerService(scheduledTestPlanRepository, scheduledTestService, accountTestService, rateLimitService, configConfig)
paymentOrderExpiryService := service.ProvidePaymentOrderExpiryService(paymentService, leaderLockCache, db)
channelMonitorRunner := service.ProvideChannelMonitorRunner(channelMonitorService, settingService)
+43
View File
@@ -580,6 +580,18 @@ type TokenRefreshConfig struct {
MaxRetries int `mapstructure:"max_retries"`
// 重试退避基础时间(秒)
RetryBackoffSeconds int `mapstructure:"retry_backoff_seconds"`
// 每次从数据库读取的候选账号上限
CandidatePageSize int `mapstructure:"candidate_page_size"`
// 每个平台允许的并发刷新数
ProviderConcurrency int `mapstructure:"provider_concurrency"`
// 每个平台、每个进程允许的刷新请求速率
ProviderQPS int `mapstructure:"provider_qps"`
// 一个周期内连续临时失败达到此值后停止该平台
ProviderFailureThreshold int `mapstructure:"provider_failure_threshold"`
// 单次上游刷新尝试的超时(秒)
AttemptTimeoutSeconds int `mapstructure:"attempt_timeout_seconds"`
// 单个后台刷新周期的总超时(秒)
CycleTimeoutSeconds int `mapstructure:"cycle_timeout_seconds"`
}
type PricingConfig struct {
@@ -748,6 +760,11 @@ type GatewayConfig struct {
// OpenAIResponseHeaderTimeout: OpenAI/Codex 上游等待响应头的超时时间(秒),0表示无超时
// OpenAI/Codex 请求可能在上游排队较久;默认不使用通用响应头超时截断。
OpenAIResponseHeaderTimeout int `mapstructure:"openai_response_header_timeout"`
// OpenAIFirstOutputTimeoutSeconds: native HTTP Responses 首个语义输出超时(秒),0表示禁用。
OpenAIFirstOutputTimeoutSeconds int `mapstructure:"openai_first_output_timeout_seconds"`
// OpenAIHighEffortFirstOutputTimeoutSeconds: high/xhigh/max 推理的首个语义输出超时(秒)。
// 0 表示回退到 OpenAIFirstOutputTimeoutSeconds。
OpenAIHighEffortFirstOutputTimeoutSeconds int `mapstructure:"openai_high_effort_first_output_timeout_seconds"`
// 请求体最大字节数,用于网关请求体大小限制
MaxBodySize int64 `mapstructure:"max_body_size"`
// 非流式上游响应体读取上限(字节),用于防止无界读取导致内存放大
@@ -919,6 +936,9 @@ func (c *UserMessageQueueConfig) GetEffectiveMode() string {
return ""
}
// DefaultOpenAIWSClientFirstMessageTimeoutSeconds preserves the legacy ingress deadline.
const DefaultOpenAIWSClientFirstMessageTimeoutSeconds = 30
// GatewayOpenAIWSConfig OpenAI Responses WebSocket 配置。
// 注意:默认全局开启;如需回滚可使用 force_http 或关闭 enabled。
type GatewayOpenAIWSConfig struct {
@@ -926,6 +946,9 @@ type GatewayOpenAIWSConfig struct {
ModeRouterV2Enabled bool `mapstructure:"mode_router_v2_enabled"`
// IngressModeDefault: ingress 默认模式(off/ctx_pool/passthrough/http_bridge)
IngressModeDefault string `mapstructure:"ingress_mode_default"`
// ClientFirstMessageTimeoutSeconds bounds the total time to read and decompress
// the first client response.create message after the WebSocket upgrade.
ClientFirstMessageTimeoutSeconds int `mapstructure:"client_first_message_timeout_seconds"`
// IngressInterTurnIdleTimeoutSeconds bounds the time a client may remain idle
// between completed ingress turns. Zero disables this protection.
IngressInterTurnIdleTimeoutSeconds int `mapstructure:"ingress_inter_turn_idle_timeout_seconds"`
@@ -1944,6 +1967,8 @@ func setDefaults() {
// Gateway
viper.SetDefault("gateway.response_header_timeout", 600) // 600秒(10分钟)等待上游响应头,LLM高负载时可能排队较久
viper.SetDefault("gateway.openai_response_header_timeout", 0)
viper.SetDefault("gateway.openai_first_output_timeout_seconds", 0)
viper.SetDefault("gateway.openai_high_effort_first_output_timeout_seconds", 0)
viper.SetDefault("gateway.log_upstream_error_body", true)
viper.SetDefault("gateway.log_upstream_error_body_max_bytes", 2048)
viper.SetDefault("gateway.inject_beta_for_apikey", false)
@@ -1958,6 +1983,7 @@ func setDefaults() {
viper.SetDefault("gateway.openai_ws.enabled", true)
viper.SetDefault("gateway.openai_ws.mode_router_v2_enabled", false)
viper.SetDefault("gateway.openai_ws.ingress_mode_default", "ctx_pool")
viper.SetDefault("gateway.openai_ws.client_first_message_timeout_seconds", DefaultOpenAIWSClientFirstMessageTimeoutSeconds)
viper.SetDefault("gateway.openai_ws.ingress_inter_turn_idle_timeout_seconds", 300)
viper.SetDefault("gateway.openai_ws.max_ingress_connections_per_api_key", 64)
viper.SetDefault("gateway.openai_ws.oauth_enabled", true)
@@ -2098,6 +2124,12 @@ func setDefaults() {
viper.SetDefault("token_refresh.refresh_before_expiry_hours", 0.5) // 提前30分钟刷新(适配Google 1小时token)
viper.SetDefault("token_refresh.max_retries", 3) // 最多重试3次
viper.SetDefault("token_refresh.retry_backoff_seconds", 2) // 重试退避基础2秒
viper.SetDefault("token_refresh.candidate_page_size", 200)
viper.SetDefault("token_refresh.provider_concurrency", 4)
viper.SetDefault("token_refresh.provider_qps", 2)
viper.SetDefault("token_refresh.provider_failure_threshold", 3)
viper.SetDefault("token_refresh.attempt_timeout_seconds", 15)
viper.SetDefault("token_refresh.cycle_timeout_seconds", 240)
// Gemini OAuth - configure via environment variables or config file
// GEMINI_OAUTH_CLIENT_ID and GEMINI_OAUTH_CLIENT_SECRET
@@ -2651,6 +2683,14 @@ func (c *Config) Validate() error {
if c.Gateway.OpenAIResponseHeaderTimeout < 0 {
return fmt.Errorf("gateway.openai_response_header_timeout must be non-negative")
}
if c.Gateway.OpenAIFirstOutputTimeoutSeconds < 0 || c.Gateway.OpenAIFirstOutputTimeoutSeconds > 600 ||
(c.Gateway.OpenAIFirstOutputTimeoutSeconds > 0 && c.Gateway.OpenAIFirstOutputTimeoutSeconds < 30) {
return fmt.Errorf("gateway.openai_first_output_timeout_seconds must be 0 or between 30-600 seconds")
}
if c.Gateway.OpenAIHighEffortFirstOutputTimeoutSeconds < 0 || c.Gateway.OpenAIHighEffortFirstOutputTimeoutSeconds > 1800 ||
(c.Gateway.OpenAIHighEffortFirstOutputTimeoutSeconds > 0 && c.Gateway.OpenAIHighEffortFirstOutputTimeoutSeconds < 30) {
return fmt.Errorf("gateway.openai_high_effort_first_output_timeout_seconds must be 0 or between 30-1800 seconds")
}
if strings.TrimSpace(c.Gateway.ConnectionPoolIsolation) != "" {
switch c.Gateway.ConnectionPoolIsolation {
case ConnectionPoolIsolationProxy, ConnectionPoolIsolationAccount, ConnectionPoolIsolationAccountProxy:
@@ -2740,6 +2780,9 @@ func (c *Config) Validate() error {
if c.Gateway.OpenAIWS.MaxConnsPerAccount <= 0 {
return fmt.Errorf("gateway.openai_ws.max_conns_per_account must be positive")
}
if c.Gateway.OpenAIWS.ClientFirstMessageTimeoutSeconds <= 0 {
return fmt.Errorf("gateway.openai_ws.client_first_message_timeout_seconds must be positive")
}
if c.Gateway.OpenAIWS.IngressInterTurnIdleTimeoutSeconds < 0 {
return fmt.Errorf("gateway.openai_ws.ingress_inter_turn_idle_timeout_seconds must be non-negative")
}
+64
View File
@@ -98,6 +98,34 @@ func TestLoadDefaultSchedulingConfig(t *testing.T) {
}
}
func TestLoadDefaultOpenAIFirstOutputTimeoutsDisabled(t *testing.T) {
resetViperWithJWTSecret(t)
cfg, err := Load()
require.NoError(t, err)
require.Zero(t, cfg.Gateway.OpenAIFirstOutputTimeoutSeconds)
require.Zero(t, cfg.Gateway.OpenAIHighEffortFirstOutputTimeoutSeconds)
}
func TestLoadOpenAIFirstOutputTimeoutsFromEnv(t *testing.T) {
resetViperWithJWTSecret(t)
t.Setenv("GATEWAY_OPENAI_FIRST_OUTPUT_TIMEOUT_SECONDS", "90")
t.Setenv("GATEWAY_OPENAI_HIGH_EFFORT_FIRST_OUTPUT_TIMEOUT_SECONDS", "240")
cfg, err := Load()
require.NoError(t, err)
require.Equal(t, 90, cfg.Gateway.OpenAIFirstOutputTimeoutSeconds)
require.Equal(t, 240, cfg.Gateway.OpenAIHighEffortFirstOutputTimeoutSeconds)
}
func TestValidateOpenAIFirstOutputTimeoutMinimum(t *testing.T) {
resetViperWithJWTSecret(t)
cfg, err := Load()
require.NoError(t, err)
cfg.Gateway.OpenAIFirstOutputTimeoutSeconds = 30
require.NoError(t, cfg.Validate())
}
func TestLoadDefaultOpenAIWSConfig(t *testing.T) {
resetViperWithJWTSecret(t)
@@ -199,6 +227,13 @@ func TestLoadDefaultOpenAIWSConfig(t *testing.T) {
if cfg.Gateway.OpenAIWS.IngressModeDefault != "ctx_pool" {
t.Fatalf("Gateway.OpenAIWS.IngressModeDefault = %q, want %q", cfg.Gateway.OpenAIWS.IngressModeDefault, "ctx_pool")
}
if cfg.Gateway.OpenAIWS.ClientFirstMessageTimeoutSeconds != DefaultOpenAIWSClientFirstMessageTimeoutSeconds {
t.Fatalf(
"Gateway.OpenAIWS.ClientFirstMessageTimeoutSeconds = %d, want %d",
cfg.Gateway.OpenAIWS.ClientFirstMessageTimeoutSeconds,
DefaultOpenAIWSClientFirstMessageTimeoutSeconds,
)
}
if cfg.Gateway.OpenAIWS.IngressInterTurnIdleTimeoutSeconds != 300 {
t.Fatalf("Gateway.OpenAIWS.IngressInterTurnIdleTimeoutSeconds = %d, want 300", cfg.Gateway.OpenAIWS.IngressInterTurnIdleTimeoutSeconds)
}
@@ -207,6 +242,15 @@ func TestLoadDefaultOpenAIWSConfig(t *testing.T) {
}
}
func TestLoadOpenAIWSClientFirstMessageTimeoutFromEnv(t *testing.T) {
resetViperWithJWTSecret(t)
t.Setenv("GATEWAY_OPENAI_WS_CLIENT_FIRST_MESSAGE_TIMEOUT_SECONDS", "120")
cfg, err := Load()
require.NoError(t, err)
require.Equal(t, 120, cfg.Gateway.OpenAIWS.ClientFirstMessageTimeoutSeconds)
}
func TestLoadDefaultOpenAICompactModel(t *testing.T) {
resetViperWithJWTSecret(t)
@@ -1348,6 +1392,16 @@ func TestValidateConfigErrors(t *testing.T) {
mutate: func(c *Config) { c.Gateway.OpenAIResponseHeaderTimeout = -1 },
wantErr: "gateway.openai_response_header_timeout",
},
{
name: "gateway openai first output timeout below minimum",
mutate: func(c *Config) { c.Gateway.OpenAIFirstOutputTimeoutSeconds = 29 },
wantErr: "gateway.openai_first_output_timeout_seconds",
},
{
name: "gateway openai high effort first output timeout too large",
mutate: func(c *Config) { c.Gateway.OpenAIHighEffortFirstOutputTimeoutSeconds = 1801 },
wantErr: "gateway.openai_high_effort_first_output_timeout_seconds",
},
{
name: "gateway max idle conns",
mutate: func(c *Config) { c.Gateway.MaxIdleConns = 0 },
@@ -1682,6 +1736,16 @@ func TestValidateConfig_OpenAIWSRules(t *testing.T) {
mutate: func(c *Config) { c.Gateway.OpenAIWS.MaxConnsPerAccount = 0 },
wantErr: "gateway.openai_ws.max_conns_per_account",
},
{
name: "client_first_message_timeout_seconds 必须为正数",
mutate: func(c *Config) { c.Gateway.OpenAIWS.ClientFirstMessageTimeoutSeconds = 0 },
wantErr: "gateway.openai_ws.client_first_message_timeout_seconds",
},
{
name: "client_first_message_timeout_seconds 不能为负数",
mutate: func(c *Config) { c.Gateway.OpenAIWS.ClientFirstMessageTimeoutSeconds = -1 },
wantErr: "gateway.openai_ws.client_first_message_timeout_seconds",
},
{
name: "ingress_inter_turn_idle_timeout_seconds 不能为负数",
mutate: func(c *Config) { c.Gateway.OpenAIWS.IngressInterTurnIdleTimeoutSeconds = -1 },
@@ -0,0 +1,47 @@
package admin
import (
"crypto/ed25519"
"crypto/rand"
"crypto/x509"
"encoding/base64"
"testing"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/stretchr/testify/require"
)
func TestNormalizeCodexImportEntryAcceptsAgentIdentityAuthJSON(t *testing.T) {
_, privateKey, err := ed25519.GenerateKey(rand.Reader)
require.NoError(t, err)
der, err := x509.MarshalPKCS8PrivateKey(privateKey)
require.NoError(t, err)
privateKeyBase64 := base64.StdEncoding.EncodeToString(der)
item, err := normalizeCodexImportEntry(codexImportEntry{
Index: 1,
Value: map[string]any{
"auth_mode": "agentIdentity",
"agent_identity": map[string]any{
"agent_runtime_id": "runtime-import",
"agent_private_key": privateKeyBase64,
"account_id": "account-import",
"chatgpt_user_id": "user-import",
"email": "agent@example.invalid",
"plan_type": "pro",
"chatgpt_account_is_fedramp": false,
},
},
})
require.NoError(t, err)
require.NotNil(t, item)
require.True(t, item.IsAgentIdentity)
require.Equal(t, service.OpenAIAuthModeAgentIdentity, item.Credentials["auth_mode"])
require.Equal(t, "runtime-import", item.Credentials["agent_runtime_id"])
require.Equal(t, privateKeyBase64, item.Credentials["agent_private_key"])
require.Equal(t, "account-import", item.Credentials["chatgpt_account_id"])
require.Equal(t, "user-import", item.Credentials["chatgpt_user_id"])
require.NotContains(t, item.Credentials, "access_token")
require.NotContains(t, item.Credentials, "refresh_token")
require.NotEmpty(t, item.WarningTexts)
}
@@ -72,20 +72,25 @@ type codexImportEntry struct {
}
type codexImportAccount struct {
Name string
AccessToken string
RefreshToken string
IDToken string
Email string
AccountID string
UserID string
PlanType string
Organization string
Credentials map[string]any
Extra map[string]any
TokenExpiresAt *time.Time
IdentityKeys []string
WarningTexts []string
Name string
AccessToken string
RefreshToken string
IDToken string
Email string
AccountID string
UserID string
PlanType string
Organization string
AgentRuntimeID string
AgentPrivateKey string
AgentTaskID string
AgentFedRAMP bool
IsAgentIdentity bool
Credentials map[string]any
Extra map[string]any
TokenExpiresAt *time.Time
IdentityKeys []string
WarningTexts []string
}
type codexJWTClaims struct {
@@ -496,6 +501,41 @@ func normalizeCodexImportEntry(entry codexImportEntry) (*codexImportAccount, err
case string:
item.AccessToken = strings.TrimSpace(raw)
case map[string]any:
if agentIdentity, ok := firstCodexMap(raw, []string{"agent_identity"}, []string{"agentIdentity"}); ok || strings.EqualFold(firstCodexString(raw, []string{"auth_mode"}, []string{"authMode"}), service.OpenAIAuthModeAgentIdentity) {
if !ok {
agentIdentity = raw
}
item.IsAgentIdentity = true
item.AgentRuntimeID = firstCodexString(agentIdentity, []string{"agent_runtime_id"}, []string{"agentRuntimeId"})
item.AgentPrivateKey = firstCodexString(agentIdentity, []string{"agent_private_key"}, []string{"agentPrivateKey"})
item.AgentTaskID = firstCodexString(agentIdentity, []string{"task_id"}, []string{"taskId"})
item.AccountID = firstCodexString(agentIdentity, []string{"account_id"}, []string{"accountId"})
item.UserID = firstCodexString(agentIdentity, []string{"chatgpt_user_id"}, []string{"chatgptUserId"})
item.Email = firstCodexString(agentIdentity, []string{"email"})
item.PlanType = firstCodexString(agentIdentity, []string{"plan_type"}, []string{"planType"})
item.AgentFedRAMP = firstCodexBool(agentIdentity, []string{"chatgpt_account_is_fedramp"}, []string{"chatgptAccountIsFedramp"})
if item.AgentRuntimeID == "" || item.AgentPrivateKey == "" || item.AccountID == "" || item.UserID == "" {
return nil, errors.New("agent identity 缺少必要字段")
}
if err := service.ValidateOpenAIAgentIdentityPrivateKey(item.AgentPrivateKey); err != nil {
return nil, errors.New("agent identity private key 格式无效")
}
item.Credentials["auth_mode"] = service.OpenAIAuthModeAgentIdentity
item.Credentials["agent_runtime_id"] = item.AgentRuntimeID
item.Credentials["agent_private_key"] = item.AgentPrivateKey
item.Credentials["chatgpt_account_id"] = item.AccountID
item.Credentials["chatgpt_user_id"] = item.UserID
item.Credentials["chatgpt_account_is_fedramp"] = item.AgentFedRAMP
setCodexCredentialIfNotEmpty(item.Credentials, "task_id", item.AgentTaskID)
setCodexCredentialIfNotEmpty(item.Credentials, "email", item.Email)
setCodexCredentialIfNotEmpty(item.Credentials, "plan_type", item.PlanType)
if item.AgentTaskID == "" {
item.WarningTexts = append(item.WarningTexts, "未包含 task_id,首次请求会使用现有 runtime 注册新 task")
}
item.IdentityKeys = buildCodexAgentIdentityKeys(item.AccountID, item.UserID, item.Email, item.AgentRuntimeID)
item.Name = buildCodexImportAccountName(item, entry.Index)
return item, nil
}
item.AccessToken = firstCodexString(raw,
[]string{"tokens", "access_token"},
[]string{"tokens", "accessToken"},
@@ -577,6 +617,9 @@ func normalizeCodexImportEntry(entry codexImportEntry) (*codexImportAccount, err
return nil, fmt.Errorf("第 %d 条格式不支持", entry.Index)
}
if item.IsAgentIdentity {
return item, nil
}
if item.AccessToken == "" {
return nil, errors.New("缺少 accessToken/access_token")
}
@@ -812,6 +855,9 @@ func sanitizeCodexImportCredentialExtras(input map[string]any) map[string]any {
"openai_auth_mode": {},
"token_type": {},
"chatgpt_account_is_fedramp": {},
"agent_runtime_id": {},
"agent_private_key": {},
"task_id": {},
}
out := make(map[string]any, len(input))
for key, value := range input {
@@ -842,6 +888,14 @@ func buildCodexImportIdentityKeys(accountID, userID, email, accessToken, refresh
return buildCodexStoredIdentityKeys(accountID, userID, email, accessToken)
}
func buildCodexAgentIdentityKeys(accountID, userID, email, runtimeID string) []string {
keys := buildCodexStoredIdentityKeys(accountID, userID, email, "")
if runtimeID = strings.TrimSpace(runtimeID); runtimeID != "" {
keys = append([]string{"agent:" + runtimeID}, keys...)
}
return keys
}
// buildCodexStoredIdentityKeys 生成存量账号索引键,保留 user/account 维度,
// 让 accessToken-only 账号后续升级为完整 OAuth 时仍能命中并更新原账号。
func buildCodexStoredIdentityKeys(accountID, userID, email, accessToken string) []string {
@@ -891,6 +945,10 @@ func (i *codexAccountIndex) Add(account service.Account) {
for _, key := range keys {
i.accountsByKey[key] = upsertCodexAccount(i.accountsByKey[key], account)
}
if runtimeID := codexCredentialString(account.Credentials, "agent_runtime_id"); runtimeID != "" {
key := "agent:" + runtimeID
i.accountsByKey[key] = upsertCodexAccount(i.accountsByKey[key], account)
}
}
func (i *codexAccountIndex) remove(accountID int64) {
@@ -1043,6 +1101,38 @@ func firstCodexString(obj map[string]any, paths ...[]string) string {
return ""
}
func firstCodexMap(obj map[string]any, paths ...[]string) (map[string]any, bool) {
for _, path := range paths {
value, ok := codexPathValue(obj, path)
if !ok || value == nil {
continue
}
if mapped, ok := value.(map[string]any); ok {
return mapped, true
}
}
return nil, false
}
func firstCodexBool(obj map[string]any, paths ...[]string) bool {
for _, path := range paths {
value, ok := codexPathValue(obj, path)
if !ok {
continue
}
switch value := value.(type) {
case bool:
return value
case string:
parsed, err := strconv.ParseBool(strings.TrimSpace(value))
if err == nil {
return parsed
}
}
}
return false
}
func copyCodexExtraString(obj map[string]any, extra map[string]any, key string, path []string) {
value := firstCodexString(obj, path)
if value != "" {
@@ -863,6 +863,53 @@ func (h *AccountHandler) Create(c *gin.Context) {
response.Success(c, result.Data)
}
// Duplicate handles creating an independent account from an existing account's configuration.
// POST /api/v1/admin/accounts/:id/duplicate
func (h *AccountHandler) Duplicate(c *gin.Context) {
accountID, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
response.BadRequest(c, "Invalid account ID")
return
}
actorScope := adminActorScope(c)
result, err := executeAdminIdempotent(
c,
"admin.accounts.duplicate",
struct {
AccountID int64 `json:"account_id"`
}{AccountID: accountID},
service.DefaultWriteIdempotencyTTL(),
func(ctx context.Context) (any, error) {
account, execErr := h.adminService.DuplicateAccount(ctx, accountID, actorScope, c.GetHeader("Idempotency-Key"))
if execErr != nil {
return nil, execErr
}
return h.buildAccountResponseWithRuntime(ctx, account), nil
},
)
if err != nil {
reason := infraerrors.Reason(err)
if reason == infraerrors.Reason(service.ErrIdempotencyInProgress) || reason == infraerrors.Reason(service.ErrIdempotencyStoreUnavail) {
recovered, recoverErr := h.adminService.RecoverDuplicateAccount(c.Request.Context(), accountID, actorScope, c.GetHeader("Idempotency-Key"))
if recoverErr != nil {
slog.Warn("account_duplicate_recovery_failed", "account_id", accountID, "actor_scope", actorScope, "reason", reason, "error", recoverErr)
} else if recovered != nil {
c.Header("X-Idempotency-Recovered", "true")
response.Success(c, h.buildAccountResponseWithRuntime(c.Request.Context(), recovered))
return
}
}
response.ErrorFrom(c, err)
return
}
if result != nil && result.Replayed {
c.Header("X-Idempotency-Replayed", "true")
}
response.Success(c, result.Data)
}
// Update handles updating an account
// PUT /api/v1/admin/accounts/:id
func (h *AccountHandler) Update(c *gin.Context) {
@@ -0,0 +1,295 @@
//go:build unit
package admin
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
"time"
middleware2 "github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
type duplicateAccountAdminServiceStub struct {
service.AdminService
account *service.Account
calls int
recoverCalls int
accountID int64
actorScope string
operationKey string
recoverScope string
recoverKey string
recoverErr error
created bool
}
type blockingDuplicateAdminServiceStub struct {
service.AdminService
account *service.Account
started chan struct{}
release chan struct{}
calls atomic.Int32
recoverCalls atomic.Int32
recoverErr error
}
type failOnceMarkSucceededRepo struct {
*memoryIdempotencyRepoStub
failNext bool
}
func (r *failOnceMarkSucceededRepo) MarkSucceeded(ctx context.Context, id int64, responseStatus int, responseBody string, expiresAt time.Time) error {
if r.failNext {
r.failNext = false
return errors.New("mark succeeded failed")
}
return r.memoryIdempotencyRepoStub.MarkSucceeded(ctx, id, responseStatus, responseBody, expiresAt)
}
func (s *duplicateAccountAdminServiceStub) DuplicateAccount(_ context.Context, accountID int64, actorScope, operationKey string) (*service.Account, error) {
s.calls++
s.accountID = accountID
s.actorScope = actorScope
s.operationKey = operationKey
s.created = true
return s.account, nil
}
func (s *duplicateAccountAdminServiceStub) RecoverDuplicateAccount(_ context.Context, _ int64, actorScope, operationKey string) (*service.Account, error) {
s.recoverCalls++
s.recoverScope = actorScope
s.recoverKey = operationKey
if s.recoverErr != nil {
return nil, s.recoverErr
}
if !s.created {
return nil, nil
}
return s.account, nil
}
func (s *blockingDuplicateAdminServiceStub) DuplicateAccount(_ context.Context, _ int64, _, _ string) (*service.Account, error) {
s.calls.Add(1)
close(s.started)
<-s.release
return s.account, nil
}
func (s *blockingDuplicateAdminServiceStub) RecoverDuplicateAccount(_ context.Context, _ int64, _, _ string) (*service.Account, error) {
s.recoverCalls.Add(1)
return nil, s.recoverErr
}
func setupDuplicateAccountRouter(t *testing.T, svc service.AdminService) *gin.Engine {
t.Helper()
previousCoordinator := service.DefaultIdempotencyCoordinator()
service.SetDefaultIdempotencyCoordinator(nil)
t.Cleanup(func() { service.SetDefaultIdempotencyCoordinator(previousCoordinator) })
gin.SetMode(gin.TestMode)
router := gin.New()
router.Use(func(c *gin.Context) {
c.Set(string(middleware2.ContextKeyUser), middleware2.AuthSubject{UserID: 77})
c.Next()
})
handler := NewAccountHandler(svc, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
router.POST("/api/v1/admin/accounts/:id/duplicate", handler.Duplicate)
return router
}
func TestDuplicateAccountHandlerRedactsCredentials(t *testing.T) {
svc := &duplicateAccountAdminServiceStub{
account: &service.Account{
ID: 43,
Name: "primary (Copy)",
Platform: service.PlatformAnthropic,
Type: service.AccountTypeAPIKey,
Status: service.StatusActive,
Schedulable: false,
Credentials: map[string]any{"api_key": "top-secret-key"},
},
}
router := setupDuplicateAccountRouter(t, svc)
recorder := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/42/duplicate", nil)
router.ServeHTTP(recorder, request)
require.Equal(t, http.StatusOK, recorder.Code)
require.Equal(t, 1, svc.calls)
require.Contains(t, recorder.Body.String(), `"name":"primary (Copy)"`)
require.NotContains(t, recorder.Body.String(), "top-secret-key")
var responseBody struct {
Data struct {
Credentials map[string]any `json:"credentials"`
Schedulable bool `json:"schedulable"`
} `json:"data"`
}
require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &responseBody))
require.Empty(t, responseBody.Data.Credentials)
require.False(t, responseBody.Data.Schedulable)
}
func TestDuplicateAccountHandlerRejectsInvalidID(t *testing.T) {
svc := &duplicateAccountAdminServiceStub{}
router := setupDuplicateAccountRouter(t, svc)
recorder := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/not-a-number/duplicate", nil)
router.ServeHTTP(recorder, request)
require.Equal(t, http.StatusBadRequest, recorder.Code)
require.Zero(t, svc.calls)
}
func TestDuplicateAccountHandlerReplaysSameIdempotencyKey(t *testing.T) {
svc := &duplicateAccountAdminServiceStub{
account: &service.Account{
ID: 43,
Name: "primary (Copy)",
Platform: service.PlatformAnthropic,
Type: service.AccountTypeAPIKey,
Status: service.StatusActive,
Schedulable: false,
},
}
router := setupDuplicateAccountRouter(t, svc)
repo := newMemoryIdempotencyRepoStub()
service.SetDefaultIdempotencyCoordinator(service.NewIdempotencyCoordinator(repo, service.DefaultIdempotencyConfig()))
call := func() *httptest.ResponseRecorder {
recorder := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/42/duplicate", nil)
request.Header.Set("Idempotency-Key", "duplicate-account-42")
router.ServeHTTP(recorder, request)
return recorder
}
first := call()
second := call()
require.Equal(t, http.StatusOK, first.Code)
require.Equal(t, http.StatusOK, second.Code)
require.Equal(t, 1, svc.calls)
require.Equal(t, int64(42), svc.accountID)
require.Equal(t, "admin:77", svc.actorScope)
require.Equal(t, "duplicate-account-42", svc.operationKey)
require.Equal(t, "true", second.Header().Get("X-Idempotency-Replayed"))
}
func TestDuplicateAccountHandlerRecoversAfterMarkSucceededFailure(t *testing.T) {
svc := &duplicateAccountAdminServiceStub{
account: &service.Account{
ID: 43,
Name: "primary (Copy)",
Platform: service.PlatformAnthropic,
Type: service.AccountTypeAPIKey,
Status: service.StatusActive,
Schedulable: false,
},
}
router := setupDuplicateAccountRouter(t, svc)
repo := &failOnceMarkSucceededRepo{memoryIdempotencyRepoStub: newMemoryIdempotencyRepoStub(), failNext: true}
service.SetDefaultIdempotencyCoordinator(service.NewIdempotencyCoordinator(repo, service.DefaultIdempotencyConfig()))
call := func() *httptest.ResponseRecorder {
recorder := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/42/duplicate", nil)
request.Header.Set("Idempotency-Key", "duplicate-account-42-recovery")
router.ServeHTTP(recorder, request)
return recorder
}
first := call()
second := call()
require.Equal(t, http.StatusOK, first.Code)
require.Equal(t, http.StatusOK, second.Code)
require.Equal(t, "true", first.Header().Get("X-Idempotency-Recovered"))
require.Equal(t, "true", second.Header().Get("X-Idempotency-Recovered"))
require.Equal(t, 1, svc.calls, "ambiguous retries must not repeat the create side effect")
require.Equal(t, 2, svc.recoverCalls)
require.Equal(t, "admin:77", svc.recoverScope)
require.Equal(t, "duplicate-account-42-recovery", svc.recoverKey)
require.Contains(t, second.Body.String(), `"id":43`)
}
func TestDuplicateAccountHandlerPreservesIdempotencyErrorWhenRecoveryLookupFails(t *testing.T) {
svc := &duplicateAccountAdminServiceStub{
account: &service.Account{
ID: 43,
Name: "primary (Copy)",
Platform: service.PlatformAnthropic,
Type: service.AccountTypeAPIKey,
Status: service.StatusActive,
Schedulable: false,
},
recoverErr: errors.New("recovery database unavailable"),
}
router := setupDuplicateAccountRouter(t, svc)
repo := &failOnceMarkSucceededRepo{memoryIdempotencyRepoStub: newMemoryIdempotencyRepoStub(), failNext: true}
service.SetDefaultIdempotencyCoordinator(service.NewIdempotencyCoordinator(repo, service.DefaultIdempotencyConfig()))
recorder := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/42/duplicate", nil)
request.Header.Set("Idempotency-Key", "duplicate-account-42-recovery-error")
router.ServeHTTP(recorder, request)
require.Equal(t, http.StatusServiceUnavailable, recorder.Code)
require.Contains(t, recorder.Body.String(), "IDEMPOTENCY_STORE_UNAVAILABLE")
require.Equal(t, 1, svc.calls)
require.Equal(t, 1, svc.recoverCalls)
require.Equal(t, "admin:77", svc.recoverScope)
}
func TestDuplicateAccountHandlerDoesNotReexecuteWhileOriginalIsProcessing(t *testing.T) {
svc := &blockingDuplicateAdminServiceStub{
account: &service.Account{
ID: 43,
Name: "primary (Copy)",
Platform: service.PlatformAnthropic,
Type: service.AccountTypeAPIKey,
Status: service.StatusActive,
Schedulable: false,
},
started: make(chan struct{}),
release: make(chan struct{}),
recoverErr: errors.New("recovery database unavailable"),
}
router := setupDuplicateAccountRouter(t, svc)
service.SetDefaultIdempotencyCoordinator(service.NewIdempotencyCoordinator(newMemoryIdempotencyRepoStub(), service.DefaultIdempotencyConfig()))
call := func() *httptest.ResponseRecorder {
recorder := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/42/duplicate", nil)
request.Header.Set("Idempotency-Key", "duplicate-account-42-active")
router.ServeHTTP(recorder, request)
return recorder
}
firstDone := make(chan *httptest.ResponseRecorder, 1)
go func() { firstDone <- call() }()
<-svc.started
second := call()
require.Equal(t, http.StatusConflict, second.Code)
require.Contains(t, second.Body.String(), "IDEMPOTENCY_IN_PROGRESS")
require.Equal(t, int32(1), svc.calls.Load())
require.Equal(t, int32(1), svc.recoverCalls.Load())
close(svc.release)
select {
case first := <-firstDone:
require.Equal(t, http.StatusOK, first.Code)
case <-time.After(time.Second):
t.Fatal("original duplicate request did not finish")
}
}
@@ -418,6 +418,15 @@ func (s *stubAdminService) CreateAccount(ctx context.Context, input *service.Cre
return &account, nil
}
func (s *stubAdminService) DuplicateAccount(ctx context.Context, id int64, actorScope, operationKey string) (*service.Account, error) {
account := service.Account{ID: 301, Name: "account (Copy)", Status: service.StatusActive, Schedulable: false}
return &account, nil
}
func (s *stubAdminService) RecoverDuplicateAccount(ctx context.Context, id int64, actorScope, operationKey string) (*service.Account, error) {
return nil, nil
}
func (s *stubAdminService) UpdateAccount(ctx context.Context, id int64, input *service.UpdateAccountInput) (*service.Account, error) {
s.updateAccountCalls++
if s.updateAccountErr != nil {
@@ -73,7 +73,7 @@ func TestGrokSSOBatchImportKeepsCreatedAccountsWhenOneAutomaticProbeFails(t *tes
defer oauthService.Stop()
prober := newGrokImportProbeStub(3)
prober.failures[502] = infraerrors.New(502, "GROK_TEST_PROBE_FAILED", "sensitive-upstream-body")
handler := NewGrokOAuthHandler(oauthService, adminService, nil)
handler := NewGrokOAuthHandler(oauthService, adminService, nil, nil)
handler.importProber = prober
router := gin.New()
@@ -7,6 +7,7 @@ import (
"strconv"
"strings"
"sync"
"time"
"github.com/Wei-Shaw/sub2api/internal/handler/dto"
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
@@ -23,18 +24,21 @@ type GrokOAuthHandler struct {
adminService service.AdminService
quotaService *service.GrokQuotaService
importProber grokUsageProber
reconciler service.GrokOAuthReconciler
}
func NewGrokOAuthHandler(
grokOAuthService *service.GrokOAuthService,
adminService service.AdminService,
quotaService *service.GrokQuotaService,
reconciler service.GrokOAuthReconciler,
) *GrokOAuthHandler {
return &GrokOAuthHandler{
grokOAuthService: grokOAuthService,
adminService: adminService,
quotaService: quotaService,
importProber: quotaService,
reconciler: reconciler,
}
}
@@ -160,6 +164,50 @@ func (h *GrokOAuthHandler) RefreshAccountToken(c *gin.Context) {
response.Success(c, dto.AccountFromService(updatedAccount))
}
type GrokOAuthReconcileRequest struct {
DryRun *bool `json:"dry_run"`
Apply bool `json:"apply"`
AfterID int64 `json:"after_id"`
Limit int `json:"limit"`
RefreshWindowSeconds int64 `json:"refresh_window_seconds"`
}
func (h *GrokOAuthHandler) ReconcileOAuthAccounts(c *gin.Context) {
var req GrokOAuthReconcileRequest
if err := c.ShouldBindJSON(&req); err != nil {
response.BadRequest(c, "Invalid request")
return
}
dryRun := true
if req.DryRun != nil {
dryRun = *req.DryRun
}
if req.Apply == dryRun {
response.ErrorFrom(c, service.ErrGrokOAuthReconcileMode)
return
}
if req.RefreshWindowSeconds < 0 || req.RefreshWindowSeconds > int64((24*time.Hour)/time.Second) {
response.ErrorFrom(c, service.ErrGrokOAuthReconcileWindow)
return
}
if h.reconciler == nil {
response.InternalError(c, "Grok OAuth reconciliation service is unavailable")
return
}
result, err := h.reconciler.ReconcileGrokOAuth(c.Request.Context(), service.GrokOAuthReconcileInput{
DryRun: dryRun,
Apply: req.Apply,
AfterID: req.AfterID,
Limit: req.Limit,
RefreshWindow: time.Duration(req.RefreshWindowSeconds) * time.Second,
})
if err != nil {
response.ErrorFrom(c, err)
return
}
response.Success(c, result)
}
func (h *GrokOAuthHandler) CreateAccountFromOAuth(c *gin.Context) {
var req struct {
SessionID string `json:"session_id" binding:"required"`
@@ -47,6 +47,19 @@ type grokQuotaHandlerUpstream struct {
bodies [][]byte
}
type grokOAuthReconcilerStub struct {
input service.GrokOAuthReconcileInput
calls int
result *service.GrokOAuthReconcileResult
err error
}
func (s *grokOAuthReconcilerStub) ReconcileGrokOAuth(_ context.Context, input service.GrokOAuthReconcileInput) (*service.GrokOAuthReconcileResult, error) {
s.calls++
s.input = input
return s.result, s.err
}
func (u *grokQuotaHandlerUpstream) Do(req *http.Request, _ string, _ int64, _ int) (*http.Response, error) {
var body []byte
if req.Body != nil {
@@ -90,15 +103,18 @@ func TestGrokOAuthHandlerQueryQuotaProbesUpstream(t *testing.T) {
ID: 42,
Platform: service.PlatformGrok,
Type: service.AccountTypeOAuth,
Status: service.StatusActive,
Schedulable: true,
Concurrency: 1,
Credentials: map[string]any{
"access_token": "access-token",
"expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339),
"access_token": "access-token",
"refresh_token": "refresh-token",
"expires_at": time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339),
},
}}
upstream := &grokQuotaHandlerUpstream{}
quotaService := service.NewGrokQuotaService(repo, nil, service.NewGrokTokenProvider(repo, nil), upstream)
handler := NewGrokOAuthHandler(nil, nil, quotaService)
handler := NewGrokOAuthHandler(nil, nil, quotaService, nil)
router := gin.New()
router.GET("/api/v1/admin/grok/accounts/:id/quota", handler.QueryQuota)
@@ -136,7 +152,7 @@ func TestGrokOAuthHandlerResetQuotaReturnsUnsupported(t *testing.T) {
Type: service.AccountTypeOAuth,
}}
quotaService := service.NewGrokQuotaService(repo, nil, nil, nil)
handler := NewGrokOAuthHandler(nil, nil, quotaService)
handler := NewGrokOAuthHandler(nil, nil, quotaService, nil)
router := gin.New()
router.POST("/api/v1/admin/grok/accounts/:id/reset-quota", handler.ResetQuota)
@@ -154,7 +170,7 @@ func TestGrokOAuthHandlerRuntimeSanityDoesNotExposeSecrets(t *testing.T) {
t.Setenv(xai.EnvBaseURL, "http://127.0.0.1:8080/v1?access_token=secret")
t.Setenv(xai.EnvClientID, "client-secret-like-value")
handler := NewGrokOAuthHandler(nil, nil, nil)
handler := NewGrokOAuthHandler(nil, nil, nil, nil)
router := gin.New()
router.GET("/api/v1/admin/grok/runtime-sanity", handler.RuntimeSanity)
rec := httptest.NewRecorder()
@@ -216,3 +232,69 @@ func TestGrokSSOImportWorkerRecoversPanic(t *testing.T) {
require.Equal(t, 2, result.item.Index)
require.Contains(t, result.item.Error, "internal worker panic")
}
func TestGrokOAuthHandlerReconcileDefaultsToDryRun(t *testing.T) {
gin.SetMode(gin.TestMode)
reconciler := &grokOAuthReconcilerStub{result: &service.GrokOAuthReconcileResult{
DryRun: true,
Scanned: 2,
Actionable: 1,
WouldBlock: 1,
Items: []service.GrokOAuthReconcileItem{{AccountID: 42, Reason: service.GrokOAuthReconcileReasonMissingRefreshToken, Action: service.GrokOAuthReconcileActionBlock, Outcome: service.GrokOAuthReconcileOutcomePlanned}},
NextAfterID: 0,
}}
handler := NewGrokOAuthHandler(nil, nil, nil, reconciler)
router := gin.New()
router.POST("/api/v1/admin/grok/oauth/reconcile", handler.ReconcileOAuthAccounts)
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/v1/admin/grok/oauth/reconcile", strings.NewReader(`{}`))
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code)
require.Equal(t, 1, reconciler.calls)
require.True(t, reconciler.input.DryRun)
require.False(t, reconciler.input.Apply)
require.Contains(t, rec.Body.String(), `"reason":"missing_refresh_token"`)
require.NotContains(t, rec.Body.String(), `"refresh_token":`)
require.NotContains(t, rec.Body.String(), `"access_token":`)
}
func TestGrokOAuthHandlerReconcileRequiresExplicitApply(t *testing.T) {
gin.SetMode(gin.TestMode)
reconciler := &grokOAuthReconcilerStub{}
handler := NewGrokOAuthHandler(nil, nil, nil, reconciler)
router := gin.New()
router.POST("/api/v1/admin/grok/oauth/reconcile", handler.ReconcileOAuthAccounts)
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/v1/admin/grok/oauth/reconcile", strings.NewReader(`{"dry_run":false}`))
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(rec, req)
require.Equal(t, http.StatusBadRequest, rec.Code)
require.Zero(t, reconciler.calls)
require.NotContains(t, rec.Body.String(), "credentials")
}
func TestGrokOAuthHandlerReconcileExplicitApply(t *testing.T) {
gin.SetMode(gin.TestMode)
reconciler := &grokOAuthReconcilerStub{result: &service.GrokOAuthReconcileResult{DryRun: false, Refreshed: 1}}
handler := NewGrokOAuthHandler(nil, nil, nil, reconciler)
router := gin.New()
router.POST("/api/v1/admin/grok/oauth/reconcile", handler.ReconcileOAuthAccounts)
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/v1/admin/grok/oauth/reconcile", strings.NewReader(`{"apply":true,"dry_run":false,"after_id":10,"limit":25,"refresh_window_seconds":3600}`))
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code)
require.Equal(t, 1, reconciler.calls)
require.True(t, reconciler.input.Apply)
require.False(t, reconciler.input.DryRun)
require.Equal(t, int64(10), reconciler.input.AfterID)
require.Equal(t, 25, reconciler.input.Limit)
require.Equal(t, time.Hour, reconciler.input.RefreshWindow)
}
@@ -37,14 +37,9 @@ func executeAdminIdempotent(
return &service.IdempotencyExecuteResult{Data: data}, nil
}
actorScope := "admin:0"
if subject, ok := middleware2.GetAuthSubjectFromContext(c); ok {
actorScope = "admin:" + strconv.FormatInt(subject.UserID, 10)
}
return coordinator.Execute(c.Request.Context(), service.IdempotencyExecuteOptions{
Scope: scope,
ActorScope: actorScope,
ActorScope: adminActorScope(c),
Method: c.Request.Method,
Route: c.FullPath(),
IdempotencyKey: c.GetHeader("Idempotency-Key"),
@@ -54,6 +49,14 @@ func executeAdminIdempotent(
}, execute)
}
func adminActorScope(c *gin.Context) string {
actorScope := "admin:0"
if subject, ok := middleware2.GetAuthSubjectFromContext(c); ok {
actorScope = "admin:" + strconv.FormatInt(subject.UserID, 10)
}
return actorScope
}
func executeAdminIdempotentJSON(
c *gin.Context,
scope string,
@@ -386,8 +386,8 @@ func (h *OpsHandler) ListRequestErrorUpstreamErrors(c *gin.Context) {
filter.EndTime = &endTime
}
filter.View = "all"
filter.Phase = "upstream"
// 上游错误列表需含 status<400 的 recovered 行,显式豁免客户端可见守卫。
filter.ErrorPhasesAny = []string{"upstream", "account_auth"}
// Provider-health list includes recovered inference and credential rows.
filter.IncludeRecoveredUpstream = true
filter.Owner = "provider"
filter.Source = strings.TrimSpace(c.Query("error_source"))
@@ -470,8 +470,8 @@ func (h *OpsHandler) ListUpstreamErrors(c *gin.Context) {
}
filter.View = parseOpsViewParam(c)
filter.Phase = "upstream"
// 上游错误列表需含 status<400 的 recovered 行,显式豁免客户端可见守卫。
filter.ErrorPhasesAny = []string{"upstream", "account_auth"}
// Provider-health list includes recovered inference and credential rows.
filter.IncludeRecoveredUpstream = true
filter.Owner = "provider"
filter.Source = strings.TrimSpace(c.Query("error_source"))
@@ -20,6 +20,7 @@ func TestRedactCredentials_StripsSensitiveKeysAndReportsStatus(t *testing.T) {
"aws_secret_access_key": "aws-secret",
"service_account_json": map[string]any{"private_key": "..."},
"private_key": "raw-key",
"agent_private_key": "agent-key-secret",
// 非敏感
"base_url": "https://api.example.com",
"model_mapping": map[string]any{"foo": "bar"},
@@ -35,6 +36,7 @@ func TestRedactCredentials_StripsSensitiveKeysAndReportsStatus(t *testing.T) {
require.NotContains(t, out, "aws_secret_access_key")
require.NotContains(t, out, "service_account_json")
require.NotContains(t, out, "private_key")
require.NotContains(t, out, "agent_private_key")
require.Equal(t, "https://api.example.com", out["base_url"])
require.Equal(t, map[string]any{"foo": "bar"}, out["model_mapping"])
@@ -47,6 +49,7 @@ func TestRedactCredentials_StripsSensitiveKeysAndReportsStatus(t *testing.T) {
require.True(t, status["has_aws_secret_access_key"])
require.True(t, status["has_service_account_json"])
require.True(t, status["has_private_key"])
require.True(t, status["has_agent_private_key"])
// 状态 map 不应携带非敏感键的 has_*
require.NotContains(t, status, "has_base_url")
@@ -84,6 +87,7 @@ func TestRedactCredentials_AllKnownSensitiveKeys(t *testing.T) {
"api_key", "session_key", "cookie",
"aws_secret_access_key", "aws_session_token",
"service_account_json", "service_account", "private_key",
"agent_private_key",
}
in := make(map[string]any, len(keys))
for _, k := range keys {
+38
View File
@@ -5,6 +5,8 @@ import (
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/Wei-Shaw/sub2api/internal/pkg/logger"
"github.com/Wei-Shaw/sub2api/internal/service"
"go.uber.org/zap"
@@ -71,7 +73,15 @@ func (s *FailoverState) HandleFailoverError(
retryLimit int,
failoverErr *service.UpstreamFailoverError,
) FailoverAction {
// 客户端已断开:failover 只会用已取消的 context 重新选号并必然失败,
// 不应再被当成账号耗尽处理(误报 502)。
if ctx != nil && ctx.Err() != nil {
return FailoverCanceled
}
s.LastFailoverErr = failoverErr
if failoverErr == nil || !failoverErr.ShouldRetryNextAccount() {
return FailoverExhausted
}
// 缓存计费判断
if needForceCacheBilling(s.hasBoundSession, failoverErr) {
@@ -135,6 +145,12 @@ func (s *FailoverState) HandleFailoverError(
// 返回 FailoverExhausted 时,调用方应返回错误响应。
// 返回 FailoverCanceled 时,调用方应直接 return。
func (s *FailoverState) HandleSelectionExhausted(ctx context.Context) FailoverAction {
// 客户端已断开时选号失败是 context canceled 的必然结果,
// 不代表账号耗尽,直接按取消终止。
if ctx.Err() != nil {
return FailoverCanceled
}
if s.LastFailoverErr != nil &&
s.LastFailoverErr.StatusCode == http.StatusServiceUnavailable &&
s.SwitchCount <= s.MaxSwitches {
@@ -163,6 +179,28 @@ func needForceCacheBilling(hasBoundSession bool, failoverErr *service.UpstreamFa
return hasBoundSession || (failoverErr != nil && failoverErr.ForceCacheBilling)
}
// failoverClientGone 判断下游客户端是否已断开(请求 context 已取消)。
// 客户端断开后 failover 必须静默终止:用已取消的 context 重新选号只会得到
// context.Canceled,并被误报成账号耗尽(通用 502);上游 detach 的在途请求
// 照常完成计费,但不再为无人接收的响应启动新的上游尝试。
// 响应尚未提交时把状态码标记为 499(client closed request),供访问日志归类。
func failoverClientGone(c *gin.Context) bool {
if c == nil || c.Request == nil || c.Request.Context().Err() == nil {
return false
}
// 先停 compact 心跳(接管 ResponseWriter,建立 happens-before),与
// handleStreamingAwareError/errorResponse 等终结路径对齐,避免心跳
// goroutine 与下面的状态标记并发触碰同一 writer。心跳已提交 200 时
// 状态码已固化,不再标 499。
if service.StopOpenAICompactSSEKeepaliveCommitted(c) {
return true
}
if !c.Writer.Written() {
c.Status(statusClientClosedRequest)
}
return true
}
// sleepWithContext 等待指定时长,返回 false 表示 context 已取消。
func sleepWithContext(ctx context.Context, d time.Duration) bool {
if d <= 0 {
+142 -3
View File
@@ -2,11 +2,14 @@ package handler
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
@@ -128,6 +131,50 @@ func TestSleepWithContext(t *testing.T) {
// ---------------------------------------------------------------------------
func TestHandleFailoverError_BasicSwitch(t *testing.T) {
t.Run("显式停止不切换账号且旧错误默认仍切换", func(t *testing.T) {
mock := &mockTempUnscheduler{}
fs := NewFailoverState(3, false)
stopErr := &service.UpstreamFailoverError{
Stage: service.GatewayFailureStageAccountAuth,
Scope: service.GatewayFailureScopeProvider,
NextAccountAction: service.NextAccountStop,
}
action := fs.HandleFailoverError(context.Background(), mock, 100, service.PlatformGrok, maxSameAccountRetries, stopErr)
require.Equal(t, FailoverExhausted, action)
require.Zero(t, fs.SwitchCount)
require.Empty(t, fs.FailedAccountIDs)
require.Equal(t, stopErr, fs.LastFailoverErr)
legacyErr := newTestFailoverErr(http.StatusTooManyRequests, false, false)
action = fs.HandleFailoverError(context.Background(), mock, 100, service.PlatformGrok, maxSameAccountRetries, legacyErr)
require.Equal(t, FailoverContinue, action)
require.Equal(t, 1, fs.SwitchCount)
require.Contains(t, fs.FailedAccountIDs, int64(100))
})
t.Run("已取消的认证失败不改变切换状态", func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
mock := &mockTempUnscheduler{}
fs := NewFailoverState(3, false)
err := &service.UpstreamFailoverError{
Stage: service.GatewayFailureStageAccountAuth,
Scope: service.GatewayFailureScopeAccount,
NextAccountAction: service.NextAccountRetry,
}
action := fs.HandleFailoverError(ctx, mock, 101, service.PlatformGrok, maxSameAccountRetries, err)
require.Equal(t, FailoverCanceled, action)
require.Zero(t, fs.SwitchCount)
require.Empty(t, fs.FailedAccountIDs)
require.Nil(t, fs.LastFailoverErr)
require.Empty(t, mock.calls)
})
t.Run("非重试错误_非Antigravity_直接切换", func(t *testing.T) {
mock := &mockTempUnscheduler{}
fs := NewFailoverState(3, false)
@@ -444,7 +491,28 @@ func TestHandleFailoverError_ContextCanceled(t *testing.T) {
err := newTestFailoverErr(400, true, false)
ctx, cancel := context.WithCancel(context.Background())
cancel() // 立即取消
go func() {
time.Sleep(30 * time.Millisecond)
cancel() // 通过入口检查后、sleep 期间取消
}()
start := time.Now()
action := fs.HandleFailoverError(ctx, mock, 100, "openai", maxSameAccountRetries, err)
elapsed := time.Since(start)
require.Equal(t, FailoverCanceled, action)
require.Less(t, elapsed, 400*time.Millisecond, "sleep 应被取消打断")
// 进入重试分支后才取消:重试计数已递增
require.Equal(t, 1, fs.SameAccountRetryCount[100])
})
t.Run("入口即已取消_不改动任何failover状态", func(t *testing.T) {
mock := &mockTempUnscheduler{}
fs := NewFailoverState(3, false)
err := newTestFailoverErr(520, false, false)
ctx, cancel := context.WithCancel(context.Background())
cancel() // 调用前客户端已断开
start := time.Now()
action := fs.HandleFailoverError(ctx, mock, 100, "openai", maxSameAccountRetries, err)
@@ -452,8 +520,12 @@ func TestHandleFailoverError_ContextCanceled(t *testing.T) {
require.Equal(t, FailoverCanceled, action)
require.Less(t, elapsed, 100*time.Millisecond, "应立即返回")
// 重试计数仍应递增
require.Equal(t, 1, fs.SameAccountRetryCount[100])
// 入口已取消时不得改变任何 failover 状态。
require.Equal(t, 0, fs.SwitchCount, "取消的请求不应计入切换")
require.Equal(t, 0, fs.SameAccountRetryCount[100], "取消的请求不应改动重试计数")
require.NotContains(t, fs.FailedAccountIDs, int64(100))
require.Nil(t, fs.LastFailoverErr)
require.Empty(t, mock.calls, "不应触发 TempUnschedule")
})
t.Run("Antigravity延迟期间context取消", func(t *testing.T) {
@@ -755,6 +827,29 @@ func TestHandleSelectionExhausted(t *testing.T) {
require.Less(t, elapsed, 100*time.Millisecond, "应立即返回")
})
t.Run("context已取消_非503也返回Canceled而非Exhausted", func(t *testing.T) {
// #4257 核心场景:客户端断开后选号失败源于 context canceled,
// 不应被当成账号耗尽转成 502。
fs := NewFailoverState(3, false)
fs.LastFailoverErr = newTestFailoverErr(520, false, false)
ctx, cancel := context.WithCancel(context.Background())
cancel()
action := fs.HandleSelectionExhausted(ctx)
require.Equal(t, FailoverCanceled, action)
})
t.Run("context已取消_无LastFailoverErr也返回Canceled", func(t *testing.T) {
fs := NewFailoverState(3, false)
ctx, cancel := context.WithCancel(context.Background())
cancel()
action := fs.HandleSelectionExhausted(ctx)
require.Equal(t, FailoverCanceled, action)
})
t.Run("503且SwitchCount等于MaxSwitches_仍可重试", func(t *testing.T) {
fs := NewFailoverState(2, false)
fs.LastFailoverErr = newTestFailoverErr(503, false, false)
@@ -764,3 +859,47 @@ func TestHandleSelectionExhausted(t *testing.T) {
require.Equal(t, FailoverContinue, action)
})
}
// ---------------------------------------------------------------------------
// failoverClientGone 测试
// ---------------------------------------------------------------------------
func TestFailoverClientGone(t *testing.T) {
gin.SetMode(gin.TestMode)
t.Run("活跃请求返回false", func(t *testing.T) {
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil)
require.False(t, failoverClientGone(c))
require.Equal(t, http.StatusOK, c.Writer.Status(), "不应改动状态码")
})
t.Run("客户端已断开_返回true并标记499", func(t *testing.T) {
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
ctx, cancel := context.WithCancel(context.Background())
cancel()
c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil).WithContext(ctx)
require.True(t, failoverClientGone(c))
require.Equal(t, statusClientClosedRequest, c.Writer.Status())
})
t.Run("响应已提交_不改状态码", func(t *testing.T) {
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
ctx, cancel := context.WithCancel(context.Background())
cancel()
c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil).WithContext(ctx)
c.String(http.StatusOK, "partial")
require.True(t, failoverClientGone(c))
require.Equal(t, http.StatusOK, c.Writer.Status(), "已提交的状态码不应被覆盖")
})
t.Run("nil安全", func(t *testing.T) {
require.False(t, failoverClientGone(nil))
})
}
@@ -327,6 +327,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
c.Request = c.Request.WithContext(ctx)
continue
case FailoverCanceled:
failoverClientGone(c)
return
default: // FailoverExhausted
if fs.LastFailoverErr != nil {
@@ -456,6 +457,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
h.handleFailoverExhausted(c, fs.LastFailoverErr, service.PlatformGemini, streamStarted)
return
case FailoverCanceled:
failoverClientGone(c)
return
}
}
@@ -613,6 +615,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
c.Request = c.Request.WithContext(ctx)
continue
case FailoverCanceled:
failoverClientGone(c)
return
default: // FailoverExhausted
if fs.LastFailoverErr != nil {
@@ -876,6 +879,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
h.handleFailoverExhausted(c, fs.LastFailoverErr, account.Platform, streamStarted)
return
case FailoverCanceled:
failoverClientGone(c)
return
}
}
@@ -0,0 +1,98 @@
//go:build unit
package handler
import (
"bytes"
"context"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
"github.com/Wei-Shaw/sub2api/internal/config"
"github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
middleware "github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
type countingGatewaySchedulerCache struct {
*fakeSchedulerCache
snapshotCalls atomic.Int64
}
func (c *countingGatewaySchedulerCache) GetSnapshot(ctx context.Context, bucket service.SchedulerBucket) ([]*service.Account, bool, error) {
c.snapshotCalls.Add(1)
return c.fakeSchedulerCache.GetSnapshot(ctx, bucket)
}
func TestGatewayHandlerPreCancelledCompatibleRequestsDoNotSelectAccount(t *testing.T) {
gin.SetMode(gin.TestMode)
groupID := int64(9100)
group := &service.Group{ID: groupID, Hydrated: true, Platform: service.PlatformAnthropic, Status: service.StatusActive}
account := &service.Account{
ID: 9101, Platform: service.PlatformAnthropic, Type: service.AccountTypeAPIKey,
Status: service.StatusActive, Schedulable: true, Concurrency: 1,
AccountGroups: []service.AccountGroup{{AccountID: 9101, GroupID: groupID}},
}
schedulerCache := &countingGatewaySchedulerCache{fakeSchedulerCache: &fakeSchedulerCache{accounts: []*service.Account{account}}}
schedulerSnapshot := service.NewSchedulerSnapshotService(schedulerCache, nil, nil, nil, nil)
gatewayService := service.NewGatewayService(
nil, &fakeGroupRepo{group: group}, nil, nil, nil, nil, nil, nil, nil,
schedulerSnapshot, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
)
cfg := &config.Config{RunMode: config.RunModeSimple}
billingCacheService := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
t.Cleanup(billingCacheService.Stop)
h := &GatewayHandler{
gatewayService: gatewayService,
billingCacheService: billingCacheService,
concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(&fakeConcurrencyCache{}), SSEPingFormatClaude, 0),
maxAccountSwitches: 1,
cfg: cfg,
}
apiKey := &service.APIKey{
ID: 9102, UserID: 9103, GroupID: &groupID, Group: group, Status: service.StatusActive,
User: &service.User{ID: 9103, Concurrency: 10, Balance: 100},
}
tests := []struct {
name string
path string
body string
call func(*gin.Context)
}{
{
name: "responses", path: "/v1/responses", body: `{"model":"claude-test","input":"hello","stream":false}`,
call: h.Responses,
},
{
name: "chat completions", path: "/v1/chat/completions", body: `{"model":"claude-test","messages":[{"role":"user","content":"hello"}],"stream":false}`,
call: h.ChatCompletions,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
schedulerCache.snapshotCalls.Store(0)
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
ctx, cancel := context.WithCancel(context.Background())
cancel()
ctx = context.WithValue(ctx, ctxkey.Group, group)
req := httptest.NewRequest(http.MethodPost, tt.path, bytes.NewBufferString(tt.body)).WithContext(ctx)
req.Header.Set("Content-Type", "application/json")
c.Request = req
c.Set(string(middleware.ContextKeyAPIKey), apiKey)
c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: apiKey.UserID, Concurrency: 10})
tt.call(c)
require.Zero(t, schedulerCache.snapshotCalls.Load(), "a cancelled request must stop before the account selector")
_, selected := c.Get(opsAccountIDKey)
require.False(t, selected)
})
}
}
@@ -159,6 +159,9 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
}
for {
if c.Request.Context().Err() != nil {
return
}
selection, err := h.gatewayService.SelectAccountWithLoadAwareness(c.Request.Context(), apiKey.GroupID, selectionSessionHash, reqModel, fs.FailedAccountIDs, "", int64(0))
if err != nil {
if len(fs.FailedAccountIDs) == 0 {
@@ -178,6 +181,7 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
case FailoverContinue:
continue
case FailoverCanceled:
failoverClientGone(c)
return
default:
if fs.LastFailoverErr != nil {
@@ -262,6 +266,7 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
h.handleCCFailoverExhausted(c, fs.LastFailoverErr, streamStarted)
return
case FailoverCanceled:
failoverClientGone(c)
return
}
}
@@ -328,6 +333,14 @@ func (h *GatewayHandler) handleCCFailoverExhausted(c *gin.Context, lastErr *serv
if streamStarted {
return
}
if lastErr != nil {
copyFailoverRetryAfter(c, lastErr.ResponseHeaders)
}
if lastErr != nil && lastErr.IsCredentialFailure() {
status, message := credentialFailoverClientResponse(lastErr)
h.chatCompletionsErrorResponse(c, status, "server_error", message)
return
}
statusCode := http.StatusBadGateway
if lastErr != nil && lastErr.StatusCode > 0 {
statusCode = lastErr.StatusCode
@@ -157,6 +157,9 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
fs := NewFailoverState(h.maxAccountSwitches, false)
for {
if requestCtx.Err() != nil {
return
}
selection, err := h.gatewayService.SelectAccountWithLoadAwareness(requestCtx, apiKey.GroupID, sessionHash, reqModel, fs.FailedAccountIDs, "", int64(0))
if err != nil {
if len(fs.FailedAccountIDs) == 0 {
@@ -176,6 +179,7 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
case FailoverContinue:
continue
case FailoverCanceled:
failoverClientGone(c)
return
default:
if fs.LastFailoverErr != nil {
@@ -241,6 +245,7 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
h.handleResponsesFailoverExhausted(c, fs.LastFailoverErr, streamStarted)
return
case FailoverCanceled:
failoverClientGone(c)
return
}
}
@@ -307,6 +312,14 @@ func (h *GatewayHandler) handleResponsesFailoverExhausted(c *gin.Context, lastEr
if streamStarted {
return // Can't write error after stream started
}
if lastErr != nil {
copyFailoverRetryAfter(c, lastErr.ResponseHeaders)
}
if lastErr != nil && lastErr.IsCredentialFailure() {
status, message := credentialFailoverClientResponse(lastErr)
h.responsesErrorResponse(c, status, "server_error", message)
return
}
statusCode := http.StatusBadGateway
if lastErr != nil && lastErr.StatusCode > 0 {
statusCode = lastErr.StatusCode
@@ -31,7 +31,22 @@ type fakeSchedulerCache struct {
func (f *fakeSchedulerCache) GetSnapshot(_ context.Context, _ service.SchedulerBucket) ([]*service.Account, bool, error) {
return f.accounts, true, nil
}
func (f *fakeSchedulerCache) SetSnapshot(_ context.Context, _ service.SchedulerBucket, _ []service.Account) error {
func (f *fakeSchedulerCache) CaptureBucketWriteToken(_ context.Context, bucket service.SchedulerBucket) (service.SchedulerBucketWriteToken, error) {
return service.SchedulerBucketWriteToken{Bucket: bucket, Epoch: 1}, nil
}
func (f *fakeSchedulerCache) SetSnapshot(_ context.Context, _ service.SchedulerBucket, _ service.SchedulerBucketWriteToken, _ []service.Account) error {
return nil
}
func (f *fakeSchedulerCache) RetireBucket(_ context.Context, _ service.SchedulerBucket) error {
return nil
}
func (f *fakeSchedulerCache) ReopenBucket(_ context.Context, bucket service.SchedulerBucket) (service.SchedulerBucketWriteToken, error) {
return service.SchedulerBucketWriteToken{Bucket: bucket, Epoch: 1}, nil
}
func (f *fakeSchedulerCache) TryAcquireGroupLifecycleLease(_ context.Context, _ int64, _ time.Duration) (service.SchedulerGroupLifecycleLease, bool, error) {
return service.SchedulerGroupLifecycleLease{}, false, nil
}
func (f *fakeSchedulerCache) ReleaseGroupLifecycleLease(_ context.Context, _ service.SchedulerGroupLifecycleLease) error {
return nil
}
func (f *fakeSchedulerCache) GetAccount(_ context.Context, id int64) (*service.Account, error) {
+7 -12
View File
@@ -163,20 +163,15 @@ func wrapReleaseOnDone(ctx context.Context, releaseFunc func()) func() {
return nil
}
var once sync.Once
var stop func() bool
release := func() {
once.Do(func() {
if stop != nil {
_ = stop()
}
releaseFunc()
})
releaseOnce := func() {
once.Do(releaseFunc)
}
stop := context.AfterFunc(ctx, releaseOnce)
stop = context.AfterFunc(ctx, release)
return release
return func() {
_ = stop()
releaseOnce()
}
}
// IncrementWaitCount increments the wait count for a user
@@ -6,6 +6,8 @@ import (
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/require"
)
// TestWrapReleaseOnDone_NoGoroutineLeak 验证 wrapReleaseOnDone 修复后不会泄露 goroutine
@@ -67,6 +69,21 @@ func TestWrapReleaseOnDone_ContextCancellation(t *testing.T) {
}
}
func TestWrapReleaseOnDone_AlreadyCancelledReleasesExactlyOnce(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
var releaseCount int32
release := wrapReleaseOnDone(ctx, func() {
atomic.AddInt32(&releaseCount, 1)
})
release()
require.Eventually(t, func() bool {
return atomic.LoadInt32(&releaseCount) == 1
}, time.Second, time.Millisecond)
}
// TestWrapReleaseOnDone_MultipleCallsOnlyReleaseOnce 验证多次调用 release 只释放一次
func TestWrapReleaseOnDone_MultipleCallsOnlyReleaseOnce(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
@@ -368,6 +368,7 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) {
c.Request = c.Request.WithContext(ctx)
continue
case FailoverCanceled:
failoverClientGone(c)
return
default: // FailoverExhausted
h.handleGeminiFailoverExhausted(c, fs.LastFailoverErr)
@@ -490,6 +491,7 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) {
h.handleGeminiFailoverExhausted(c, fs.LastFailoverErr)
return
case FailoverCanceled:
failoverClientGone(c)
return
}
}
+26 -1
View File
@@ -166,6 +166,7 @@ func (h *OpenAIGatewayHandler) handleGrokMedia(c *gin.Context, endpoint service.
failedAccountIDs := make(map[int64]struct{})
sameAccountRetryCount := make(map[int64]int)
var lastFailoverErr *service.UpstreamFailoverError
var oauth429FailoverState service.OpenAIOAuth429FailoverState
switchCount := 0
maxAccountSwitches := h.maxAccountSwitches
if maxAccountSwitches <= 0 {
@@ -174,6 +175,9 @@ func (h *OpenAIGatewayHandler) handleGrokMedia(c *gin.Context, endpoint service.
routingStart := time.Now()
for {
if failoverClientGone(c) {
return
}
selection, scheduleDecision, err := h.gatewayService.SelectAccountWithSchedulerForCapability(
requestCtx,
apiKey.GroupID,
@@ -188,6 +192,10 @@ func (h *OpenAIGatewayHandler) handleGrokMedia(c *gin.Context, endpoint service.
service.PlatformGrok,
)
if err != nil {
if failoverClientGone(c) {
reqLog.Info("grok_media.account_select_aborted_client_disconnected", zap.Error(err))
return
}
reqLog.Warn("grok_media.account_select_failed",
zap.Error(err),
zap.Int("excluded_account_count", len(failedAccountIDs)),
@@ -257,11 +265,24 @@ func (h *OpenAIGatewayHandler) handleGrokMedia(c *gin.Context, endpoint service.
if err != nil {
var failoverErr *service.UpstreamFailoverError
if errors.As(err, &failoverErr) {
h.gatewayService.ReportOpenAIAccountScheduleResult(account.ID, false, nil)
if failoverClientGone(c) {
reqLog.Info("grok_media.failover_aborted_client_disconnected",
zap.Int64("account_id", account.ID),
zap.Int("upstream_status", failoverErr.StatusCode),
)
return
}
if failoverErr.ShouldReportAccountScheduleFailure() {
h.gatewayService.ReportOpenAIAccountScheduleResult(account.ID, false, nil)
}
if c.Writer.Size() != writerSizeBeforeForward {
h.handleFailoverExhausted(c, failoverErr, true)
return
}
if !failoverErr.ShouldRetryNextAccount() {
h.handleFailoverExhausted(c, failoverErr, false)
return
}
if failoverErr.RetryableOnSameAccount {
retryLimit := account.GetPoolModeRetryCount()
if sameAccountRetryCount[account.ID] < retryLimit {
@@ -288,6 +309,10 @@ func (h *OpenAIGatewayHandler) handleGrokMedia(c *gin.Context, endpoint service.
return
}
switchCount++
if h.gatewayService.ShouldStopOpenAIOAuth429Failover(account, failoverErr.StatusCode, switchCount, &oauth429FailoverState) {
h.handleFailoverExhausted(c, failoverErr, false)
return
}
reqLog.Warn("grok_media.upstream_failover_switching",
zap.Int64("account_id", account.ID),
zap.Int("upstream_status", failoverErr.StatusCode),
@@ -106,6 +106,7 @@ func (h *OpenAIGatewayHandler) AlphaSearch(c *gin.Context) {
failedAccountIDs := make(map[int64]struct{})
var lastFailoverErr *service.UpstreamFailoverError
switchCount := 0
var oauth429FailoverState service.OpenAIOAuth429FailoverState
routingStart := time.Now()
for {
@@ -123,6 +124,10 @@ func (h *OpenAIGatewayHandler) AlphaSearch(c *gin.Context) {
service.PlatformOpenAI,
)
if err != nil || selection == nil || selection.Account == nil {
if failoverClientGone(c) {
reqLog.Info("openai_alpha_search.account_select_aborted_client_disconnected", zap.Error(err))
return
}
if len(failedAccountIDs) == 0 {
cls := classifyNoAccountErrorFromGin(c, h.gatewayService, apiKey, requestedModel, requestedModel, service.PlatformOpenAI)
if !cls.ModelNotFound {
@@ -180,6 +185,13 @@ func (h *OpenAIGatewayHandler) AlphaSearch(c *gin.Context) {
h.handleFailoverExhausted(c, failoverErr, true)
return
}
if failoverClientGone(c) {
reqLog.Info("openai_alpha_search.failover_aborted_client_disconnected",
zap.Int64("account_id", account.ID),
zap.Int("upstream_status", failoverErr.StatusCode),
)
return
}
h.gatewayService.RecordOpenAIAccountSwitch()
failedAccountIDs[account.ID] = struct{}{}
lastFailoverErr = failoverErr
@@ -188,7 +200,7 @@ func (h *OpenAIGatewayHandler) AlphaSearch(c *gin.Context) {
return
}
switchCount++
if h.gatewayService.ShouldStopOpenAIOAuth429Failover(account, failoverErr.StatusCode, switchCount) {
if h.gatewayService.ShouldStopOpenAIOAuth429Failover(account, failoverErr.StatusCode, switchCount, &oauth429FailoverState) {
h.handleFailoverExhausted(c, failoverErr, false)
return
}
@@ -133,8 +133,12 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) {
failedAccountIDs := make(map[int64]struct{})
sameAccountRetryCount := make(map[int64]int)
var lastFailoverErr *service.UpstreamFailoverError
var oauth429FailoverState service.OpenAIOAuth429FailoverState
for {
if failoverClientGone(c) {
return
}
reqLog.Debug("openai_chat_completions.account_selecting", zap.Int("excluded_account_count", len(failedAccountIDs)))
selection, scheduleDecision, err := h.gatewayService.SelectAccountWithSchedulerForCapability(
c.Request.Context(),
@@ -150,6 +154,10 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) {
requestPlatform,
)
if err != nil {
if failoverClientGone(c) {
reqLog.Info("openai_chat_completions.account_select_aborted_client_disconnected", zap.Error(err))
return
}
reqLog.Warn("openai_chat_completions.account_select_failed",
zap.Error(openAICompatibleSelectionErrorForLog(err, requestPlatform)),
zap.Int("excluded_account_count", len(failedAccountIDs)),
@@ -231,11 +239,24 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) {
} else {
var failoverErr *service.UpstreamFailoverError
if errors.As(err, &failoverErr) {
if failoverClientGone(c) {
reqLog.Info("openai_chat_completions.failover_aborted_client_disconnected",
zap.Int64("account_id", account.ID),
zap.Int("upstream_status", failoverErr.StatusCode),
)
return
}
if c.Writer.Size() != writerSizeBeforeForward {
h.handleFailoverExhausted(c, failoverErr, true)
return
}
h.gatewayService.ReportOpenAIAccountScheduleResult(account.ID, false, nil)
if failoverErr.ShouldReportAccountScheduleFailure() {
h.gatewayService.ReportOpenAIAccountScheduleResult(account.ID, false, nil)
}
if !failoverErr.ShouldRetryNextAccount() {
h.handleFailoverExhausted(c, failoverErr, streamStarted)
return
}
// Pool mode: retry on the same account
if failoverErr.RetryableOnSameAccount {
retryLimit := account.GetPoolModeRetryCount()
@@ -263,7 +284,7 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) {
return
}
switchCount++
if h.gatewayService.ShouldStopOpenAIOAuth429Failover(account, failoverErr.StatusCode, switchCount) {
if h.gatewayService.ShouldStopOpenAIOAuth429Failover(account, failoverErr.StatusCode, switchCount, &oauth429FailoverState) {
h.handleFailoverExhausted(c, failoverErr, streamStarted)
return
}
@@ -121,6 +121,10 @@ func (h *OpenAIGatewayHandler) Embeddings(c *gin.Context) {
false,
)
if err != nil {
if failoverClientGone(c) {
reqLog.Info("openai_embeddings.account_select_aborted_client_disconnected", zap.Error(err))
return
}
reqLog.Warn("openai_embeddings.account_select_failed",
zap.Error(err),
zap.Int("excluded_account_count", len(failedAccountIDs)),
@@ -189,6 +193,13 @@ func (h *OpenAIGatewayHandler) Embeddings(c *gin.Context) {
return
}
h.gatewayService.ReportOpenAIAccountScheduleResult(account.ID, false, nil)
if failoverClientGone(c) {
reqLog.Info("openai_embeddings.failover_aborted_client_disconnected",
zap.Int64("account_id", account.ID),
zap.Int("upstream_status", failoverErr.StatusCode),
)
return
}
h.gatewayService.RecordOpenAIAccountSwitch()
failedAccountIDs[account.ID] = struct{}{}
lastFailoverErr = failoverErr
@@ -66,6 +66,20 @@ func (s *handlerInMemoryLogSink) ContainsFieldValue(field, substr string) bool {
return false
}
func (s *handlerInMemoryLogSink) FieldValueForMessage(message, field string) (any, bool) {
s.mu.Lock()
defer s.mu.Unlock()
for _, event := range s.events {
if event == nil || event.Message != message || event.Fields == nil {
continue
}
if value, ok := event.Fields[field]; ok {
return value, true
}
}
return nil, false
}
func captureHandlerStructuredLog(t *testing.T) (*handlerInMemoryLogSink, func()) {
t.Helper()
handlerStructuredLogCaptureMu.Lock()
@@ -0,0 +1,926 @@
//go:build unit
package handler
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/Wei-Shaw/sub2api/internal/config"
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
"github.com/Wei-Shaw/sub2api/internal/pkg/xai"
"github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/Wei-Shaw/sub2api/internal/service"
coderws "github.com/coder/websocket"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
type grokCredentialHandlerRepo struct {
service.AccountRepository
mu sync.Mutex
accounts []service.Account
setErrorIDs []int64
setTempIDs []int64
rateLimitIDs []int64
updateExtraIDs []int64
selectionCalls int
setErrorErr error
setTempErr error
missingOnGet map[int64]bool
}
func (r *grokCredentialHandlerRepo) ListSchedulableByPlatform(_ context.Context, platform string) ([]service.Account, error) {
r.mu.Lock()
defer r.mu.Unlock()
r.selectionCalls++
out := make([]service.Account, 0, len(r.accounts))
for _, account := range r.accounts {
if account.Platform == platform && account.IsSchedulable() {
out = append(out, account)
}
}
return out, nil
}
func (r *grokCredentialHandlerRepo) ListSchedulableByGroupIDAndPlatform(ctx context.Context, _ int64, platform string) ([]service.Account, error) {
return r.ListSchedulableByPlatform(ctx, platform)
}
func (r *grokCredentialHandlerRepo) ListSchedulableUngroupedByPlatform(ctx context.Context, platform string) ([]service.Account, error) {
return r.ListSchedulableByPlatform(ctx, platform)
}
func (r *grokCredentialHandlerRepo) GetByID(_ context.Context, id int64) (*service.Account, error) {
r.mu.Lock()
defer r.mu.Unlock()
if r.missingOnGet[id] {
return nil, nil
}
for _, account := range r.accounts {
if account.ID == id {
copy := account
copy.Credentials = cloneCredentialMap(account.Credentials)
return &copy, nil
}
}
return nil, nil
}
func (r *grokCredentialHandlerRepo) SetError(_ context.Context, id int64, message string) error {
r.mu.Lock()
defer r.mu.Unlock()
r.setErrorIDs = append(r.setErrorIDs, id)
if r.setErrorErr != nil {
return r.setErrorErr
}
for i := range r.accounts {
if r.accounts[i].ID == id {
r.accounts[i].Status = service.StatusError
r.accounts[i].Schedulable = false
r.accounts[i].ErrorMessage = message
}
}
return nil
}
func (r *grokCredentialHandlerRepo) SetTempUnschedulable(_ context.Context, id int64, until time.Time, _ string) error {
r.mu.Lock()
defer r.mu.Unlock()
r.setTempIDs = append(r.setTempIDs, id)
if r.setTempErr != nil {
return r.setTempErr
}
for i := range r.accounts {
if r.accounts[i].ID == id {
value := until
r.accounts[i].TempUnschedulableUntil = &value
}
}
return nil
}
func (r *grokCredentialHandlerRepo) SetRateLimited(_ context.Context, id int64, resetAt time.Time) error {
r.mu.Lock()
defer r.mu.Unlock()
r.rateLimitIDs = append(r.rateLimitIDs, id)
for i := range r.accounts {
if r.accounts[i].ID != id {
continue
}
now := time.Now()
r.accounts[i].RateLimitedAt = &now
value := resetAt
r.accounts[i].RateLimitResetAt = &value
}
return nil
}
func (r *grokCredentialHandlerRepo) SetRateLimitedIfLater(ctx context.Context, id int64, resetAt time.Time) error {
r.mu.Lock()
for i := range r.accounts {
if r.accounts[i].ID == id && r.accounts[i].RateLimitResetAt != nil && !resetAt.After(*r.accounts[i].RateLimitResetAt) {
r.mu.Unlock()
return nil
}
}
r.mu.Unlock()
return r.SetRateLimited(ctx, id, resetAt)
}
func (r *grokCredentialHandlerRepo) SetGrokCredentialErrorIfMatch(
_ context.Context,
id int64,
snapshot service.GrokCredentialMutationSnapshot,
message string,
) (bool, error) {
r.mu.Lock()
defer r.mu.Unlock()
for i := range r.accounts {
account := &r.accounts[i]
if account.ID != id || !handlerGrokCredentialSnapshotMatches(account, snapshot) {
continue
}
r.setErrorIDs = append(r.setErrorIDs, id)
if r.setErrorErr != nil {
return false, r.setErrorErr
}
account.Status = service.StatusError
account.Schedulable = false
account.ErrorMessage = message
return true, nil
}
return false, nil
}
func (r *grokCredentialHandlerRepo) SetGrokCredentialTempUnschedulableIfMatch(
_ context.Context,
id int64,
snapshot service.GrokCredentialMutationSnapshot,
until time.Time,
_ string,
) (bool, error) {
r.mu.Lock()
defer r.mu.Unlock()
for i := range r.accounts {
account := &r.accounts[i]
if account.ID != id || !handlerGrokCredentialSnapshotMatches(account, snapshot) {
continue
}
r.setTempIDs = append(r.setTempIDs, id)
if r.setTempErr != nil {
return false, r.setTempErr
}
value := until
account.TempUnschedulableUntil = &value
return true, nil
}
return false, nil
}
func handlerGrokCredentialSnapshotMatches(account *service.Account, snapshot service.GrokCredentialMutationSnapshot) bool {
if account == nil {
return false
}
credentialsJSON, err := json.Marshal(account.Credentials)
return err == nil && account.IsGrokOAuth() && account.IsSchedulable() && string(credentialsJSON) == snapshot.CredentialsJSON &&
handlerGrokCredentialProxyIDsEqual(account.ProxyID, snapshot.ProxyID)
}
func handlerGrokCredentialProxyIDsEqual(left, right *int64) bool {
if left == nil || right == nil {
return left == nil && right == nil
}
return *left == *right
}
func (r *grokCredentialHandlerRepo) UpdateExtra(_ context.Context, id int64, updates map[string]any) error {
r.mu.Lock()
defer r.mu.Unlock()
r.updateExtraIDs = append(r.updateExtraIDs, id)
for i := range r.accounts {
if r.accounts[i].ID != id {
continue
}
if r.accounts[i].Extra == nil {
r.accounts[i].Extra = map[string]any{}
}
for key, value := range updates {
r.accounts[i].Extra[key] = value
}
}
return nil
}
func (r *grokCredentialHandlerRepo) errorIDs() []int64 {
r.mu.Lock()
defer r.mu.Unlock()
return append([]int64(nil), r.setErrorIDs...)
}
func (r *grokCredentialHandlerRepo) selectorCalls() int {
r.mu.Lock()
defer r.mu.Unlock()
return r.selectionCalls
}
func (r *grokCredentialHandlerRepo) rateLimitedAccountIDs() []int64 {
r.mu.Lock()
defer r.mu.Unlock()
return append([]int64(nil), r.rateLimitIDs...)
}
type grokCredentialHandlerTokenCache struct {
service.GrokTokenCache
mu sync.Mutex
deleteErr error
}
func (c *grokCredentialHandlerTokenCache) GetAccessToken(context.Context, string) (string, error) {
return "", errors.New("not cached")
}
func (c *grokCredentialHandlerTokenCache) SetAccessToken(context.Context, string, string, time.Duration) error {
return nil
}
func (c *grokCredentialHandlerTokenCache) DeleteAccessToken(context.Context, string) error {
c.mu.Lock()
defer c.mu.Unlock()
return c.deleteErr
}
func (c *grokCredentialHandlerTokenCache) AcquireRefreshLock(context.Context, string, time.Duration) (bool, error) {
return true, nil
}
func (c *grokCredentialHandlerTokenCache) ReleaseRefreshLock(context.Context, string) error {
return nil
}
func cloneCredentialMap(source map[string]any) map[string]any {
cloned := make(map[string]any, len(source))
for key, value := range source {
cloned[key] = value
}
return cloned
}
type grokCredentialHandlerRefresher struct {
mode string
started chan struct{}
once sync.Once
}
func (r *grokCredentialHandlerRefresher) CacheKey(account *service.Account) string {
return service.GrokTokenCacheKey(account)
}
func (r *grokCredentialHandlerRefresher) CanRefresh(account *service.Account) bool {
return account != nil && account.IsGrokOAuth()
}
func (r *grokCredentialHandlerRefresher) NeedsRefresh(account *service.Account, _ time.Duration) bool {
return account != nil && (account.ID == 801 || r.mode == "all_revoked")
}
func (r *grokCredentialHandlerRefresher) Refresh(ctx context.Context, _ *service.Account) (map[string]any, error) {
switch r.mode {
case "revoked", "all_revoked", "mutation_set_error", "mutation_cache":
return nil, infraerrors.New(http.StatusBadGateway, "GROK_OAUTH_TOKEN_REFRESH_FAILED", "invalid_grant")
case "provider":
return nil, infraerrors.New(http.StatusBadGateway, "GROK_OAUTH_TOKEN_REFRESH_FAILED", "invalid_client")
case "cancel":
r.once.Do(func() { close(r.started) })
<-ctx.Done()
return nil, ctx.Err()
case "transient", "mutation_temp":
return nil, errors.New("temporary refresh transport failure")
default:
return nil, nil
}
}
type grokCredentialHandlerUpstream struct {
service.HTTPUpstream
mu sync.Mutex
hits []int64
requestURLs []string
authorization []string
failAccountID int64
rateLimitIDs map[int64]bool
failureStatus map[int64]int
cancelRequest context.CancelFunc
}
func (u *grokCredentialHandlerUpstream) Do(req *http.Request, _ string, accountID int64, _ int) (*http.Response, error) {
var requestBody []byte
if req.Body != nil {
requestBody, _ = io.ReadAll(req.Body)
}
u.mu.Lock()
u.hits = append(u.hits, accountID)
u.requestURLs = append(u.requestURLs, req.URL.String())
u.authorization = append(u.authorization, req.Header.Get("Authorization"))
failAccountID := u.failAccountID
rateLimited := u.rateLimitIDs[accountID]
failureStatus := u.failureStatus[accountID]
cancelRequest := u.cancelRequest
u.mu.Unlock()
if rateLimited {
return &http.Response{
StatusCode: http.StatusTooManyRequests,
Header: http.Header{
"Content-Type": []string{"application/json"},
"Retry-After": []string{"60"},
},
Body: io.NopCloser(bytes.NewBufferString(`{"error":{"message":"rate limited"}}`)),
}, nil
}
if failureStatus > 0 {
return &http.Response{
StatusCode: failureStatus,
Header: http.Header{"Content-Type": []string{"application/json"}},
Body: io.NopCloser(bytes.NewBufferString(`{"error":{"message":"upstream unavailable"}}`)),
}, nil
}
if accountID == failAccountID {
if cancelRequest != nil {
cancelRequest()
}
return &http.Response{
StatusCode: http.StatusPaymentRequired,
Header: http.Header{"Content-Type": []string{"application/json"}},
Body: io.NopCloser(bytes.NewBufferString(`{"error":{"message":"payment required"}}`)),
}, nil
}
if bytes.Contains(requestBody, []byte(`"stream":true`)) {
return &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Content-Type": []string{"text/event-stream"}},
Body: io.NopCloser(bytes.NewBufferString(
"data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_healthy\",\"model\":\"grok-4.5\",\"usage\":{\"input_tokens\":1,\"output_tokens\":1}}}\n\n",
)),
}, nil
}
if strings.Contains(req.URL.Path, "/chat/completions") {
return &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Content-Type": []string{"application/json"}},
Body: io.NopCloser(bytes.NewBufferString(
`{"id":"chatcmpl_healthy","object":"chat.completion","model":"grok-4.5","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}`,
)),
}, nil
}
return &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Content-Type": []string{"application/json"}},
Body: io.NopCloser(bytes.NewBufferString(
`{"id":"resp_healthy","object":"response","model":"grok-4.5","status":"completed","output":[],"usage":{"input_tokens":1,"output_tokens":1}}`,
)),
}, nil
}
func (u *grokCredentialHandlerUpstream) accountHits() []int64 {
u.mu.Lock()
defer u.mu.Unlock()
return append([]int64(nil), u.hits...)
}
func (u *grokCredentialHandlerUpstream) requests() ([]string, []string) {
u.mu.Lock()
defer u.mu.Unlock()
return append([]string(nil), u.requestURLs...), append([]string(nil), u.authorization...)
}
func TestResponsesCredentialFailoverLoop(t *testing.T) {
gin.SetMode(gin.TestMode)
t.Run("revoked account selects healthy account", func(t *testing.T) {
h, repo, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "revoked")
defer cleanup()
_ = h
recorder := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/openai/v1/responses", bytes.NewBufferString(`{"model":"grok","input":"hello","stream":false}`))
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(recorder, req)
require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String())
require.Contains(t, recorder.Body.String(), "resp_healthy")
require.Equal(t, []int64{801}, repo.errorIDs())
require.Equal(t, []int64{802}, upstream.accountHits())
requestURLs, authorization := upstream.requests()
require.Equal(t, []string{xai.DefaultCLIBaseURL + "/responses"}, requestURLs)
require.Equal(t, []string{"Bearer healthy-access"}, authorization)
})
t.Run("provider configuration stops before healthy account", func(t *testing.T) {
h, repo, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "provider")
defer cleanup()
recorder := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/openai/v1/responses", bytes.NewBufferString(`{"model":"grok","input":"hello","stream":false}`))
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(recorder, req)
require.Equal(t, http.StatusServiceUnavailable, recorder.Code)
require.Contains(t, recorder.Body.String(), service.GrokCredentialUnavailableClientMessage)
require.Empty(t, repo.errorIDs())
require.Empty(t, upstream.accountHits())
require.Equal(t, 1, repo.selectorCalls())
require.Zero(t, h.gatewayService.SnapshotOpenAIAccountSchedulerMetrics().RuntimeStatsAccountCount,
"provider-scoped auth failure must not penalize the selected account")
})
t.Run("parent cancellation stops before healthy account", func(t *testing.T) {
_, repo, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "cancel")
defer cleanup()
ctx, cancel := context.WithCancel(context.Background())
req := httptest.NewRequest(http.MethodPost, "/openai/v1/responses", bytes.NewBufferString(`{"model":"grok","input":"hello","stream":false}`)).WithContext(ctx)
req.Header.Set("Content-Type", "application/json")
recorder := httptest.NewRecorder()
done := make(chan struct{})
go func() {
defer close(done)
router.ServeHTTP(recorder, req)
}()
select {
case <-time.After(2 * time.Second):
t.Fatal("credential refresh did not start")
case <-findHandlerRefresherStarted(router):
cancel()
}
select {
case <-time.After(2 * time.Second):
t.Fatal("handler did not stop after cancellation")
case <-done:
}
require.Empty(t, repo.errorIDs())
require.Empty(t, upstream.accountHits())
})
t.Run("post-mapping cancellation stops before scheduler mutation or reselection", func(t *testing.T) {
h, repo, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "postmap_cancel")
defer cleanup()
ctx, cancel := context.WithCancel(context.Background())
upstream.mu.Lock()
upstream.failAccountID = 801
upstream.cancelRequest = cancel
upstream.mu.Unlock()
recorder := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/openai/v1/responses", bytes.NewBufferString(`{"model":"grok","input":"hello","stream":false}`)).WithContext(ctx)
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(recorder, req)
require.Equal(t, []int64{801}, upstream.accountHits())
require.Empty(t, repo.errorIDs())
require.Equal(t, 1, repo.selectorCalls())
require.Zero(t, h.gatewayService.SnapshotOpenAIAccountSchedulerMetrics().RuntimeStatsAccountCount)
})
t.Run("pre-cancelled request never invokes an account selector", func(t *testing.T) {
tests := []struct {
name string
method string
path string
body string
}{
{name: "responses", method: http.MethodPost, path: "/openai/v1/responses", body: `{"model":"grok","input":"hello","stream":false}`},
{name: "messages", method: http.MethodPost, path: "/openai/v1/messages", body: `{"model":"grok","max_tokens":16,"messages":[{"role":"user","content":"hello"}]}`},
{name: "chat completions", method: http.MethodPost, path: "/openai/v1/chat/completions", body: `{"model":"grok","messages":[{"role":"user","content":"hello"}],"stream":false}`},
{name: "grok media", method: http.MethodGet, path: "/openai/v1/videos/request-1"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, repo, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "revoked")
defer cleanup()
ctx, cancel := context.WithCancel(context.Background())
cancel()
recorder := httptest.NewRecorder()
req := httptest.NewRequest(tt.method, tt.path, bytes.NewBufferString(tt.body)).WithContext(ctx)
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(recorder, req)
require.Zero(t, repo.selectorCalls())
require.Empty(t, upstream.accountHits())
})
}
})
t.Run("credential state mutation failures stop before reselection", func(t *testing.T) {
for _, mode := range []string{"mutation_set_error", "mutation_temp", "mutation_cache"} {
t.Run(mode, func(t *testing.T) {
_, repo, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, mode)
defer cleanup()
recorder := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/openai/v1/responses", bytes.NewBufferString(`{"model":"grok","input":"hello","stream":false}`))
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(recorder, req)
require.Equal(t, http.StatusServiceUnavailable, recorder.Code, recorder.Body.String())
require.Contains(t, recorder.Body.String(), service.GrokCredentialUnavailableClientMessage)
require.Empty(t, upstream.accountHits())
require.Equal(t, 1, repo.selectorCalls())
})
}
})
t.Run("missing credential provider stops before upstream or reselection", func(t *testing.T) {
_, repo, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "nil_provider")
defer cleanup()
recorder := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/openai/v1/responses", bytes.NewBufferString(`{"model":"grok","input":"hello","stream":false}`))
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(recorder, req)
require.Equal(t, http.StatusServiceUnavailable, recorder.Code, recorder.Body.String())
require.Contains(t, recorder.Body.String(), service.GrokCredentialUnavailableClientMessage)
require.Equal(t, 1, repo.selectorCalls())
require.Empty(t, upstream.accountHits())
require.Empty(t, repo.errorIDs())
})
}
func TestResponsesGrok429FailoverIsBounded(t *testing.T) {
gin.SetMode(gin.TestMode)
t.Run("first rate limited account selects healthy account", func(t *testing.T) {
_, repo, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "first_429")
defer cleanup()
recorder := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/openai/v1/responses", bytes.NewBufferString(`{"model":"grok","input":"hello","stream":false}`))
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(recorder, req)
require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String())
require.Contains(t, recorder.Body.String(), "resp_healthy")
require.Equal(t, []int64{801, 802}, upstream.accountHits())
require.Equal(t, []int64{801}, repo.rateLimitedAccountIDs())
})
t.Run("two rate limited accounts stop without sweeping the pool", func(t *testing.T) {
_, repo, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "all_429")
defer cleanup()
recorder := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/openai/v1/responses", bytes.NewBufferString(`{"model":"grok","input":"hello","stream":false}`))
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(recorder, req)
require.Equal(t, http.StatusTooManyRequests, recorder.Code, recorder.Body.String())
require.Equal(t, []int64{801, 802}, upstream.accountHits())
require.Equal(t, []int64{801, 802}, repo.rateLimitedAccountIDs())
require.NotContains(t, recorder.Body.String(), "expired")
require.NotContains(t, recorder.Body.String(), "healthy-access")
require.NotContains(t, recorder.Body.String(), "rate limited")
})
}
func TestResponsesGrok429FailoverHandlesMixedStatuses(t *testing.T) {
gin.SetMode(gin.TestMode)
t.Run("429 then 500 stops after the bounded followup", func(t *testing.T) {
_, _, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "mixed_429_500")
defer cleanup()
recorder := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/openai/v1/responses", bytes.NewBufferString(`{"model":"grok","input":"hello","stream":false}`))
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(recorder, req)
require.Equal(t, http.StatusBadGateway, recorder.Code, recorder.Body.String())
require.Equal(t, []int64{801, 802}, upstream.accountHits())
require.NotContains(t, recorder.Body.String(), "upstream unavailable")
})
t.Run("500 then 429 permits one healthy followup", func(t *testing.T) {
_, _, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "mixed_500_429")
defer cleanup()
recorder := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/openai/v1/responses", bytes.NewBufferString(`{"model":"grok","input":"hello","stream":false}`))
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(recorder, req)
require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String())
require.Equal(t, []int64{801, 802, 803}, upstream.accountHits())
})
t.Run("OAuth 429 then API-key failure cannot bypass the bound", func(t *testing.T) {
_, _, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "oauth_429_apikey_500")
defer cleanup()
recorder := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/openai/v1/responses", bytes.NewBufferString(`{"model":"grok","input":"hello","stream":false}`))
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(recorder, req)
require.Equal(t, http.StatusBadGateway, recorder.Code, recorder.Body.String())
require.Equal(t, []int64{801, 802}, upstream.accountHits())
})
}
func TestGrokMedia429FailoverIsBounded(t *testing.T) {
gin.SetMode(gin.TestMode)
t.Run("first 429 selects one healthy followup", func(t *testing.T) {
_, _, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "first_429")
defer cleanup()
recorder := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/openai/v1/videos/request-1", nil)
router.ServeHTTP(recorder, req)
require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String())
require.Equal(t, []int64{801, 802}, upstream.accountHits())
})
t.Run("second 429 stops without sweeping a third account", func(t *testing.T) {
_, _, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "all_429")
defer cleanup()
recorder := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/openai/v1/videos/request-1", nil)
router.ServeHTTP(recorder, req)
require.Equal(t, http.StatusTooManyRequests, recorder.Code, recorder.Body.String())
require.Equal(t, []int64{801, 802}, upstream.accountHits())
require.NotContains(t, recorder.Body.String(), "rate limited")
})
}
func TestGrokOAuthCredentialFailoverAcrossHTTPHandlers(t *testing.T) {
gin.SetMode(gin.TestMode)
endpoints := []struct {
name string
method string
path string
body string
}{
{name: "messages", method: http.MethodPost, path: "/openai/v1/messages", body: `{"model":"grok","max_tokens":16,"messages":[{"role":"user","content":"hello"}]}`},
{name: "chat completions", method: http.MethodPost, path: "/openai/v1/chat/completions", body: `{"model":"grok","messages":[{"role":"user","content":"hello"}],"stream":false}`},
{name: "chat completions raw fallback", method: http.MethodPost, path: "/openai/v1/chat/completions", body: `{"model":"grok","messages":[{"role":"user","content":"hello"}],"stop":["END"],"stream":false}`},
{name: "grok media", method: http.MethodGet, path: "/openai/v1/videos/request-1"},
}
for _, endpoint := range endpoints {
t.Run(endpoint.name+" revoked selects healthy", func(t *testing.T) {
_, repo, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "revoked")
defer cleanup()
recorder := httptest.NewRecorder()
req := httptest.NewRequest(endpoint.method, endpoint.path, bytes.NewBufferString(endpoint.body))
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(recorder, req)
require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String())
require.Equal(t, []int64{801}, repo.errorIDs())
require.Equal(t, []int64{802}, upstream.accountHits())
})
t.Run(endpoint.name+" all accounts exhausted safely", func(t *testing.T) {
_, repo, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "all_revoked")
defer cleanup()
recorder := httptest.NewRecorder()
req := httptest.NewRequest(endpoint.method, endpoint.path, bytes.NewBufferString(endpoint.body))
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(recorder, req)
require.Equal(t, http.StatusServiceUnavailable, recorder.Code, recorder.Body.String())
require.Contains(t, recorder.Body.String(), service.GrokCredentialUnavailableClientMessage)
require.NotContains(t, recorder.Body.String(), "revoked-refresh")
require.NotContains(t, recorder.Body.String(), "healthy-refresh")
require.Equal(t, []int64{801, 802}, repo.errorIDs())
require.Empty(t, upstream.accountHits())
})
}
}
func TestGrokOAuthMissingSelectedRowRetriesHealthyAccountWithoutMutation(t *testing.T) {
gin.SetMode(gin.TestMode)
_, repo, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "missing_row")
defer cleanup()
recorder := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/openai/v1/responses", bytes.NewBufferString(`{"model":"grok","input":"hello","stream":false}`))
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(recorder, req)
require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String())
require.Equal(t, []int64{802}, upstream.accountHits())
require.Empty(t, repo.errorIDs())
require.Empty(t, repo.setTempIDs)
}
func TestResponsesWebSocketCredentialFailoverLoop(t *testing.T) {
gin.SetMode(gin.TestMode)
dial := func(t *testing.T, router *gin.Engine) (*coderws.Conn, func()) {
t.Helper()
server := httptest.NewServer(router)
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
conn, _, err := coderws.Dial(ctx, "ws"+strings.TrimPrefix(server.URL, "http")+"/openai/v1/responses", nil)
cancel()
require.NoError(t, err)
return conn, func() {
_ = conn.CloseNow()
server.Close()
}
}
writeFirst := func(t *testing.T, conn *coderws.Conn) {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
require.NoError(t, conn.Write(ctx, coderws.MessageText, []byte(`{"type":"response.create","model":"grok","input":"hello","stream":false}`)))
}
t.Run("revoked account selects healthy account", func(t *testing.T) {
_, repo, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "revoked")
defer cleanup()
conn, closeConn := dial(t, router)
defer closeConn()
writeFirst(t, conn)
readCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
_, payload, err := conn.Read(readCtx)
cancel()
require.NoError(t, err)
require.Contains(t, string(payload), "resp_healthy")
require.Equal(t, []int64{801}, repo.errorIDs())
require.Equal(t, 2, repo.selectorCalls())
require.Equal(t, []int64{802}, upstream.accountHits())
})
t.Run("provider configuration stops", func(t *testing.T) {
_, repo, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "provider")
defer cleanup()
conn, closeConn := dial(t, router)
defer closeConn()
writeFirst(t, conn)
readCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
_, _, err := conn.Read(readCtx)
cancel()
var closeErr coderws.CloseError
require.ErrorAs(t, err, &closeErr)
require.Contains(t, closeErr.Reason, service.GrokCredentialUnavailableClientMessage)
require.Equal(t, 1, repo.selectorCalls())
require.Empty(t, upstream.accountHits())
})
t.Run("parent cancellation prevents reselection", func(t *testing.T) {
_, repo, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "cancel")
defer cleanup()
conn, closeConn := dial(t, router)
writeFirst(t, conn)
select {
case <-findHandlerRefresherStarted(router):
case <-time.After(2 * time.Second):
t.Fatal("credential refresh did not start")
}
closeConn()
require.Eventually(t, func() bool { return repo.selectorCalls() == 1 }, 2*time.Second, 20*time.Millisecond)
require.Empty(t, repo.errorIDs())
require.Empty(t, upstream.accountHits())
})
}
var handlerRefresherStarted sync.Map
func findHandlerRefresherStarted(router *gin.Engine) <-chan struct{} {
value, _ := handlerRefresherStarted.Load(router)
return value.(chan struct{})
}
func newGrokCredentialFailoverHandler(t *testing.T, mode string) (*OpenAIGatewayHandler, *grokCredentialHandlerRepo, *grokCredentialHandlerUpstream, *gin.Engine, func()) {
t.Helper()
groupID := int64(901)
accounts := []service.Account{
{
ID: 801, Name: "revoked", Platform: service.PlatformGrok, Type: service.AccountTypeOAuth,
Status: service.StatusActive, Schedulable: true, Concurrency: 1, Priority: 1,
Credentials: map[string]any{
"access_token": "expired", "refresh_token": "revoked-refresh",
"expires_at": time.Now().Add(-time.Minute).UTC().Format(time.RFC3339),
},
},
{
ID: 802, Name: "healthy", Platform: service.PlatformGrok, Type: service.AccountTypeOAuth,
Status: service.StatusActive, Schedulable: true, Concurrency: 1, Priority: 2,
Credentials: map[string]any{
"access_token": "healthy-access", "refresh_token": "healthy-refresh",
"expires_at": time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339),
},
},
}
if mode == "postmap_cancel" || mode == "first_429" || mode == "all_429" || mode == "mixed_429_500" || mode == "mixed_500_429" || mode == "oauth_429_apikey_500" {
accounts[0].Credentials["expires_at"] = time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339)
}
if mode == "all_429" || mode == "mixed_429_500" || mode == "mixed_500_429" || mode == "oauth_429_apikey_500" {
accounts = append(accounts, service.Account{
ID: 803, Name: "untried-healthy", Platform: service.PlatformGrok, Type: service.AccountTypeOAuth,
Status: service.StatusActive, Schedulable: true, Concurrency: 1, Priority: 3,
Credentials: map[string]any{
"access_token": "untried-healthy-access", "refresh_token": "untried-healthy-refresh",
"expires_at": time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339),
},
})
}
if mode == "oauth_429_apikey_500" {
accounts[1].Type = service.AccountTypeAPIKey
accounts[1].Credentials = map[string]any{"api_key": "third-party-key"}
}
if mode == "all_revoked" {
accounts[1].Credentials["expires_at"] = time.Now().Add(-time.Minute).UTC().Format(time.RFC3339)
}
repo := &grokCredentialHandlerRepo{accounts: accounts, missingOnGet: map[int64]bool{}}
if mode == "missing_row" {
repo.missingOnGet[801] = true
}
if mode == "mutation_set_error" {
repo.setErrorErr = errors.New("database write failed")
}
if mode == "mutation_temp" {
repo.setTempErr = errors.New("database write failed")
}
refresher := &grokCredentialHandlerRefresher{mode: mode, started: make(chan struct{})}
tokenCache := &grokCredentialHandlerTokenCache{}
if mode == "mutation_cache" {
tokenCache.deleteErr = errors.New("cache delete failed")
}
var provider *service.GrokTokenProvider
if mode != "nil_provider" {
provider = service.NewGrokTokenProvider(repo, tokenCache)
provider.SetRefreshAPI(service.NewOAuthRefreshAPI(repo, tokenCache), refresher)
}
upstream := &grokCredentialHandlerUpstream{}
switch mode {
case "first_429":
upstream.rateLimitIDs = map[int64]bool{801: true}
case "all_429":
upstream.rateLimitIDs = map[int64]bool{801: true, 802: true}
case "mixed_429_500":
upstream.rateLimitIDs = map[int64]bool{801: true}
upstream.failureStatus = map[int64]int{802: http.StatusInternalServerError}
case "mixed_500_429":
upstream.failureStatus = map[int64]int{801: http.StatusInternalServerError}
upstream.rateLimitIDs = map[int64]bool{802: true}
case "oauth_429_apikey_500":
upstream.rateLimitIDs = map[int64]bool{801: true}
upstream.failureStatus = map[int64]int{802: http.StatusInternalServerError}
}
cfg := &config.Config{RunMode: config.RunModeSimple}
cfg.Gateway.MaxAccountSwitches = 3
billingCache := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
gateway := service.NewOpenAIGatewayService(
repo, nil, nil, nil, nil, nil, nil, cfg, nil, nil,
service.NewBillingService(cfg, nil), nil, billingCache, upstream,
&service.DeferredService{}, nil, provider, nil, nil, nil, nil, nil,
)
cache := &concurrencyCacheMock{
acquireUserSlotFn: func(context.Context, int64, int, string) (bool, error) { return true, nil },
acquireAccountSlotFn: func(context.Context, int64, int, string) (bool, error) { return true, nil },
}
h := NewOpenAIGatewayHandler(gateway, service.NewConcurrencyService(cache), billingCache, &service.APIKeyService{}, nil, nil, nil, nil, cfg)
apiKey := &service.APIKey{
ID: 902, GroupID: &groupID,
User: &service.User{ID: 903, Status: service.StatusActive},
Group: &service.Group{ID: groupID, Platform: service.PlatformGrok, Status: service.StatusActive},
}
router := gin.New()
router.Use(func(c *gin.Context) {
c.Set(string(middleware.ContextKeyAPIKey), apiKey)
c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: apiKey.User.ID, Concurrency: 1})
c.Next()
})
router.POST("/openai/v1/responses", h.Responses)
router.GET("/openai/v1/responses", h.ResponsesWebSocket)
router.POST("/openai/v1/messages", h.Messages)
router.POST("/openai/v1/chat/completions", h.ChatCompletions)
router.GET("/openai/v1/videos/:request_id", h.GrokVideoStatus)
handlerRefresherStarted.Store(router, refresher.started)
cleanup := func() {
handlerRefresherStarted.Delete(router)
billingCache.Stop()
}
return h, repo, upstream, router, cleanup
}
@@ -0,0 +1,211 @@
//go:build unit
package handler
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
func TestGatewayChatCredentialStopDoesNotSelectAnotherAccountAndReturnsSafe503(t *testing.T) {
gin.SetMode(gin.TestMode)
stopErr := &service.UpstreamFailoverError{
Stage: service.GatewayFailureStageAccountAuth,
Scope: service.GatewayFailureScopeProvider,
Reason: service.GrokCredentialReasonProviderConfig,
NextAccountAction: service.NextAccountStop,
ClientStatusCode: http.StatusTeapot,
ClientMessage: "invalid_client client_secret=must-not-leak",
}
state := NewFailoverState(3, false)
action := state.HandleFailoverError(context.Background(), &mockTempUnscheduler{}, 71, service.PlatformGrok, 0, stopErr)
require.Equal(t, FailoverExhausted, action)
require.Zero(t, state.SwitchCount)
require.Empty(t, state.FailedAccountIDs)
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
(&GatewayHandler{}).handleCCFailoverExhausted(c, state.LastFailoverErr, false)
require.Equal(t, http.StatusServiceUnavailable, recorder.Code)
require.Contains(t, recorder.Body.String(), service.GrokCredentialUnavailableClientMessage)
require.NotContains(t, recorder.Body.String(), "invalid_client")
require.NotContains(t, recorder.Body.String(), "client_secret")
}
func TestGatewayChatInferenceExhaustionRestoresRetryAfter(t *testing.T) {
gin.SetMode(gin.TestMode)
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
(&GatewayHandler{}).handleCCFailoverExhausted(c, &service.UpstreamFailoverError{
StatusCode: http.StatusTooManyRequests,
ResponseHeaders: http.Header{"Retry-After": []string{"45"}},
}, false)
require.Equal(t, http.StatusTooManyRequests, recorder.Code)
require.Equal(t, "45", recorder.Header().Get("Retry-After"))
}
func TestCredentialFailoverExhaustionReturnsFixedSafe503(t *testing.T) {
gin.SetMode(gin.TestMode)
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
h := &OpenAIGatewayHandler{}
h.handleFailoverExhausted(c, &service.UpstreamFailoverError{
Stage: service.GatewayFailureStageAccountAuth,
Scope: service.GatewayFailureScopeAccount,
Reason: service.GrokCredentialReasonRevoked,
NextAccountAction: service.NextAccountRetry,
ClientStatusCode: http.StatusTeapot,
ClientMessage: "invalid_grant refresh_token=must-not-leak",
}, false)
require.Equal(t, http.StatusServiceUnavailable, recorder.Code)
require.Contains(t, recorder.Body.String(), service.GrokCredentialUnavailableClientMessage)
require.NotContains(t, strings.ToLower(recorder.Body.String()), "invalid_grant")
require.NotContains(t, strings.ToLower(recorder.Body.String()), "refresh_token")
require.NotContains(t, recorder.Body.String(), "must-not-leak")
}
func TestInferenceFailoverExhaustionRestoresRetryAfter(t *testing.T) {
gin.SetMode(gin.TestMode)
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
h := &OpenAIGatewayHandler{}
h.handleFailoverExhausted(c, &service.UpstreamFailoverError{
StatusCode: http.StatusTooManyRequests,
ResponseHeaders: http.Header{"Retry-After": []string{"17"}},
}, false)
require.Equal(t, http.StatusTooManyRequests, recorder.Code)
require.Equal(t, "17", recorder.Header().Get("Retry-After"))
}
func TestFailoverExhaustionRejectsSecretBearingRetryAfter(t *testing.T) {
gin.SetMode(gin.TestMode)
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
h := &OpenAIGatewayHandler{}
h.handleFailoverExhausted(c, &service.UpstreamFailoverError{
StatusCode: http.StatusTooManyRequests,
ResponseHeaders: http.Header{"Retry-After": []string{"refresh_token=must-not-leak"}},
}, false)
require.Equal(t, http.StatusTooManyRequests, recorder.Code)
require.Empty(t, recorder.Header().Get("Retry-After"))
require.NotContains(t, recorder.Body.String(), "must-not-leak")
}
func TestFailoverExhaustionRejectsFarFutureRetryAfterDate(t *testing.T) {
gin.SetMode(gin.TestMode)
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
h := &OpenAIGatewayHandler{}
h.handleFailoverExhausted(c, &service.UpstreamFailoverError{
StatusCode: http.StatusTooManyRequests,
ResponseHeaders: http.Header{
"Retry-After": []string{time.Now().Add(30 * 24 * time.Hour).UTC().Format(http.TimeFormat)},
},
}, false)
require.Equal(t, http.StatusTooManyRequests, recorder.Code)
require.Empty(t, recorder.Header().Get("Retry-After"))
}
func TestFailoverExhaustionAllowsBoundedRetryAfterDate(t *testing.T) {
gin.SetMode(gin.TestMode)
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
h := &OpenAIGatewayHandler{}
retryAfter := time.Now().Add(time.Hour).UTC().Format(http.TimeFormat)
h.handleFailoverExhausted(c, &service.UpstreamFailoverError{
StatusCode: http.StatusTooManyRequests,
ResponseHeaders: http.Header{"Retry-After": []string{retryAfter}},
}, false)
require.Equal(t, http.StatusTooManyRequests, recorder.Code)
require.Equal(t, retryAfter, recorder.Header().Get("Retry-After"))
}
func TestOpsClassificationTreatsCredentialFailureAsAuthNotInference(t *testing.T) {
gin.SetMode(gin.TestMode)
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Set(service.OpsUpstreamStatusCodeKey, http.StatusForbidden)
c.Set(service.OpsUpstreamErrorMessageKey, "stale inference message")
c.Set(service.OpsUpstreamErrorDetailKey, "stale inference detail")
c.Set(service.OpsUpstreamErrorsKey, []*service.OpsUpstreamErrorEvent{
{Stage: string(service.GatewayFailureStageInference), UpstreamStatusCode: http.StatusForbidden, Message: "stale inference message", Detail: "stale inference detail"},
{
Stage: string(service.GatewayFailureStageAccountAuth),
Scope: string(service.GatewayFailureScopeAccount),
Reason: string(service.GrokCredentialReasonRevoked),
UpstreamStatusCode: 0,
Message: "Grok OAuth credentials require account action",
},
})
phase, _, owner, source := classifyOpsErrorLog(c, "upstream_error", service.GrokCredentialUnavailableClientMessage, "", http.StatusServiceUnavailable)
require.Equal(t, "account_auth", phase)
require.Equal(t, "provider", owner)
require.Equal(t, "gateway", source)
entry := &service.OpsInsertErrorLogInput{}
applyOpsUpstreamFieldsFromContext(c, entry)
require.NotNil(t, entry.UpstreamStatusCode)
require.Zero(t, *entry.UpstreamStatusCode)
require.NotNil(t, entry.UpstreamErrorMessage)
require.Equal(t, "Grok OAuth credentials require account action", *entry.UpstreamErrorMessage)
require.Nil(t, entry.UpstreamErrorDetail)
require.Len(t, entry.UpstreamErrors, 2)
require.Equal(t, http.StatusForbidden, entry.UpstreamErrors[0].UpstreamStatusCode)
}
func TestOpsRecoveredCredentialFailoverUsesAccountAuthAttribution(t *testing.T) {
setupOpsErrorLogTestQueue(t, 2)
gin.SetMode(gin.TestMode)
ops := service.NewOpsService(nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
router := gin.New()
router.Use(OpsErrorLoggerMiddleware(ops))
router.GET("/openai/v1/responses", func(c *gin.Context) {
c.Set(service.OpsUpstreamErrorsKey, []*service.OpsUpstreamErrorEvent{
{Stage: string(service.GatewayFailureStageInference), UpstreamStatusCode: http.StatusForbidden, Message: "earlier inference failure"},
{
Stage: string(service.GatewayFailureStageAccountAuth), Scope: string(service.GatewayFailureScopeAccount),
Reason: string(service.GrokCredentialReasonRevoked), Message: "Grok OAuth credentials require account action",
},
})
c.JSON(http.StatusOK, gin.H{"ok": true})
})
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/openai/v1/responses", nil))
require.Equal(t, http.StatusOK, recorder.Code)
require.Equal(t, int64(1), OpsErrorLogQueueLength())
job := <-opsErrorLogQueue
require.Equal(t, "account_auth", job.entry.ErrorPhase)
require.Equal(t, "provider", job.entry.ErrorOwner)
require.Equal(t, "gateway", job.entry.ErrorSource)
require.Contains(t, job.entry.ErrorMessage, "Recovered account authentication failure")
require.NotContains(t, job.entry.ErrorMessage, "403")
require.NotContains(t, job.entry.ErrorMessage, "earlier inference failure")
require.NotNil(t, job.entry.UpstreamStatusCode)
require.Zero(t, *job.entry.UpstreamStatusCode)
require.Len(t, job.entry.UpstreamErrors, 2)
require.Equal(t, http.StatusForbidden, job.entry.UpstreamErrors[0].UpstreamStatusCode)
}
@@ -0,0 +1,51 @@
package handler
import (
"context"
"fmt"
"net/http/httptest"
"testing"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
func TestOpenAIForwardMayFailoverOnlyAfterNonSemanticWrite(t *testing.T) {
gin.SetMode(gin.TestMode)
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
before := service.OpenAICompactKeepaliveAdjustedWrittenSize(c)
_, err := fmt.Fprint(c.Writer, ":\n\n")
require.NoError(t, err)
c.Writer.Flush()
require.True(t, openAIForwardMayFailover(c, before, &service.UpstreamFailoverError{
SafeToFailoverAfterWrite: true,
}))
require.False(t, openAIForwardMayFailover(c, before, &service.UpstreamFailoverError{}))
}
func TestOpenAIFirstOutputFailoverStopsAfterOneAccountSwitch(t *testing.T) {
failoverErr := &service.UpstreamFailoverError{SafeToFailoverAfterWrite: true}
count := 0
require.False(t, openAIFirstOutputFailoverExhausted(failoverErr, &count))
require.Equal(t, 1, count)
require.True(t, openAIFirstOutputFailoverExhausted(failoverErr, &count))
require.Equal(t, 1, count)
}
func TestOpenAIRequestAllowsFailoverReplayStopsCanceledClient(t *testing.T) {
require.False(t, openAIRequestAllowsFailoverReplay(nil))
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
requestCtx, cancel := context.WithCancel(context.Background())
c.Request = httptest.NewRequest("POST", "/v1/responses", nil).WithContext(requestCtx)
require.True(t, openAIRequestAllowsFailoverReplay(c))
cancel()
require.False(t, openAIRequestAllowsFailoverReplay(c))
}
@@ -40,6 +40,8 @@ type OpenAIGatewayHandler struct {
cfg *config.Config
}
const maxOpenAIFirstOutputTimeoutSwitches = 1
func resolveOpenAIMessagesDispatchMappedModel(apiKey *service.APIKey, requestedModel string) string {
if apiKey == nil || apiKey.Group == nil {
return ""
@@ -56,6 +58,14 @@ func openAIModelMappedBody(body []byte, mapped bool, mappedModel string, replace
return replace(body, mappedModel)
}
func seedOpenAIForwardImageIntentHint(c *gin.Context, channelMapped bool, imageIntent bool) {
if channelMapped {
// 渠道映射改变了规范请求,保持 unknown,由 Forward 按映射后的 model/body 初始化。
return
}
service.SetOpenAIImageIntentHint(c, imageIntent)
}
func newOpenAIModelMappedBodyCache(body []byte, replace openAIModelBodyReplaceFunc) func(bool, string) []byte {
replacedBodies := make(map[string][]byte)
return func(mapped bool, mappedModel string) []byte {
@@ -282,6 +292,7 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
// 解析渠道级模型映射
channelMapping, _ := h.gatewayService.ResolveChannelMappingAndRestrict(c.Request.Context(), apiKey.GroupID, reqModel)
forwardBody := openAIModelMappedBody(body, channelMapping.Mapped, channelMapping.MappedModel, h.gatewayService.ReplaceModelInBody)
seedOpenAIForwardImageIntentHint(c, channelMapping.Mapped, imageIntent)
// 提前校验 function_call_output 是否具备可关联上下文,避免上游 400。
if !h.validateFunctionCallOutputRequest(c, body, reqLog) {
@@ -329,11 +340,19 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
maxAccountSwitches := h.maxAccountSwitches
switchCount := 0
firstOutputTimeoutSwitchCount := 0
failedAccountIDs := make(map[int64]struct{})
sameAccountRetryCount := make(map[int64]int)
var lastFailoverErr *service.UpstreamFailoverError
var oauth429FailoverState service.OpenAIOAuth429FailoverState
for {
// Streaming Forward intentionally detaches the upstream request so usage can
// be drained after a disconnect. Re-check the client context before every
// account attempt so a canceled request never starts a failover replay.
if !openAIRequestAllowsFailoverReplay(c) {
return
}
// Select account supporting the requested model
reqLog.Debug("openai.account_selecting", zap.Int("excluded_account_count", len(failedAccountIDs)))
selection, scheduleDecision, err := h.gatewayService.SelectAccountWithSchedulerForCapability(
@@ -350,6 +369,10 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
requestPlatform,
)
if err != nil {
if failoverClientGone(c) {
reqLog.Info("openai.account_select_aborted_client_disconnected", zap.Error(err))
return
}
reqLog.Warn("openai.account_select_failed",
zap.Error(openAICompatibleSelectionErrorForLog(err, requestPlatform)),
zap.Int("excluded_account_count", len(failedAccountIDs)),
@@ -443,11 +466,31 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
} else {
var failoverErr *service.UpstreamFailoverError
if errors.As(err, &failoverErr) {
if service.OpenAICompactKeepaliveAdjustedWrittenSize(c) != writerSizeBeforeForward {
if failoverClientGone(c) {
reqLog.Info("openai.failover_aborted_client_disconnected",
zap.Int64("account_id", account.ID),
zap.Int("upstream_status", failoverErr.StatusCode),
)
return
}
if !openAIForwardMayFailover(c, writerSizeBeforeForward, failoverErr) {
h.handleFailoverExhausted(c, failoverErr, true)
return
}
h.gatewayService.ReportOpenAIAccountScheduleResult(account.ID, false, nil)
if failoverErr.SafeToFailoverAfterWrite && c.Writer.Written() {
streamStarted = true
}
if failoverErr.ShouldReportAccountScheduleFailure() {
h.gatewayService.ReportOpenAIAccountScheduleResult(account.ID, false, nil)
}
if !failoverErr.ShouldRetryNextAccount() {
h.handleFailoverExhausted(c, failoverErr, streamStarted)
return
}
if openAIFirstOutputFailoverExhausted(failoverErr, &firstOutputTimeoutSwitchCount) {
h.handleFailoverExhausted(c, failoverErr, streamStarted)
return
}
// 池模式:同账号重试
if failoverErr.RetryableOnSameAccount {
retryLimit := account.GetPoolModeRetryCount()
@@ -475,16 +518,27 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
return
}
switchCount++
if h.gatewayService.ShouldStopOpenAIOAuth429Failover(account, failoverErr.StatusCode, switchCount) {
if h.gatewayService.ShouldStopOpenAIOAuth429Failover(account, failoverErr.StatusCode, switchCount, &oauth429FailoverState) {
h.handleFailoverExhausted(c, failoverErr, streamStarted)
return
}
reqLog.Warn("openai.upstream_failover_switching",
failoverSwitchFields := []zap.Field{
zap.Int64("account_id", account.ID),
zap.Int("upstream_status", failoverErr.StatusCode),
zap.Int("switch_count", switchCount),
zap.Int("max_switches", maxAccountSwitches),
)
}
if account.Proxy != nil {
failoverSwitchFields = append(failoverSwitchFields,
zap.Int64("proxy_id", account.Proxy.ID),
zap.String("proxy_name", account.Proxy.Name),
zap.String("proxy_host", account.Proxy.Host),
zap.Int("proxy_port", account.Proxy.Port),
)
} else if account.ProxyID != nil {
failoverSwitchFields = append(failoverSwitchFields, zap.Int64p("proxy_id", account.ProxyID))
}
reqLog.Warn("openai.upstream_failover_switching", failoverSwitchFields...)
continue
}
h.gatewayService.ReportOpenAIAccountScheduleResult(account.ID, false, nil)
@@ -832,9 +886,13 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) {
failedAccountIDs := make(map[int64]struct{})
sameAccountRetryCount := make(map[int64]int)
var lastFailoverErr *service.UpstreamFailoverError
var oauth429FailoverState service.OpenAIOAuth429FailoverState
effectiveMappedModel := preferredMappedModel
for {
if failoverClientGone(c) {
return
}
currentRoutingModel := routingModel
if effectiveMappedModel != "" {
currentRoutingModel = effectiveMappedModel
@@ -854,6 +912,10 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) {
requestPlatform,
)
if err != nil {
if failoverClientGone(c) {
reqLog.Info("openai_messages.account_select_aborted_client_disconnected", zap.Error(err))
return
}
reqLog.Warn("openai_messages.account_select_failed",
zap.Error(openAICompatibleSelectionErrorForLog(err, requestPlatform)),
zap.Int("excluded_account_count", len(failedAccountIDs)),
@@ -935,11 +997,24 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) {
} else {
var failoverErr *service.UpstreamFailoverError
if errors.As(err, &failoverErr) {
if failoverClientGone(c) {
reqLog.Info("openai_messages.failover_aborted_client_disconnected",
zap.Int64("account_id", account.ID),
zap.Int("upstream_status", failoverErr.StatusCode),
)
return
}
if c.Writer.Size() != writerSizeBeforeForward {
h.handleAnthropicFailoverExhausted(c, failoverErr, true)
return
}
h.gatewayService.ReportOpenAIAccountScheduleResult(account.ID, false, nil)
if failoverErr.ShouldReportAccountScheduleFailure() {
h.gatewayService.ReportOpenAIAccountScheduleResult(account.ID, false, nil)
}
if !failoverErr.ShouldRetryNextAccount() {
h.handleAnthropicFailoverExhausted(c, failoverErr, streamStarted)
return
}
// 池模式:同账号重试
if failoverErr.RetryableOnSameAccount {
retryLimit := account.GetPoolModeRetryCount()
@@ -967,7 +1042,7 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) {
return
}
switchCount++
if h.gatewayService.ShouldStopOpenAIOAuth429Failover(account, failoverErr.StatusCode, switchCount) {
if h.gatewayService.ShouldStopOpenAIOAuth429Failover(account, failoverErr.StatusCode, switchCount, &oauth429FailoverState) {
h.handleAnthropicFailoverExhausted(c, failoverErr, streamStarted)
return
}
@@ -1093,6 +1168,14 @@ func (h *OpenAIGatewayHandler) anthropicStreamingAwareError(c *gin.Context, stat
// handleAnthropicFailoverExhausted maps upstream failover errors to Anthropic format.
func (h *OpenAIGatewayHandler) handleAnthropicFailoverExhausted(c *gin.Context, failoverErr *service.UpstreamFailoverError, streamStarted bool) {
if failoverErr != nil {
copyFailoverRetryAfter(c, failoverErr.ResponseHeaders)
}
if failoverErr != nil && failoverErr.IsCredentialFailure() {
status, message := credentialFailoverClientResponse(failoverErr)
h.anthropicStreamingAwareError(c, status, "api_error", message, streamStarted)
return
}
status, errType, errMsg := h.mapUpstreamError(failoverErr.StatusCode)
h.anthropicStreamingAwareError(c, status, errType, errMsg, streamStarted)
}
@@ -1320,7 +1403,8 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
c.Request = c.Request.WithContext(ctx)
}
readCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
firstMessageTimeout := service.ResolveOpenAIWSClientFirstMessageTimeout(h.cfg)
readCtx, cancel := context.WithTimeout(ctx, firstMessageTimeout)
msgType, firstMessage, err := wsConn.Read(readCtx)
cancel()
if err != nil {
@@ -1335,7 +1419,7 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
zap.String("client_ip", clientIP),
zap.String("close_status", closeStatus),
zap.String("close_reason", closeReason),
zap.Duration("read_timeout", 30*time.Second),
zap.Duration("read_timeout", firstMessageTimeout),
)
closeOpenAIClientWS(wsConn, coderws.StatusPolicyViolation, "missing first response.create message")
return
@@ -1464,8 +1548,50 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
switchCount := 0
failedAccountIDs := make(map[int64]struct{})
var lastFailoverErr *service.UpstreamFailoverError
var oauth429FailoverState service.OpenAIOAuth429FailoverState
handleWSFailover := func(account *service.Account, failoverErr *service.UpstreamFailoverError) bool {
if ctx.Err() != nil {
return false
}
if failoverErr.ShouldReportAccountScheduleFailure() {
h.gatewayService.ReportOpenAIAccountScheduleResult(account.ID, false, nil)
}
releaseAccountSlot()
if !failoverErr.ShouldRetryNextAccount() {
closeOpenAIWSFailoverExhausted(wsConn, failoverErr)
return false
}
if ctx.Err() != nil {
return false
}
h.gatewayService.RecordOpenAIAccountSwitch()
failedAccountIDs[account.ID] = struct{}{}
lastFailoverErr = failoverErr
if switchCount >= maxAccountSwitches {
closeOpenAIWSFailoverExhausted(wsConn, failoverErr)
return false
}
switchCount++
if h.gatewayService.ShouldStopOpenAIOAuth429Failover(account, failoverErr.StatusCode, switchCount, &oauth429FailoverState) {
closeOpenAIWSFailoverExhausted(wsConn, failoverErr)
return false
}
reqLog.Warn("openai.websocket_upstream_failover_switching",
zap.Int64("account_id", account.ID),
zap.Int("upstream_status", failoverErr.StatusCode),
zap.Int("switch_count", switchCount),
zap.Int("max_switches", maxAccountSwitches),
)
if ctx.Err() != nil {
return false
}
return ensureUserSlotHeld()
}
for {
if ctx.Err() != nil {
return
}
reqLog.Debug("openai.websocket_account_selecting", zap.Int("excluded_account_count", len(failedAccountIDs)))
selection, scheduleDecision, err := h.gatewayService.SelectAccountWithSchedulerForCapability(
ctx,
@@ -1533,9 +1659,19 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
reqLog.Warn("openai.websocket_bind_sticky_session_failed", zap.Int64("account_id", account.ID), zap.Error(err))
}
token, _, err := h.gatewayService.GetAccessToken(ctx, account)
token, _, err := h.gatewayService.GetRequestCredential(ctx, c, account)
if err != nil {
reqLog.Warn("openai.websocket_get_access_token_failed", zap.Int64("account_id", account.ID), zap.Error(err))
if ctx.Err() != nil {
return
}
var failoverErr *service.UpstreamFailoverError
if errors.As(err, &failoverErr) {
if handleWSFailover(account, failoverErr) {
continue
}
return
}
closeOpenAIClientWS(wsConn, coderws.StatusInternalError, "failed to get access token")
return
}
@@ -1692,30 +1828,10 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
if err := h.gatewayService.ProxyResponsesWebSocketFromClient(ctx, c, wsConn, account, token, wsFirstMessage, hooks); err != nil {
var failoverErr *service.UpstreamFailoverError
if errors.As(err, &failoverErr) {
h.gatewayService.ReportOpenAIAccountScheduleResult(account.ID, false, nil)
releaseAccountSlot()
failedAccountIDs[account.ID] = struct{}{}
lastFailoverErr = failoverErr
if switchCount >= maxAccountSwitches {
closeOpenAIWSFailoverExhausted(wsConn, failoverErr)
return
if handleWSFailover(account, failoverErr) {
continue
}
switchCount++
if h.gatewayService.ShouldStopOpenAIOAuth429Failover(account, failoverErr.StatusCode, switchCount) {
closeOpenAIWSFailoverExhausted(wsConn, failoverErr)
return
}
h.gatewayService.RecordOpenAIAccountSwitch()
reqLog.Warn("openai.websocket_upstream_failover_switching",
zap.Int64("account_id", account.ID),
zap.Int("upstream_status", failoverErr.StatusCode),
zap.Int("switch_count", switchCount),
zap.Int("max_switches", maxAccountSwitches),
)
if !ensureUserSlotHeld() {
return
}
continue
return
}
if errors.Is(context.Cause(ctx), service.ErrOpenAIWSIngressLeaseLost) {
@@ -1739,12 +1855,23 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
h.gatewayService.ReportOpenAIAccountScheduleResult(account.ID, false, nil)
closeStatus, closeReason := summarizeWSCloseErrorForLog(err)
reqLog.Warn("openai.websocket_proxy_failed",
proxyFailedFields := []zap.Field{
zap.Int64("account_id", account.ID),
zap.Error(err),
zap.String("close_status", closeStatus),
zap.String("close_reason", closeReason),
)
}
if account.Proxy != nil {
proxyFailedFields = append(proxyFailedFields,
zap.Int64("proxy_id", account.Proxy.ID),
zap.String("proxy_name", account.Proxy.Name),
zap.String("proxy_host", account.Proxy.Host),
zap.Int("proxy_port", account.Proxy.Port),
)
} else if account.ProxyID != nil {
proxyFailedFields = append(proxyFailedFields, zap.Int64p("proxy_id", account.ProxyID))
}
reqLog.Warn("openai.websocket_proxy_failed", proxyFailedFields...)
if errors.As(err, &closeErr) {
closeOpenAIClientWS(wsConn, closeErr.StatusCode(), closeErr.Reason())
return
@@ -1946,6 +2073,16 @@ func (h *OpenAIGatewayHandler) handleConcurrencyError(c *gin.Context, err error,
}
func (h *OpenAIGatewayHandler) handleFailoverExhausted(c *gin.Context, failoverErr *service.UpstreamFailoverError, streamStarted bool) {
if failoverErr == nil {
h.handleFailoverExhaustedSimple(c, http.StatusBadGateway, streamStarted)
return
}
copyFailoverRetryAfter(c, failoverErr.ResponseHeaders)
if failoverErr.IsCredentialFailure() {
status, message := credentialFailoverClientResponse(failoverErr)
h.handleStreamingAwareError(c, status, "upstream_error", message, streamStarted)
return
}
statusCode := failoverErr.StatusCode
responseBody := failoverErr.ResponseBody
if service.IsOpenAISilentRefusalErrorBody(responseBody) {
@@ -1987,6 +2124,41 @@ func (h *OpenAIGatewayHandler) handleFailoverExhausted(c *gin.Context, failoverE
h.handleStreamingAwareError(c, status, errType, errMsg, streamStarted)
}
func credentialFailoverClientResponse(failoverErr *service.UpstreamFailoverError) (int, string) {
_ = failoverErr
return http.StatusServiceUnavailable, service.GrokCredentialUnavailableClientMessage
}
func copyFailoverRetryAfter(c *gin.Context, headers http.Header) {
if c == nil || headers == nil {
return
}
retryAfter := strings.TrimSpace(headers.Get("Retry-After"))
if retryAfter == "" || len(retryAfter) > 128 || strings.ContainsAny(retryAfter, "\r\n") || !isSafeRetryAfter(retryAfter) {
return
}
c.Header("Retry-After", retryAfter)
}
func isSafeRetryAfter(value string) bool {
digitsOnly := true
for _, char := range value {
if char < '0' || char > '9' {
digitsOnly = false
break
}
}
if digitsOnly {
seconds, err := strconv.ParseUint(value, 10, 32)
return err == nil && seconds <= uint64((7*24*time.Hour)/time.Second)
}
retryAt, err := http.ParseTime(value)
if err != nil {
return false
}
return !retryAt.After(time.Now().Add(7 * 24 * time.Hour))
}
// handleFailoverExhaustedSimple 简化版本,用于没有响应体的情况
func (h *OpenAIGatewayHandler) handleFailoverExhaustedSimple(c *gin.Context, statusCode int, streamStarted bool) {
status, errType, errMsg := h.mapUpstreamError(statusCode)
@@ -2051,13 +2223,23 @@ func (h *OpenAIGatewayHandler) ensureForwardErrorResponse(c *gin.Context, stream
return false
}
// 先停 compact 心跳再读 Writer 状态,避免与心跳 goroutine 竞争。
if service.StopOpenAICompactSSEKeepaliveCommitted(c) {
compactKeepaliveCommitted := service.StopOpenAICompactSSEKeepaliveCommitted(c)
if compactKeepaliveCommitted {
streamStarted = true
}
if service.IsResponseCommitted(c) {
imageKeepalivePresent := service.OpenAIImagesJSONKeepalivePresent(c)
service.StopOpenAIImagesJSONKeepaliveCommitted(c)
imageKeepalivePaddingOnly := false
imageKeepaliveResponseWritten := false
if imageKeepalivePresent {
adjustedSize := service.OpenAIImagesJSONKeepaliveAdjustedWrittenSize(c)
imageKeepalivePaddingOnly = adjustedSize < 0
imageKeepaliveResponseWritten = adjustedSize >= 0
}
if service.IsResponseCommitted(c) || (!compactKeepaliveCommitted && imageKeepaliveResponseWritten) {
return false
}
if c.Writer.Written() {
if c.Writer.Written() && !imageKeepalivePaddingOnly {
streamStarted = true
}
h.handleStreamingAwareError(c, http.StatusBadGateway, "upstream_error", "Upstream request failed", streamStarted)
@@ -2116,6 +2298,34 @@ func openAIForwardErrorAlreadyCommunicated(c *gin.Context, writerSizeBeforeForwa
return false
}
func openAIForwardMayFailover(c *gin.Context, writerSizeBeforeForward int, failoverErr *service.UpstreamFailoverError) bool {
if c == nil || c.Writer == nil {
return false
}
if service.OpenAICompactKeepaliveAdjustedWrittenSize(c) == writerSizeBeforeForward {
return true
}
return failoverErr != nil && failoverErr.SafeToFailoverAfterWrite
}
func openAIRequestAllowsFailoverReplay(c *gin.Context) bool {
if c == nil || c.Request == nil {
return false
}
return !failoverClientGone(c)
}
func openAIFirstOutputFailoverExhausted(failoverErr *service.UpstreamFailoverError, switchCount *int) bool {
if failoverErr == nil || !failoverErr.SafeToFailoverAfterWrite || switchCount == nil {
return false
}
if *switchCount >= maxOpenAIFirstOutputTimeoutSwitches {
return true
}
*switchCount = *switchCount + 1
return false
}
// errorResponse returns OpenAI API format error response
func (h *OpenAIGatewayHandler) errorResponse(c *gin.Context, status int, errType, message string) {
// body-signal compact 心跳可能已把响应头提交为 200:JSON 错误体会与已
@@ -2194,6 +2404,10 @@ func closeOpenAIWSFailoverExhausted(conn *coderws.Conn, failoverErr *service.Ups
closeOpenAIClientWS(conn, coderws.StatusInternalError, "upstream websocket proxy failed")
return
}
if failoverErr.Stage == service.GatewayFailureStageAccountAuth {
closeOpenAIClientWS(conn, coderws.StatusTryAgainLater, service.GrokCredentialUnavailableClientMessage)
return
}
switch failoverErr.StatusCode {
case http.StatusTooManyRequests:
closeOpenAIClientWS(conn, coderws.StatusTryAgainLater, "upstream rate limit exceeded, please retry later")
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"strings"
@@ -220,6 +221,97 @@ func TestOpenAIEnsureForwardErrorResponse_ResponsesRouteAfterWrittenEmitsRespons
assert.Contains(t, body, "Upstream request failed")
}
func TestOpenAIEnsureForwardErrorResponse_ImageJSONKeepaliveWritesSingleJSONFallback(t *testing.T) {
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodPost, "/v1/images/generations", nil)
stop := service.StartOpenAIImagesJSONKeepalive(c, 5*time.Millisecond)
defer stop()
before := service.OpenAIImagesJSONKeepaliveAdjustedWrittenSize(c)
require.Eventually(t, c.Writer.Written, time.Second, time.Millisecond)
require.Equal(t, before, service.OpenAIImagesJSONKeepaliveAdjustedWrittenSize(c))
require.False(t, openAIForwardErrorAlreadyCommunicated(c, before, errors.New("read upstream response: unexpected EOF")))
h := &OpenAIGatewayHandler{}
wrote := h.ensureForwardErrorResponse(c, false)
require.True(t, wrote)
require.Equal(t, http.StatusOK, w.Code, "heartbeat already committed the status")
require.True(t, json.Valid(w.Body.Bytes()), w.Body.String())
require.NotContains(t, w.Body.String(), "event:")
require.NotContains(t, w.Body.String(), "data:")
decoder := json.NewDecoder(strings.NewReader(w.Body.String()))
var payload map[string]any
require.NoError(t, decoder.Decode(&payload))
require.ErrorIs(t, decoder.Decode(&payload), io.EOF)
require.Equal(t, "upstream_error", gjson.Get(w.Body.String(), "error.type").String())
require.Equal(t, "Upstream request failed", gjson.Get(w.Body.String(), "error.message").String())
}
func TestOpenAIEnsureForwardErrorResponse_ImageJSONKeepalivePreservesCompletedJSON(t *testing.T) {
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodPost, "/v1/images/generations", nil)
stop := service.StartOpenAIImagesJSONKeepalive(c, 5*time.Millisecond)
defer stop()
before := service.OpenAIImagesJSONKeepaliveAdjustedWrittenSize(c)
require.Eventually(t, c.Writer.Written, time.Second, time.Millisecond)
c.JSON(http.StatusOK, gin.H{"data": []gin.H{{"b64_json": "aW1hZ2U="}}})
completedBody := w.Body.String()
require.True(t, json.Valid([]byte(completedBody)), completedBody)
require.Greater(t, service.OpenAIImagesJSONKeepaliveAdjustedWrittenSize(c), before)
require.False(t, openAIForwardErrorAlreadyCommunicated(c, before, errors.New("read upstream trailer: unexpected EOF")))
h := &OpenAIGatewayHandler{}
wrote := h.ensureForwardErrorResponse(c, false)
require.False(t, wrote, "the completed Images JSON already communicated the response")
require.Equal(t, completedBody, w.Body.String())
require.NotContains(t, w.Body.String(), "event:")
require.NotContains(t, w.Body.String(), "data:")
decoder := json.NewDecoder(strings.NewReader(w.Body.String()))
var payload map[string]any
require.NoError(t, decoder.Decode(&payload))
require.ErrorIs(t, decoder.Decode(&payload), io.EOF)
require.Equal(t, "aW1hZ2U=", gjson.Get(w.Body.String(), "data.0.b64_json").String())
}
func TestOpenAIEnsureForwardErrorResponse_FastImageJSONKeepalivePreservesCompletedJSON(t *testing.T) {
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodPost, "/v1/images/generations", nil)
stop := service.StartOpenAIImagesJSONKeepalive(c, time.Hour)
defer stop()
before := service.OpenAIImagesJSONKeepaliveAdjustedWrittenSize(c)
c.JSON(http.StatusOK, gin.H{"data": []gin.H{{"b64_json": "ZmFzdC1pbWFnZQ=="}}})
completedBody := w.Body.String()
require.True(t, json.Valid([]byte(completedBody)), completedBody)
require.Greater(t, service.OpenAIImagesJSONKeepaliveAdjustedWrittenSize(c), before)
require.False(t, openAIForwardErrorAlreadyCommunicated(c, before, errors.New("read upstream trailer: unexpected EOF")))
h := &OpenAIGatewayHandler{}
wrote := h.ensureForwardErrorResponse(c, false)
require.False(t, wrote, "fast completed Images JSON already communicated the response")
require.Equal(t, completedBody, w.Body.String())
require.NotContains(t, w.Body.String(), "event:")
require.NotContains(t, w.Body.String(), "data:")
decoder := json.NewDecoder(strings.NewReader(w.Body.String()))
var payload map[string]any
require.NoError(t, decoder.Decode(&payload))
require.ErrorIs(t, decoder.Decode(&payload), io.EOF)
require.Equal(t, "ZmFzdC1pbWFnZQ==", gjson.Get(w.Body.String(), "data.0.b64_json").String())
}
func TestShouldLogOpenAIForwardFailureAsWarn(t *testing.T) {
gin.SetMode(gin.TestMode)
@@ -741,6 +833,40 @@ func TestOpenAIResponsesWebSocket_IngressCapacityRejected(t *testing.T) {
require.Equal(t, coderws.StatusTryAgainLater, closeErr.Code)
}
func TestOpenAIResponsesWebSocket_FirstMessageTimeoutUsesConfig(t *testing.T) {
gin.SetMode(gin.TestMode)
logSink, restore := captureHandlerStructuredLog(t)
defer restore()
h := newOpenAIHandlerForPreviousResponseIDValidation(t, nil)
h.cfg = &config.Config{}
h.cfg.Gateway.OpenAIWS.ClientFirstMessageTimeoutSeconds = 1
wsServer := newOpenAIWSHandlerTestServer(t, h, middleware.AuthSubject{UserID: 1, Concurrency: 1})
defer wsServer.Close()
dialCtx, cancelDial := context.WithTimeout(context.Background(), 3*time.Second)
clientConn, _, err := coderws.Dial(dialCtx, "ws"+strings.TrimPrefix(wsServer.URL, "http")+"/openai/v1/responses", nil)
cancelDial()
require.NoError(t, err)
defer func() { _ = clientConn.CloseNow() }()
started := time.Now()
readCtx, cancelRead := context.WithTimeout(context.Background(), 5*time.Second)
_, _, err = clientConn.Read(readCtx)
cancelRead()
elapsed := time.Since(started)
require.Error(t, err)
require.NotErrorIs(t, err, context.DeadlineExceeded)
require.GreaterOrEqual(t, elapsed, 500*time.Millisecond)
require.Less(t, elapsed, 4*time.Second)
require.Eventually(t, func() bool {
readTimeout, ok := logSink.FieldValueForMessage("openai.websocket_read_first_message_failed", "read_timeout")
return ok && readTimeout == time.Second &&
logSink.ContainsMessageAtLevel("openai.websocket_read_first_message_failed", "warn")
}, time.Second, 10*time.Millisecond)
}
func TestOpenAIResponsesWebSocket_IngressLeaseReleasedOnEarlyReturn(t *testing.T) {
gin.SetMode(gin.TestMode)
cache := &concurrencyCacheMock{
@@ -1272,6 +1398,29 @@ type openAIWSFailoverHandlerAccountRepoStub struct {
rateLimitedIDs []int64
}
type openAIHTTPPassthroughFailoverUpstream struct {
service.HTTPUpstream
mu sync.Mutex
accountIDs []int64
}
func (u *openAIHTTPPassthroughFailoverUpstream) Do(_ *http.Request, _ string, accountID int64, _ int) (*http.Response, error) {
u.mu.Lock()
u.accountIDs = append(u.accountIDs, accountID)
u.mu.Unlock()
return &http.Response{
StatusCode: http.StatusBadGateway,
Header: http.Header{"Content-Type": []string{"application/json"}},
Body: io.NopCloser(strings.NewReader(`{"error":{"message":"temporary upstream failure"}}`)),
}, nil
}
func (u *openAIHTTPPassthroughFailoverUpstream) calls() []int64 {
u.mu.Lock()
defer u.mu.Unlock()
return append([]int64(nil), u.accountIDs...)
}
func (s *openAIWSFailoverHandlerAccountRepoStub) ListSchedulableByPlatform(ctx context.Context, platform string) ([]service.Account, error) {
out := make([]service.Account, 0, len(s.accounts))
for _, account := range s.accounts {
@@ -1344,6 +1493,96 @@ func (s *openAIWSUsageHandlerChannelRepoStub) GetGroupPlatforms(ctx context.Cont
return out, nil
}
func TestOpenAIResponses_APIKeyPassthroughPool5xxRetriesThenExhaustsMaxSwitches(t *testing.T) {
gin.SetMode(gin.TestMode)
groupID := int64(4203)
accounts := []service.Account{
{
ID: 9910, Name: "pool-api-key", Platform: service.PlatformOpenAI,
Type: service.AccountTypeAPIKey, Status: service.StatusActive, Schedulable: true, Priority: 1,
Credentials: map[string]any{
"api_key": "sk-pool",
"base_url": "https://api.example.test",
"pool_mode": true,
"pool_mode_retry_count": float64(1),
"pool_mode_retry_status_codes": []any{float64(http.StatusBadGateway)},
},
Extra: map[string]any{"openai_passthrough": true},
},
{
ID: 9911, Name: "fallback-api-key", Platform: service.PlatformOpenAI,
Type: service.AccountTypeAPIKey, Status: service.StatusActive, Schedulable: true, Priority: 2,
Credentials: map[string]any{
"api_key": "sk-fallback",
"base_url": "https://api.example.test",
},
Extra: map[string]any{"openai_passthrough": true},
},
}
cfg := &config.Config{RunMode: config.RunModeSimple}
cfg.Default.RateMultiplier = 1
cfg.Security.URLAllowlist.Enabled = false
cfg.Gateway.MaxAccountSwitches = 1
accountRepo := &openAIWSFailoverHandlerAccountRepoStub{accounts: accounts}
upstream := &openAIHTTPPassthroughFailoverUpstream{}
billingCacheSvc := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
t.Cleanup(billingCacheSvc.Stop)
gatewaySvc := service.NewOpenAIGatewayService(
accountRepo,
nil,
nil,
nil,
nil,
nil,
nil,
cfg,
nil,
nil,
service.NewBillingService(cfg, nil),
nil,
billingCacheSvc,
upstream,
&service.DeferredService{},
nil,
nil,
nil,
nil,
nil,
nil,
nil,
)
h := NewOpenAIGatewayHandler(
gatewaySvc,
service.NewConcurrencyService(nil),
billingCacheSvc,
service.NewAPIKeyService(nil, nil, nil, nil, nil, nil, cfg),
nil,
nil,
nil,
nil,
cfg,
)
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = httptest.NewRequest(http.MethodPost, "/openai/v1/responses", strings.NewReader(`{"model":"gpt-5.2","input":"hello","stream":false}`))
c.Request.Header.Set("Content-Type", "application/json")
c.Set(string(middleware.ContextKeyAPIKey), &service.APIKey{
ID: 1803, GroupID: &groupID,
User: &service.User{ID: 1703, Status: service.StatusActive},
Group: &service.Group{ID: groupID, Platform: service.PlatformOpenAI, Status: service.StatusActive},
})
c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 1703, Concurrency: 0})
h.Responses(c)
require.Equal(t, []int64{9910, 9910, 9911}, upstream.calls())
require.Equal(t, http.StatusBadGateway, rec.Code)
require.Equal(t, "upstream_error", gjson.GetBytes(rec.Body.Bytes(), "error.type").String())
require.Equal(t, "Upstream service temporarily unavailable", gjson.GetBytes(rec.Body.Bytes(), "error.message").String())
}
func TestOpenAIResponsesWebSocket_FailoverOnUpstreamUsageLimitEvent(t *testing.T) {
gin.SetMode(gin.TestMode)
@@ -0,0 +1,44 @@
package handler
import (
"testing"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
func TestSeedOpenAIForwardImageIntentHint(t *testing.T) {
gin.SetMode(gin.TestMode)
tests := []struct {
name string
channelMapped bool
imageIntent bool
wantHint bool
}{
{name: "seed true", imageIntent: true, wantHint: true},
{name: "seed false", imageIntent: false, wantHint: true},
{name: "mapped body stays unknown", channelMapped: true, imageIntent: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := &gin.Context{}
service.SetOpenAIClientTransport(c, service.OpenAIClientTransportHTTP)
seedOpenAIForwardImageIntentHint(c, tt.channelMapped, tt.imageIntent)
var hintValues []bool
for _, value := range c.Keys {
if hint, ok := value.(bool); ok {
hintValues = append(hintValues, hint)
}
}
if !tt.wantHint {
require.Empty(t, hintValues)
return
}
require.Equal(t, []bool{tt.imageIntent}, hintValues)
})
}
}
+13 -1
View File
@@ -145,6 +145,7 @@ func (h *OpenAIGatewayHandler) Images(c *gin.Context) {
stopJSONKeepalive := func() {}
jsonKeepaliveStarted := false
defer func() { stopJSONKeepalive() }()
var oauth429FailoverState service.OpenAIOAuth429FailoverState
for {
reqLog.Debug("openai.images.account_selecting", zap.Int("excluded_account_count", len(failedAccountIDs)))
@@ -157,6 +158,10 @@ func (h *OpenAIGatewayHandler) Images(c *gin.Context) {
parsed.RequiredCapability,
)
if err != nil {
if failoverClientGone(c) {
reqLog.Info("openai.images.account_select_aborted_client_disconnected", zap.Error(err))
return
}
reqLog.Warn("openai.images.account_select_failed",
zap.Error(err),
zap.Int("excluded_account_count", len(failedAccountIDs)),
@@ -273,6 +278,13 @@ func (h *OpenAIGatewayHandler) Images(c *gin.Context) {
h.handleFailoverExhausted(c, failoverErr, true)
return
}
if failoverClientGone(c) {
reqLog.Info("openai.images.failover_aborted_client_disconnected",
zap.Int64("account_id", account.ID),
zap.Int("upstream_status", failoverErr.StatusCode),
)
return
}
if failoverErr.RetryableOnSameAccount {
retryLimit := account.GetPoolModeRetryCount()
if sameAccountRetryCount[account.ID] < retryLimit {
@@ -299,7 +311,7 @@ func (h *OpenAIGatewayHandler) Images(c *gin.Context) {
return
}
switchCount++
if h.gatewayService.ShouldStopOpenAIOAuth429Failover(account, failoverErr.StatusCode, switchCount) {
if h.gatewayService.ShouldStopOpenAIOAuth429Failover(account, failoverErr.StatusCode, switchCount, &oauth429FailoverState) {
h.handleFailoverExhausted(c, failoverErr, streamStarted)
return
}
@@ -0,0 +1,194 @@
//go:build unit
package handler
import (
"bytes"
"context"
"io"
"net/http"
"net/http/httptest"
"sync"
"testing"
"github.com/Wei-Shaw/sub2api/internal/config"
middleware2 "github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
"github.com/tidwall/gjson"
)
// openAIResponsesFailoverCancelUpstream 固定返回 HTTP 520,可在首次上游调用时
// 触发回调(用于模拟“上游在途期间客户端断开”)。
type openAIResponsesFailoverCancelUpstream struct {
service.HTTPUpstream
mu sync.Mutex
accountIDs []int64
onFirstDo func()
}
func (u *openAIResponsesFailoverCancelUpstream) Do(_ *http.Request, _ string, accountID int64, _ int) (*http.Response, error) {
u.mu.Lock()
u.accountIDs = append(u.accountIDs, accountID)
first := len(u.accountIDs) == 1
u.mu.Unlock()
if first && u.onFirstDo != nil {
u.onFirstDo()
}
return &http.Response{
StatusCode: 520,
Header: http.Header{"Content-Type": []string{"text/html"}},
Body: io.NopCloser(bytes.NewBufferString("<html>520: unknown error</html>")),
}, nil
}
func (u *openAIResponsesFailoverCancelUpstream) calls() []int64 {
u.mu.Lock()
defer u.mu.Unlock()
return append([]int64(nil), u.accountIDs...)
}
func newOpenAIResponsesFailoverTestHandler(t *testing.T, upstream service.HTTPUpstream) *OpenAIGatewayHandler {
t.Helper()
accounts := []service.Account{
{
ID: 1,
Name: "responses-account-1",
Platform: service.PlatformOpenAI,
Type: service.AccountTypeOAuth,
Status: service.StatusActive,
Schedulable: true,
Concurrency: 0,
Priority: 0,
Credentials: map[string]any{"access_token": "token-1"},
},
{
ID: 2,
Name: "responses-account-2",
Platform: service.PlatformOpenAI,
Type: service.AccountTypeOAuth,
Status: service.StatusActive,
Schedulable: true,
Concurrency: 0,
Priority: 1,
Credentials: map[string]any{"access_token": "token-2"},
},
}
accountRepo := openAIImagesFailoverAccountRepo{accounts: accounts}
cfg := &config.Config{RunMode: config.RunModeSimple}
gatewayService := service.NewOpenAIGatewayService(
accountRepo,
nil,
nil,
nil,
nil,
nil,
nil,
cfg,
nil,
nil,
nil,
nil,
nil,
upstream,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
)
billingService := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
t.Cleanup(billingService.Stop)
concurrencyService := service.NewConcurrencyService(nil)
handler := NewOpenAIGatewayHandler(
gatewayService,
concurrencyService,
billingService,
service.NewAPIKeyService(nil, nil, nil, nil, nil, nil, cfg),
nil,
nil,
nil,
nil,
cfg,
)
handler.maxAccountSwitches = 10
return handler
}
func newOpenAIResponsesFailoverTestContext(t *testing.T, ctx context.Context) (*gin.Context, *httptest.ResponseRecorder) {
t.Helper()
groupID := int64(3131)
body := []byte(`{"model":"gpt-5.1","stream":false,"input":"hello"}`)
req := httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(body))
if ctx != nil {
req = req.WithContext(ctx)
}
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = req
c.Set(string(middleware2.ContextKeyAPIKey), &service.APIKey{
ID: 99,
GroupID: &groupID,
Group: &service.Group{
ID: groupID,
Platform: service.PlatformOpenAI,
},
User: &service.User{ID: 100},
})
c.Set(string(middleware2.ContextKeyUser), middleware2.AuthSubject{UserID: 100, Concurrency: 0})
return c, rec
}
// TestOpenAIGatewayHandlerResponses_FailoverAbortsWhenClientDisconnected 复现
// #4257:客户端在上游请求在途期间断开,上游随后返回可 failover 的 520。
// 期望:不再用已取消的 context 重新选号(不触达账号 2)、不把取消误报成
// 502 账号耗尽、请求按 499 归类。
func TestOpenAIGatewayHandlerResponses_FailoverAbortsWhenClientDisconnected(t *testing.T) {
gin.SetMode(gin.TestMode)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
upstream := &openAIResponsesFailoverCancelUpstream{onFirstDo: cancel}
handler := newOpenAIResponsesFailoverTestHandler(t, upstream)
c, rec := newOpenAIResponsesFailoverTestContext(t, ctx)
handler.Responses(c)
require.Equal(t, []int64{1}, upstream.calls(), "客户端断开后不应再切换到账号 2")
require.Equal(t, statusClientClosedRequest, c.Writer.Status(), "应按 499 归类")
require.Zero(t, rec.Body.Len(), "不应写入 502 错误响应体")
_, hasFinalUpstreamErr := c.Get(service.OpsUpstreamStatusCodeKey)
require.False(t, hasFinalUpstreamErr, "不应记录 failover 耗尽的上游错误终态")
// 真实发生过的 520 应保留 failover 事件(service 层在返回 failover 错误前记录)
rawEvents, ok := c.Get(service.OpsUpstreamErrorsKey)
require.True(t, ok)
events, ok := rawEvents.([]*service.OpsUpstreamErrorEvent)
require.True(t, ok)
require.Len(t, events, 1)
require.Equal(t, "failover", events[0].Kind)
require.Equal(t, 520, events[0].UpstreamStatusCode)
}
// TestOpenAIGatewayHandlerResponses_FailoverContinuesForConnectedClient 回归
// 守卫:客户端在线时 failover 行为不变——切换到账号 2,两个账号都 520 后按
// 耗尽返回 502。
func TestOpenAIGatewayHandlerResponses_FailoverContinuesForConnectedClient(t *testing.T) {
gin.SetMode(gin.TestMode)
upstream := &openAIResponsesFailoverCancelUpstream{}
handler := newOpenAIResponsesFailoverTestHandler(t, upstream)
c, rec := newOpenAIResponsesFailoverTestContext(t, nil)
handler.Responses(c)
require.Equal(t, []int64{1, 2}, upstream.calls(), "在线客户端应正常切换账号")
require.Equal(t, http.StatusBadGateway, rec.Code)
require.Equal(t, "upstream_error", gjson.GetBytes(rec.Body.Bytes(), "error.type").String())
}
+117 -65
View File
@@ -721,10 +721,15 @@ func OpsErrorLoggerMiddleware(ops *service.OpsService) gin.HandlerFunc {
var upstreamStatusCode *int
var upstreamErrorMessage *string
var upstreamErrorDetail *string
finalAccountAuth := false
if len(events) > 0 {
last := events[len(events)-1]
if last != nil {
if last.UpstreamStatusCode > 0 {
finalAccountAuth = last.Stage == string(service.GatewayFailureStageAccountAuth)
if finalAccountAuth {
code := 0
upstreamStatusCode = &code
} else if last.UpstreamStatusCode > 0 {
code := last.UpstreamStatusCode
upstreamStatusCode = &code
}
@@ -737,7 +742,7 @@ func OpsErrorLoggerMiddleware(ops *service.OpsService) gin.HandlerFunc {
}
}
if upstreamStatusCode == nil {
if !finalAccountAuth && upstreamStatusCode == nil {
if v, ok := c.Get(service.OpsUpstreamStatusCodeKey); ok {
switch t := v.(type) {
case int:
@@ -753,7 +758,7 @@ func OpsErrorLoggerMiddleware(ops *service.OpsService) gin.HandlerFunc {
}
}
}
if upstreamErrorMessage == nil {
if !finalAccountAuth && upstreamErrorMessage == nil {
if v, ok := c.Get(service.OpsUpstreamErrorMessageKey); ok {
if s, ok := v.(string); ok && strings.TrimSpace(s) != "" {
msg := strings.TrimSpace(s)
@@ -761,7 +766,7 @@ func OpsErrorLoggerMiddleware(ops *service.OpsService) gin.HandlerFunc {
}
}
}
if upstreamErrorDetail == nil {
if !finalAccountAuth && upstreamErrorDetail == nil {
if v, ok := c.Get(service.OpsUpstreamErrorDetailKey); ok {
if s, ok := v.(string); ok && strings.TrimSpace(s) != "" {
detail := strings.TrimSpace(s)
@@ -781,13 +786,18 @@ func OpsErrorLoggerMiddleware(ops *service.OpsService) gin.HandlerFunc {
}
recoveredMsg := "Recovered upstream error"
if effectiveUpstreamStatus > 0 {
if finalAccountAuth {
recoveredMsg = "Recovered account authentication failure"
} else if effectiveUpstreamStatus > 0 {
recoveredMsg += " " + strconvItoa(effectiveUpstreamStatus)
}
if upstreamErrorMessage != nil && strings.TrimSpace(*upstreamErrorMessage) != "" {
recoveredMsg += ": " + strings.TrimSpace(*upstreamErrorMessage)
}
recoveredMsg = truncateString(recoveredMsg, 2048)
recoveredPhase, recoveredBusinessLimited, recoveredOwner, recoveredSource := classifyOpsErrorLog(
c, "upstream_error", recoveredMsg, "", effectiveUpstreamStatus,
)
entry := &service.OpsInsertErrorLogInput{
RequestID: requestID,
@@ -828,19 +838,19 @@ func OpsErrorLoggerMiddleware(ops *service.OpsService) gin.HandlerFunc {
}(),
UserAgent: c.GetHeader("User-Agent"),
ErrorPhase: "upstream",
ErrorPhase: recoveredPhase,
ErrorType: "upstream_error",
// Severity should reflect the upstream failure, not the final client status (200).
Severity: classifyOpsSeverity("upstream_error", effectiveUpstreamStatus),
StatusCode: status,
IsBusinessLimited: false,
IsBusinessLimited: recoveredBusinessLimited,
IsCountTokens: isCountTokensRequest(c),
ErrorMessage: recoveredMsg,
ErrorBody: "",
ErrorSource: "upstream_http",
ErrorOwner: "provider",
ErrorSource: recoveredSource,
ErrorOwner: recoveredOwner,
UpstreamStatusCode: upstreamStatusCode,
UpstreamErrorMessage: upstreamErrorMessage,
@@ -850,6 +860,7 @@ func OpsErrorLoggerMiddleware(ops *service.OpsService) gin.HandlerFunc {
CreatedAt: time.Now(),
}
applyOpsLatencyFieldsFromContext(c, entry)
applyOpsUpstreamFieldsFromContext(c, entry)
if apiKey != nil {
entry.APIKeyID = &apiKey.ID
@@ -987,60 +998,7 @@ func OpsErrorLoggerMiddleware(ops *service.OpsService) gin.HandlerFunc {
CreatedAt: time.Now(),
}
applyOpsLatencyFieldsFromContext(c, entry)
// Capture upstream error context set by gateway services (if present).
// This does NOT affect the client response; it enriches Ops troubleshooting data.
{
if v, ok := c.Get(service.OpsUpstreamStatusCodeKey); ok {
switch t := v.(type) {
case int:
if t > 0 {
code := t
entry.UpstreamStatusCode = &code
}
case int64:
if t > 0 {
code := int(t)
entry.UpstreamStatusCode = &code
}
}
}
if v, ok := c.Get(service.OpsUpstreamErrorMessageKey); ok {
if s, ok := v.(string); ok {
if msg := strings.TrimSpace(s); msg != "" {
entry.UpstreamErrorMessage = &msg
}
}
}
if v, ok := c.Get(service.OpsUpstreamErrorDetailKey); ok {
if s, ok := v.(string); ok {
if detail := strings.TrimSpace(s); detail != "" {
entry.UpstreamErrorDetail = &detail
}
}
}
if v, ok := c.Get(service.OpsUpstreamErrorsKey); ok {
if events, ok := v.([]*service.OpsUpstreamErrorEvent); ok && len(events) > 0 {
entry.UpstreamErrors = events
// Best-effort backfill the single upstream fields from the last event when missing.
last := events[len(events)-1]
if last != nil {
if entry.UpstreamStatusCode == nil && last.UpstreamStatusCode > 0 {
code := last.UpstreamStatusCode
entry.UpstreamStatusCode = &code
}
if entry.UpstreamErrorMessage == nil && strings.TrimSpace(last.Message) != "" {
msg := strings.TrimSpace(last.Message)
entry.UpstreamErrorMessage = &msg
}
if entry.UpstreamErrorDetail == nil && strings.TrimSpace(last.Detail) != "" {
detail := strings.TrimSpace(last.Detail)
entry.UpstreamErrorDetail = &detail
}
}
}
}
}
applyOpsUpstreamFieldsFromContext(c, entry)
if apiKey != nil {
entry.APIKeyID = &apiKey.ID
@@ -1235,6 +1193,77 @@ func applyOpsLatencyFieldsFromContext(c *gin.Context, entry *service.OpsInsertEr
entry.TimeToFirstTokenMs = getContextLatencyMs(c, service.OpsTimeToFirstTokenMsKey)
}
// applyOpsUpstreamFieldsFromContext captures attempt-level upstream context.
// A final account_auth event owns the top-level status and forces it to zero;
// prior inference statuses remain available in UpstreamErrors.
func applyOpsUpstreamFieldsFromContext(c *gin.Context, entry *service.OpsInsertErrorLogInput) {
if c == nil || entry == nil {
return
}
if v, ok := c.Get(service.OpsUpstreamStatusCodeKey); ok {
switch t := v.(type) {
case int:
if t > 0 {
code := t
entry.UpstreamStatusCode = &code
}
case int64:
if t > 0 {
code := int(t)
entry.UpstreamStatusCode = &code
}
}
}
if v, ok := c.Get(service.OpsUpstreamErrorMessageKey); ok {
if value, ok := v.(string); ok {
if message := strings.TrimSpace(value); message != "" {
entry.UpstreamErrorMessage = &message
}
}
}
if v, ok := c.Get(service.OpsUpstreamErrorDetailKey); ok {
if value, ok := v.(string); ok {
if detail := strings.TrimSpace(value); detail != "" {
entry.UpstreamErrorDetail = &detail
}
}
}
if v, ok := c.Get(service.OpsUpstreamErrorsKey); ok {
if events, ok := v.([]*service.OpsUpstreamErrorEvent); ok && len(events) > 0 {
entry.UpstreamErrors = events
last := events[len(events)-1]
if last == nil {
return
}
if last.Stage == string(service.GatewayFailureStageAccountAuth) {
code := 0
entry.UpstreamStatusCode = &code
entry.UpstreamErrorMessage = nil
if message := strings.TrimSpace(last.Message); message != "" {
entry.UpstreamErrorMessage = &message
}
entry.UpstreamErrorDetail = nil
if detail := strings.TrimSpace(last.Detail); detail != "" {
entry.UpstreamErrorDetail = &detail
}
} else {
if entry.UpstreamStatusCode == nil && last.UpstreamStatusCode > 0 {
code := last.UpstreamStatusCode
entry.UpstreamStatusCode = &code
}
if entry.UpstreamErrorMessage == nil && strings.TrimSpace(last.Message) != "" {
message := strings.TrimSpace(last.Message)
entry.UpstreamErrorMessage = &message
}
if entry.UpstreamErrorDetail == nil && strings.TrimSpace(last.Detail) != "" {
detail := strings.TrimSpace(last.Detail)
entry.UpstreamErrorDetail = &detail
}
}
}
}
}
func getContextLatencyMs(c *gin.Context, key string) *int64 {
if c == nil || strings.TrimSpace(key) == "" {
return nil
@@ -1390,7 +1419,7 @@ func normalizeOpsErrorType(errType string, code string) string {
func classifyOpsPhase(errType, message, code string) string {
msg := strings.ToLower(message)
// Standardized phases: request|auth|routing|upstream|network|internal
// Standardized phases: request|auth|account_auth|routing|upstream|network|internal
// Map billing/concurrency/response => request; scheduling => routing.
if isOpsClientAuthError(code, msg) {
return "auth"
@@ -1445,7 +1474,10 @@ func classifyOpsErrorLog(c *gin.Context, errType, message, code string, status i
routingCapacityLimited := isOpsRoutingCapacityLimited(c)
clientBusinessLimited := service.HasOpsClientBusinessLimited(c)
upstreamError := hasOpsUpstreamErrorContext(c)
if upstreamError && !routingCapacityLimited {
accountAuthFailure := hasOpsAccountAuthFailure(c)
if accountAuthFailure && !routingCapacityLimited {
phase = "account_auth"
} else if upstreamError && !routingCapacityLimited {
phase = "upstream"
}
if clientBusinessLimited && !upstreamError && !routingCapacityLimited {
@@ -1570,6 +1602,22 @@ func hasOpsUpstreamErrorContext(c *gin.Context) bool {
return false
}
func hasOpsAccountAuthFailure(c *gin.Context) bool {
if c == nil {
return false
}
if v, ok := c.Get(service.OpsUpstreamErrorsKey); ok {
if events, ok := v.([]*service.OpsUpstreamErrorEvent); ok {
for i := len(events) - 1; i >= 0; i-- {
if events[i] != nil {
return events[i].Stage == string(service.GatewayFailureStageAccountAuth)
}
}
}
}
return false
}
func isOpsNoAvailableAccountMessage(message string) bool {
msg := strings.ToLower(message)
return strings.Contains(msg, opsErrNoAvailableAccounts) ||
@@ -1584,6 +1632,8 @@ func classifyOpsErrorOwner(phase string, message string) string {
switch phase {
case "upstream", "network":
return "provider"
case "account_auth":
return "provider"
case "request", "auth":
return "client"
case "routing", "internal":
@@ -1601,6 +1651,8 @@ func classifyOpsErrorSource(phase string, message string) string {
switch phase {
case "upstream":
return "upstream_http"
case "account_auth":
return "gateway"
case "network":
return "gateway"
case "request", "auth":
@@ -211,8 +211,8 @@ func FinalizeAnthropicResponsesStream(state *AnthropicEventToResponsesState) []R
// Close any open item
events = append(events, closeCurrentResponsesItem(state)...)
// Emit response.completed
events = append(events, makeResponsesCompletedEvent(state, "completed", nil))
status, incompleteDetails := anthropicResponsesStreamTerminalState(state.StopReason)
events = append(events, makeResponsesCompletedEvent(state, status, incompleteDetails))
state.CompletedSent = true
return events
}
@@ -434,13 +434,7 @@ func anthToResHandleMessageStop(state *AnthropicEventToResponsesState) []Respons
var events []ResponsesStreamEvent
events = append(events, closeCurrentResponsesItem(state)...)
status := "completed"
var incompleteDetails *ResponsesIncompleteDetails
if state.StopReason == "max_tokens" {
status = "incomplete"
incompleteDetails = &ResponsesIncompleteDetails{Reason: "max_output_tokens"}
}
status, incompleteDetails := anthropicResponsesStreamTerminalState(state.StopReason)
events = append(events, makeResponsesCompletedEvent(state, status, incompleteDetails))
state.CompletedSent = true
return events
@@ -448,6 +442,13 @@ func anthToResHandleMessageStop(state *AnthropicEventToResponsesState) []Respons
// --- helper functions ---
func anthropicResponsesStreamTerminalState(stopReason string) (string, *ResponsesIncompleteDetails) {
if stopReason == "max_tokens" {
return "incomplete", &ResponsesIncompleteDetails{Reason: "max_output_tokens"}
}
return "completed", nil
}
func closeCurrentResponsesItem(state *AnthropicEventToResponsesState) []ResponsesStreamEvent {
if state.CurrentItemType == "" {
return nil
@@ -0,0 +1,927 @@
package apicompat
import (
"encoding/json"
"fmt"
"sort"
"strings"
"time"
)
// This file implements a DIRECT bridge between Anthropic Messages and OpenAI
// Chat Completions, skipping the Responses API intermediate representation.
//
// The existing chat-fallback path (forwardAnthropicViaRawChatCompletions) chains
// two Responses-anchored bridges — Anthropic→Responses→ChatCompletions on the
// request side and CC→Responses→Anthropic on the response side — so every
// streaming token runs through two state machines. For force-chat accounts
// (third-party OpenAI-compatible upstreams that only speak /v1/chat/completions)
// the Responses layer is pure overhead: these upstreams never see Responses
// semantics, and the clients reaching them via /v1/messages use standard
// function tools (no custom/tool_search/namespace Codex constructs).
//
// The direct bridge collapses both directions into a single conversion each:
//
// Request: Anthropic Messages → Chat Completions
// Response: CC chunk/response → Anthropic events/response
//
// Helper functions from the Responses bridges (anthropicImageToDataURI,
// extractAnthropicTextFromBlocks, fromResponsesCallID, sanitizeAnthropicToolUseInput,
// parseAnthropicSystemContentParts, isReasoningModel, mapAnthropicEffortToResponses,
// normalizeToolParameters) are reused so the conversion semantics stay identical.
// ---------------------------------------------------------------------------
// Request: AnthropicRequest → ChatCompletionsRequest
// ---------------------------------------------------------------------------
// AnthropicToChatCompletionsRequest converts an Anthropic Messages request
// directly into a Chat Completions request, without transiting the Responses
// API. It is semantically equivalent to composing AnthropicToResponses +
// ResponsesToChatCompletionsRequest but avoids materializing the intermediate
// ResponsesRequest and the extra marshal/unmarshal cycle.
func AnthropicToChatCompletionsRequest(req *AnthropicRequest) (*ChatCompletionsRequest, error) {
if req == nil {
return nil, fmt.Errorf("anthropic request is nil")
}
messages, err := anthropicToChatMessages(req.System, req.Messages)
if err != nil {
return nil, err
}
out := &ChatCompletionsRequest{
Model: req.Model,
Messages: messages,
Stream: req.Stream,
}
// Sampling params: reasoning models (gpt-5.x) reject temperature/top_p.
if !isReasoningModel(req.Model) {
out.Temperature = req.Temperature
out.TopP = req.TopP
}
if req.MaxTokens > 0 {
v := req.MaxTokens
if v < minMaxOutputTokens {
v = minMaxOutputTokens
}
out.MaxCompletionTokens = &v
}
// Tools: Anthropic input_schema is a JSON Schema, directly usable as Chat
// function parameters. Server tools (web_search_*) have no Chat Completions
// equivalent and are dropped (mirrors responsesToolsToChatTools).
if len(req.Tools) > 0 {
tools := anthropicToolsToChatTools(req.Tools)
if len(tools) > 0 {
out.Tools = tools
}
}
// tool_choice is only forwarded when tools survived the conversion
// (upstream rejects tool_choice without tools), and a named choice only when
// it points at a declared tool — mirroring responsesToolChoiceToChatToolChoice,
// chat upstreams 400 on tool_choice referencing an unknown tool.
if len(out.Tools) > 0 && len(req.ToolChoice) > 0 {
declared := make(map[string]bool, len(out.Tools))
for _, tool := range out.Tools {
if tool.Function != nil {
declared[tool.Function.Name] = true
}
}
tc, err := convertAnthropicToolChoiceToChat(req.ToolChoice, declared)
if err != nil {
return nil, fmt.Errorf("convert tool_choice: %w", err)
}
if len(tc) > 0 {
out.ToolChoice = tc
}
}
// Reasoning effort: output_config.effort maps 1:1 (max→xhigh). thinking.type
// itself is ignored (the Responses bridge behaves identically).
effort := "medium"
if req.OutputConfig != nil && req.OutputConfig.Effort != "" {
effort = req.OutputConfig.Effort
}
out.ReasoningEffort = mapAnthropicEffortToResponses(effort)
parallelToolCalls := true
out.ParallelToolCalls = &parallelToolCalls
return out, nil
}
// anthropicToChatMessages converts the Anthropic system field + message list
// into Chat Completions messages. It mirrors convertAnthropicToResponsesInput +
// responsesInputToChatMessages but produces ChatMessage directly.
func anthropicToChatMessages(system json.RawMessage, msgs []AnthropicMessage) ([]ChatMessage, error) {
var messages []ChatMessage
// System prompt → system message. parseAnthropicSystemContentParts handles
// both string and []block forms and filters the billing header.
if len(system) > 0 {
sysParts, err := parseAnthropicSystemContentParts(system)
if err != nil {
return nil, err
}
if len(sysParts) > 0 {
text := joinResponsesContentPartText(sysParts)
if text != "" {
content, _ := json.Marshal(text)
messages = append(messages, ChatMessage{Role: "system", Content: content})
}
}
}
for _, m := range msgs {
converted, err := anthropicMsgToChatMessages(m)
if err != nil {
return nil, err
}
messages = append(messages, converted...)
}
return normalizeChatMessages(messages), nil
}
// anthropicMsgToChatMessages converts one Anthropic message into one or more
// Chat messages. tool_result blocks become standalone "tool" role messages
// (the Chat Completions convention); text/image blocks stay in a user message;
// assistant tool_use blocks become tool_calls on the assistant message.
func anthropicMsgToChatMessages(m AnthropicMessage) ([]ChatMessage, error) {
switch m.Role {
case "assistant":
return anthropicAssistantToChatMessages(m.Content)
default: // "user" and any unknown role
return anthropicUserToChatMessages(m.Content)
}
}
// anthropicUserToChatMessages handles an Anthropic user message. Content may be
// a plain string or an array of blocks. tool_result blocks are extracted into
// standalone "tool" role messages; images inside tool_results are lifted into a
// follow-up user message as image_url parts (the Responses bridge does the same
// — function_call_output only accepts strings, so images must travel separately).
func anthropicUserToChatMessages(raw json.RawMessage) ([]ChatMessage, error) {
// Plain string → single user message.
var s string
if err := json.Unmarshal(raw, &s); err == nil {
content, _ := json.Marshal(s)
return []ChatMessage{{Role: "user", Content: content}}, nil
}
var blocks []AnthropicContentBlock
if err := json.Unmarshal(raw, &blocks); err != nil {
return nil, err
}
var out []ChatMessage
var toolResultImageParts []ChatContentPart
// tool_result → "tool" role messages, text extracted; images deferred.
for _, b := range blocks {
if b.Type != "tool_result" {
continue
}
text, imageParts := convertToolResultOutput(b)
content, _ := json.Marshal(text)
out = append(out, ChatMessage{
Role: "tool",
Content: content,
ToolCallID: b.ToolUseID,
})
for _, ip := range imageParts {
toolResultImageParts = append(toolResultImageParts, ChatContentPart{
Type: "image_url",
ImageURL: &ChatImageURL{URL: ip.ImageURL},
})
}
}
// Remaining text + image blocks → user message. The double-conversion path
// (responsesContentPartsToChatContent) folds text-only content into a single
// string joined with "\n\n" and only uses the parts-array form when an image
// is present — strict chat upstreams reject array content — so the direct
// bridge preserves that folding.
var textParts []string
var parts []ChatContentPart
hasImage := false
for _, b := range blocks {
switch b.Type {
case "text":
if b.Text != "" {
textParts = append(textParts, b.Text)
parts = append(parts, ChatContentPart{Type: "text", Text: b.Text})
}
case "image":
if uri := anthropicImageToDataURI(b.Source); uri != "" {
hasImage = true
parts = append(parts, ChatContentPart{
Type: "image_url",
ImageURL: &ChatImageURL{URL: uri},
})
}
}
}
if len(toolResultImageParts) > 0 {
hasImage = true
parts = append(parts, toolResultImageParts...)
}
if !hasImage {
if len(textParts) > 0 {
content, _ := json.Marshal(strings.Join(textParts, "\n\n"))
out = append(out, ChatMessage{Role: "user", Content: content})
}
return out, nil
}
content, err := json.Marshal(parts)
if err != nil {
return nil, err
}
out = append(out, ChatMessage{Role: "user", Content: content})
return out, nil
}
// anthropicAssistantToChatMessages handles an Anthropic assistant message.
// Text content → assistant message content; tool_use blocks → tool_calls on the
// same assistant message; thinking blocks are dropped (Chat Completions has no
// inbound thinking field, matching anthropicAssistantToResponses).
func anthropicAssistantToChatMessages(raw json.RawMessage) ([]ChatMessage, error) {
// Plain string → single assistant message.
var s string
if err := json.Unmarshal(raw, &s); err == nil {
content, _ := json.Marshal(s)
return []ChatMessage{{Role: "assistant", Content: content}}, nil
}
var blocks []AnthropicContentBlock
if err := json.Unmarshal(raw, &blocks); err != nil {
return nil, err
}
msg := ChatMessage{Role: "assistant"}
text := extractAnthropicTextFromBlocks(blocks)
if text != "" {
content, _ := json.Marshal(text)
msg.Content = content
}
for _, b := range blocks {
if b.Type != "tool_use" {
continue
}
args := "{}"
if len(b.Input) > 0 {
args = string(b.Input)
}
msg.ToolCalls = append(msg.ToolCalls, ChatToolCall{
ID: b.ID,
Type: "function",
Function: ChatFunctionCall{
Name: b.Name,
Arguments: args,
},
})
}
return []ChatMessage{msg}, nil
}
// anthropicToolsToChatTools maps Anthropic tool definitions to Chat Completions
// function tools. Server-side tools (web_search_*) are dropped — they have no
// Chat Completions equivalent.
func anthropicToolsToChatTools(tools []AnthropicTool) []ChatTool {
var out []ChatTool
for _, t := range tools {
if strings.HasPrefix(t.Type, "web_search") {
continue
}
out = append(out, ChatTool{
Type: "function",
Function: &ChatFunction{
Name: t.Name,
Description: t.Description,
Parameters: normalizeToolParameters(t.InputSchema),
Strict: boolPtr(false),
},
})
}
return out
}
// convertAnthropicToolChoiceToChat maps Anthropic tool_choice to Chat
// Completions tool_choice. A nil result means the choice is dropped: like the
// double-conversion path (responsesToolChoiceToChatToolChoice), a named choice
// pointing at an undeclared tool or an unknown choice type is not forwarded,
// because chat upstreams reject it.
//
// {"type":"auto"} → "auto"
// {"type":"any"} → "required"
// {"type":"none"} → "none"
// {"type":"tool","name":"X"} → {"type":"function","function":{"name":"X"}} (X declared)
func convertAnthropicToolChoiceToChat(raw json.RawMessage, declared map[string]bool) (json.RawMessage, error) {
var tc struct {
Type string `json:"type"`
Name string `json:"name"`
}
if err := json.Unmarshal(raw, &tc); err != nil {
return nil, err
}
switch tc.Type {
case "auto":
return json.Marshal("auto")
case "any":
return json.Marshal("required")
case "none":
return json.Marshal("none")
case "tool":
if tc.Name == "" || !declared[tc.Name] {
return nil, nil
}
return json.Marshal(map[string]any{
"type": "function",
"function": map[string]string{"name": tc.Name},
})
default:
return nil, nil
}
}
// joinResponsesContentPartText concatenates the text of input_text parts. Used
// for the system prompt where parseAnthropicSystemContentParts returns
// ResponsesContentPart values.
func joinResponsesContentPartText(parts []ResponsesContentPart) string {
var texts []string
for _, p := range parts {
if p.Type == "input_text" && p.Text != "" {
texts = append(texts, p.Text)
}
}
return strings.Join(texts, "\n\n")
}
// ---------------------------------------------------------------------------
// Non-streaming response: ChatCompletionsResponse → AnthropicResponse
// ---------------------------------------------------------------------------
// ChatCompletionsResponseToAnthropic converts a Chat Completions response
// directly into an Anthropic Messages response, without materializing a
// ResponsesResponse. It is semantically equivalent to composing
// ChatCompletionsResponseToResponses + ResponsesToAnthropic.
func ChatCompletionsResponseToAnthropic(resp *ChatCompletionsResponse, model string) *AnthropicResponse {
out := &AnthropicResponse{
Type: "message",
Role: "assistant",
Model: model,
}
if resp != nil {
out.ID = resp.ID
if out.Model == "" {
out.Model = resp.Model
}
if len(resp.Choices) > 0 {
choice := resp.Choices[0]
out.Content = chatMessageToAnthropicBlocks(choice.Message)
out.StopReason = chatFinishReasonToAnthropicStopReason(choice.FinishReason, out.Content)
// "length" → "max_tokens" is handled by chatFinishReasonToAnthropicStopReason;
// Anthropic conveys max-tokens via stop_reason only, no incomplete_details field.
}
if resp.Usage != nil {
out.Usage = chatUsageToAnthropicUsage(resp.Usage)
}
}
if len(out.Content) == 0 {
out.Content = []AnthropicContentBlock{{Type: "text", Text: ""}}
}
// Empty choices / nil response never enter the choices branch above; the
// double-conversion path still reports a completed turn ("end_turn"), and
// stop_reason "" is invalid for strict Anthropic clients.
if out.StopReason == "" {
out.StopReason = chatFinishReasonToAnthropicStopReason("", out.Content)
}
// The double-conversion path generates a response id when the upstream
// omits one (ChatCompletionsResponseToResponses); clients treat it as required.
if out.ID == "" {
out.ID = generateResponsesID()
}
return out
}
// chatMessageToAnthropicBlocks converts a Chat Completions message into
// Anthropic content blocks. Reasoning content → thinking block; text content →
// text block; tool_calls → tool_use blocks. Mirrors chatMessageToResponsesOutput
// + the reasoning→thinking mapping in ResponsesToAnthropic.
func chatMessageToAnthropicBlocks(message ChatMessage) []AnthropicContentBlock {
var blocks []AnthropicContentBlock
if message.ReasoningContent != "" {
blocks = append(blocks, AnthropicContentBlock{
Type: "thinking",
Thinking: message.ReasoningContent,
})
}
text := chatMessageContentText(message.Content)
// DeepSeek reasoning-only fallback: when there is no text and no tool calls,
// surface the reasoning content as visible text so the turn isn't empty.
if text == "" && strings.TrimSpace(message.ReasoningContent) != "" && len(message.ToolCalls) == 0 {
text = message.ReasoningContent
}
if text != "" || len(message.ToolCalls) == 0 {
blocks = append(blocks, AnthropicContentBlock{Type: "text", Text: text})
}
for _, toolCall := range message.ToolCalls {
arguments := toolCall.Function.Arguments
if strings.TrimSpace(arguments) == "" {
arguments = "{}"
}
blocks = append(blocks, AnthropicContentBlock{
Type: "tool_use",
ID: fromResponsesCallID(toolCall.ID),
Name: toolCall.Function.Name,
Input: sanitizeAnthropicToolUseInput(toolCall.Function.Name, arguments),
})
}
return blocks
}
// chatFinishReasonToAnthropicStopReason maps Chat Completions finish_reason to
// Anthropic stop_reason.
//
// "length" → "max_tokens"
// "tool_calls" → "tool_use"
// other → "end_turn" (or "tool_use" if tool_use blocks present)
//
// "stop", "content_filter", and unknown reasons all map to a completed response
// in the double-conversion path, which then derives stop_reason from the blocks.
func chatFinishReasonToAnthropicStopReason(reason string, blocks []AnthropicContentBlock) string {
switch reason {
case "length":
return "max_tokens"
case "tool_calls":
return "tool_use"
default:
if containsAnthropicToolUseBlock(blocks) {
return "tool_use"
}
return "end_turn"
}
}
// chatUsageToAnthropicUsage converts Chat Completions token usage to Anthropic
// usage shape. Mirrors ChatUsageToResponsesUsage + anthropicUsageFromResponsesUsage.
func chatUsageToAnthropicUsage(usage *ChatUsage) AnthropicUsage {
if usage == nil {
return AnthropicUsage{}
}
cachedTokens := 0
cacheCreationTokens := 0
if usage.PromptTokensDetails != nil {
cachedTokens = usage.PromptTokensDetails.CachedTokens
// cache_write_tokens and cache_creation_tokens are alternate spellings of
// the same quantity, not additive; the double-conversion path
// (ChatUsageToResponsesUsage) prefers write and falls back to creation.
if usage.PromptTokensDetails.CacheWriteTokens > 0 {
cacheCreationTokens = usage.PromptTokensDetails.CacheWriteTokens
} else {
cacheCreationTokens = usage.PromptTokensDetails.CacheCreationTokens
}
}
inputTokens := usage.PromptTokens - cachedTokens - cacheCreationTokens
if inputTokens < 0 {
inputTokens = 0
}
return AnthropicUsage{
InputTokens: inputTokens,
OutputTokens: usage.CompletionTokens,
CacheReadInputTokens: cachedTokens,
CacheCreationInputTokens: cacheCreationTokens,
}
}
// ---------------------------------------------------------------------------
// Streaming: ChatCompletionsChunk → []AnthropicStreamEvent (stateful converter)
// ---------------------------------------------------------------------------
// ChatCompletionsToAnthropicStreamState tracks state while converting Chat
// Completions SSE chunks directly into Anthropic SSE events. It collapses the
// ChatCompletionsToResponsesStreamState + ResponsesEventToAnthropicState pair
// into one state machine.
type ChatCompletionsToAnthropicStreamState struct {
MessageStartSent bool
MessageStopSent bool
// Current content block lifecycle.
ContentBlockIndex int
ContentBlockOpen bool
CurrentBlockType string // "text" | "thinking" | "tool_use"
CurrentToolName string
CurrentToolHadDelta bool
HasToolCall bool
// Tool calls keyed by the upstream tool_call index. The Anthropic block
// index is assigned when the tool block is announced (content_block_start),
// which is deferred until the tool's name has arrived. Argument fragments
// and the call ID seen before the name are buffered and flushed with the
// announcement; tools whose name never arrives are announced with an empty
// name at finalize so their arguments are not lost.
toolBlockIndex map[int]int
toolAnnounced map[int]bool
toolName map[int]string
pendingToolCallID map[int]string
pendingToolArgs map[int]string
// Reasoning (DeepSeek-style): reasoning_content streamed before content.
// No separate reasoning block index — it uses ContentBlockIndex like the
// Responses bridge's ReasoningIndex, but since blocks are sequential we
// reuse the single ContentBlockIndex counter.
FinishReason string
InputTokens int
OutputTokens int
CacheReadInputTokens int
CacheCreationInputTokens int
ResponseID string
Model string
Created int64
}
// NewChatCompletionsToAnthropicStreamState returns an initialized stream state.
func NewChatCompletionsToAnthropicStreamState(model string) *ChatCompletionsToAnthropicStreamState {
return &ChatCompletionsToAnthropicStreamState{
ResponseID: generateResponsesID(),
Model: model,
Created: time.Now().Unix(),
toolBlockIndex: make(map[int]int),
toolAnnounced: make(map[int]bool),
toolName: make(map[int]string),
pendingToolCallID: make(map[int]string),
pendingToolArgs: make(map[int]string),
}
}
// ChatCompletionsChunkToAnthropicEvents converts one Chat Completions stream
// chunk into zero or more Anthropic stream events, updating state as it goes.
func ChatCompletionsChunkToAnthropicEvents(
chunk *ChatCompletionsChunk,
state *ChatCompletionsToAnthropicStreamState,
) []AnthropicStreamEvent {
if chunk == nil || state == nil {
return nil
}
if chunk.ID != "" {
state.ResponseID = chunk.ID
}
if state.Model == "" && chunk.Model != "" {
state.Model = chunk.Model
}
// Usage in a streaming chunk (include_usage) arrives in its own chunk,
// often with empty choices. Capture it for the finalize message_delta.
if chunk.Usage != nil {
u := chatUsageToAnthropicUsage(chunk.Usage)
state.InputTokens = u.InputTokens
state.OutputTokens = u.OutputTokens
state.CacheReadInputTokens = u.CacheReadInputTokens
state.CacheCreationInputTokens = u.CacheCreationInputTokens
}
var events []AnthropicStreamEvent
events = append(events, ensureCCAnthropicMessageStart(state)...)
for _, choice := range chunk.Choices {
// Reasoning content → thinking block.
if choice.Delta.ReasoningContent != nil && *choice.Delta.ReasoningContent != "" {
events = append(events, ensureCCAnthropicThinkingBlock(state)...)
events = append(events, ccAnthropicDelta(state, &AnthropicDelta{
Type: "thinking_delta",
Thinking: *choice.Delta.ReasoningContent,
})...)
}
// Text content → text block (closes any open thinking block first).
if choice.Delta.Content != nil && *choice.Delta.Content != "" {
events = append(events, closeCCAnthropicBlockIfOpen(state, "thinking")...)
events = append(events, ensureCCAnthropicTextBlock(state)...)
events = append(events, ccAnthropicDelta(state, &AnthropicDelta{
Type: "text_delta",
Text: *choice.Delta.Content,
})...)
}
// Tool calls → tool_use blocks.
for _, toolCall := range choice.Delta.ToolCalls {
events = append(events, closeCCAnthropicBlockIfOpen(state, "thinking")...)
events = append(events, handleCCAnthropicToolCall(state, &toolCall)...)
}
if choice.FinishReason != nil && *choice.FinishReason != "" {
state.FinishReason = *choice.FinishReason
}
}
return events
}
// FinalizeChatCompletionsAnthropicStream emits terminal Anthropic events
// (close open blocks + message_delta + message_stop) when the stream ends.
func FinalizeChatCompletionsAnthropicStream(state *ChatCompletionsToAnthropicStreamState) []AnthropicStreamEvent {
if state == nil || state.MessageStopSent {
return nil
}
var events []AnthropicStreamEvent
if !state.MessageStartSent {
events = append(events, ensureCCAnthropicMessageStart(state)...)
}
// Announce tools whose name never arrived so their buffered arguments are
// not silently dropped. The double-conversion path announced these
// immediately with an empty name; the deferred announcement keeps that data
// preservation while still delivering correct names when they do arrive.
if len(state.pendingToolCallID) > 0 {
idxs := make([]int, 0, len(state.pendingToolCallID))
for idx := range state.pendingToolCallID {
idxs = append(idxs, idx)
}
sort.Ints(idxs)
for _, idx := range idxs {
callID := state.pendingToolCallID[idx]
events = append(events, closeCCAnthropicBlock(state)...)
events = append(events, announceCCAnthropicToolBlock(state, idx, callID, "")...)
}
}
events = append(events, closeCCAnthropicBlock(state)...)
stopReason := ccFinishReasonToAnthropicStopReason(state.FinishReason, state.HasToolCall)
events = append(events,
AnthropicStreamEvent{
Type: "message_delta",
Delta: &AnthropicDelta{
StopReason: stopReason,
},
Usage: &AnthropicUsage{
InputTokens: state.InputTokens,
OutputTokens: state.OutputTokens,
CacheReadInputTokens: state.CacheReadInputTokens,
CacheCreationInputTokens: state.CacheCreationInputTokens,
},
},
AnthropicStreamEvent{Type: "message_stop"},
)
state.MessageStopSent = true
return events
}
// ensureCCAnthropicMessageStart emits message_start on the first event.
func ensureCCAnthropicMessageStart(state *ChatCompletionsToAnthropicStreamState) []AnthropicStreamEvent {
if state.MessageStartSent {
return nil
}
state.MessageStartSent = true
return []AnthropicStreamEvent{{
Type: "message_start",
Message: &AnthropicResponse{
ID: state.ResponseID,
Type: "message",
Role: "assistant",
Content: []AnthropicContentBlock{},
Model: state.Model,
Usage: AnthropicUsage{InputTokens: 0, OutputTokens: 0},
},
}}
}
// ensureCCAnthropicThinkingBlock opens a thinking block if none is open.
func ensureCCAnthropicThinkingBlock(state *ChatCompletionsToAnthropicStreamState) []AnthropicStreamEvent {
if state.ContentBlockOpen && state.CurrentBlockType == "thinking" {
return nil
}
events := closeCCAnthropicBlock(state)
idx := state.ContentBlockIndex
state.ContentBlockOpen = true
state.CurrentBlockType = "thinking"
events = append(events, AnthropicStreamEvent{
Type: "content_block_start",
Index: &idx,
ContentBlock: &AnthropicContentBlock{
Type: "thinking",
Thinking: "",
},
})
return events
}
// ensureCCAnthropicTextBlock opens a text block if none is open.
func ensureCCAnthropicTextBlock(state *ChatCompletionsToAnthropicStreamState) []AnthropicStreamEvent {
if state.ContentBlockOpen && state.CurrentBlockType == "text" {
return nil
}
events := closeCCAnthropicBlock(state)
idx := state.ContentBlockIndex
state.ContentBlockOpen = true
state.CurrentBlockType = "text"
events = append(events, AnthropicStreamEvent{
Type: "content_block_start",
Index: &idx,
ContentBlock: &AnthropicContentBlock{
Type: "text",
Text: "",
},
})
return events
}
// handleCCAnthropicToolCall processes one upstream tool_call delta. The
// content_block_start for a tool is deferred until its name has arrived (some
// upstreams stream id/arguments before the name); argument fragments seen
// before the announcement are buffered and flushed with it, later fragments
// stream as input_json_delta on the tool's block.
func handleCCAnthropicToolCall(state *ChatCompletionsToAnthropicStreamState, toolCall *ChatToolCall) []AnthropicStreamEvent {
idx := 0
if toolCall.Index != nil {
idx = *toolCall.Index
}
var events []AnthropicStreamEvent
if _, seen := state.toolAnnounced[idx]; !seen {
// New tool call: it ends whatever block is currently streaming.
events = append(events, closeCCAnthropicBlock(state)...)
state.HasToolCall = true
callID := toolCall.ID
if callID == "" {
callID = generateItemID()
}
if name := toolCall.Function.Name; name != "" {
events = append(events, announceCCAnthropicToolBlock(state, idx, callID, name)...)
} else {
state.toolAnnounced[idx] = false
state.pendingToolCallID[idx] = callID
}
} else if !state.toolAnnounced[idx] && toolCall.Function.Name != "" {
// Deferred announcement: the name has arrived.
callID := state.pendingToolCallID[idx]
if toolCall.ID != "" {
callID = toolCall.ID
}
events = append(events, closeCCAnthropicBlock(state)...)
events = append(events, announceCCAnthropicToolBlock(state, idx, callID, toolCall.Function.Name)...)
}
// Argument fragment → input_json_delta on the tool's block once announced,
// buffered until the deferred announcement otherwise.
if toolCall.Function.Arguments != "" {
if state.toolAnnounced[idx] {
blockIdx := state.toolBlockIndex[idx]
if state.ContentBlockOpen && blockIdx == state.ContentBlockIndex {
state.CurrentToolHadDelta = true
}
events = append(events, AnthropicStreamEvent{
Type: "content_block_delta",
Index: &blockIdx,
Delta: &AnthropicDelta{
Type: "input_json_delta",
PartialJSON: toolCall.Function.Arguments,
},
})
} else {
state.pendingToolArgs[idx] += toolCall.Function.Arguments
}
}
return events
}
// announceCCAnthropicToolBlock assigns the next Anthropic block index to the
// tool, emits its content_block_start, and flushes any argument fragments
// buffered while the announcement was deferred.
func announceCCAnthropicToolBlock(state *ChatCompletionsToAnthropicStreamState, idx int, callID, name string) []AnthropicStreamEvent {
blockIdx := state.ContentBlockIndex
state.toolBlockIndex[idx] = blockIdx
state.toolAnnounced[idx] = true
state.toolName[idx] = name
state.CurrentToolName = name
state.CurrentToolHadDelta = false
state.ContentBlockOpen = true
state.CurrentBlockType = "tool_use"
delete(state.pendingToolCallID, idx)
events := []AnthropicStreamEvent{{
Type: "content_block_start",
Index: &blockIdx,
ContentBlock: &AnthropicContentBlock{
Type: "tool_use",
ID: fromResponsesCallID(callID),
Name: name,
Input: json.RawMessage("{}"),
},
}}
if pending := state.pendingToolArgs[idx]; pending != "" {
delete(state.pendingToolArgs, idx)
state.CurrentToolHadDelta = true
events = append(events, AnthropicStreamEvent{
Type: "content_block_delta",
Index: &blockIdx,
Delta: &AnthropicDelta{
Type: "input_json_delta",
PartialJSON: pending,
},
})
}
return events
}
// ccAnthropicDelta emits a content_block_delta on the current block.
func ccAnthropicDelta(state *ChatCompletionsToAnthropicStreamState, delta *AnthropicDelta) []AnthropicStreamEvent {
if !state.ContentBlockOpen {
return nil
}
idx := state.ContentBlockIndex
return []AnthropicStreamEvent{{
Type: "content_block_delta",
Index: &idx,
Delta: delta,
}}
}
// closeCCAnthropicBlockIfOpen closes the current block only if it matches the
// given type (used to close a thinking block before opening text/tool).
func closeCCAnthropicBlockIfOpen(state *ChatCompletionsToAnthropicStreamState, blockType string) []AnthropicStreamEvent {
if !state.ContentBlockOpen || state.CurrentBlockType != blockType {
return nil
}
return closeCCAnthropicBlock(state)
}
// closeCCAnthropicBlock closes the currently open content block. A tool_use
// block that streamed no argument delta gets a final input_json_delta "{}"
// first — the double-conversion path normalizes empty tool arguments to "{}",
// and some clients assemble tool input exclusively from deltas.
func closeCCAnthropicBlock(state *ChatCompletionsToAnthropicStreamState) []AnthropicStreamEvent {
if !state.ContentBlockOpen {
return nil
}
idx := state.ContentBlockIndex
var events []AnthropicStreamEvent
if state.CurrentBlockType == "tool_use" && !state.CurrentToolHadDelta {
events = append(events, AnthropicStreamEvent{
Type: "content_block_delta",
Index: &idx,
Delta: &AnthropicDelta{
Type: "input_json_delta",
PartialJSON: "{}",
},
})
}
state.ContentBlockOpen = false
state.ContentBlockIndex++
state.CurrentBlockType = ""
state.CurrentToolName = ""
state.CurrentToolHadDelta = false
return append(events, AnthropicStreamEvent{
Type: "content_block_stop",
Index: &idx,
})
}
// ccFinishReasonToAnthropicStopReason maps a Chat Completions finish_reason
// (captured during streaming) to an Anthropic stop_reason for message_delta.
func ccFinishReasonToAnthropicStopReason(reason string, hasToolCall bool) string {
switch reason {
case "length":
return "max_tokens"
case "tool_calls":
return "tool_use"
case "stop":
if hasToolCall {
return "tool_use"
}
return "end_turn"
default:
if hasToolCall {
return "tool_use"
}
return "end_turn"
}
}
File diff suppressed because it is too large. Load diff
@@ -91,16 +91,22 @@ func EffectiveResponsesTools(req *ResponsesRequest) ([]ResponsesTool, error) {
if len(raw) == 0 || raw[0] != '{' {
continue
}
var discriminator struct {
Type string `json:"type"`
}
if err := json.Unmarshal(raw, &discriminator); err != nil {
return nil, fmt.Errorf("parse responses additional tools item: %w", err)
}
if discriminator.Type != "additional_tools" {
continue
}
var item struct {
Type string `json:"type"`
Tools []ResponsesTool `json:"tools"`
}
if err := json.Unmarshal(raw, &item); err != nil {
return nil, fmt.Errorf("parse responses additional tools item: %w", err)
}
if item.Type == "additional_tools" {
tools = append(tools, item.Tools...)
}
tools = append(tools, item.Tools...)
}
return tools, nil
}
@@ -79,6 +79,31 @@ func TestEffectiveResponsesTools_SkipsStringInputItems(t *testing.T) {
assert.Equal(t, "exec", tools[0].Name)
}
func TestEffectiveResponsesTools_IgnoresMalformedToolsOnNonAdditionalItem(t *testing.T) {
req := &ResponsesRequest{
Input: json.RawMessage(`[
{"type":"message","role":"user","tools":"not-an-array","content":[{"type":"input_text","text":"hello"}]},
{"type":"additional_tools","tools":[{"type":"custom","name":"exec"}]}
]`),
}
tools, err := EffectiveResponsesTools(req)
require.NoError(t, err)
require.Len(t, tools, 1)
assert.Equal(t, "exec", tools[0].Name)
}
func TestEffectiveResponsesTools_RejectsMalformedAdditionalTools(t *testing.T) {
req := &ResponsesRequest{
Input: json.RawMessage(`[{"type":"additional_tools","tools":"not-an-array"}]`),
}
tools, err := EffectiveResponsesTools(req)
require.Error(t, err)
assert.Contains(t, err.Error(), "parse responses additional tools item")
assert.Empty(t, tools)
}
func TestResponsesToChatCompletionsRequest_DropsToolChoiceWhenNoConvertibleTools(t *testing.T) {
req := &ResponsesRequest{
Model: "glm-5.2",
@@ -413,6 +413,28 @@ func resToAnthHandleFuncArgsDelta(evt *ResponsesStreamEvent, state *ResponsesEve
return nil
}
if state.CurrentBlockType == "tool_use" && state.CurrentToolName == "Read" {
state.CurrentToolArgs += evt.Delta
if state.CurrentToolHadDelta || !json.Valid([]byte(state.CurrentToolArgs)) {
return nil
}
blockIdx, ok := state.OutputIndexToBlockIdx[evt.OutputIndex]
if !ok {
return nil
}
state.CurrentToolHadDelta = true
sanitized := sanitizeAnthropicToolUseInput(state.CurrentToolName, state.CurrentToolArgs)
return []AnthropicStreamEvent{{
Type: "content_block_delta",
Index: &blockIdx,
Delta: &AnthropicDelta{
Type: "input_json_delta",
PartialJSON: string(sanitized),
},
}}
}
if state.CurrentBlockType == "tool_use" {
state.CurrentToolHadDelta = true
}
@@ -433,6 +455,9 @@ func resToAnthHandleFuncArgsDelta(evt *ResponsesStreamEvent, state *ResponsesEve
}
func resToAnthHandleFuncArgsDone(evt *ResponsesStreamEvent, state *ResponsesEventToAnthropicState) []AnthropicStreamEvent {
if !state.ContentBlockOpen {
return nil
}
if state.CurrentBlockType != "tool_use" {
return resToAnthHandleBlockDone(state)
}
@@ -452,10 +477,20 @@ func resToAnthHandleFuncArgsDone(evt *ResponsesStreamEvent, state *ResponsesEven
raw = string(sanitized)
}
idx := state.ContentBlockIndex
// 从事件的 OutputIndex 解析正确的 block index,与 resToAnthHandleFuncArgsDelta 对齐
blockIdx, ok := state.OutputIndexToBlockIdx[evt.OutputIndex]
if !ok {
blockIdx = state.ContentBlockIndex
}
// 如果 block 已关闭(ContentBlockIndex 已越过它),说明 arguments 已通过 delta 流式发完,不再补发
if !state.ContentBlockOpen || blockIdx != state.ContentBlockIndex {
return nil
}
events := []AnthropicStreamEvent{{
Type: "content_block_delta",
Index: &idx,
Index: &blockIdx,
Delta: &AnthropicDelta{
Type: "input_json_delta",
PartialJSON: raw,
@@ -0,0 +1,277 @@
package apicompat
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func intPtr(v int) *int { return &v }
func strPtr(s string) *string { return &s }
// TestStreamingParallelToolUseNoGhostDelta reproduces the bug from issue #4193:
// when the CC→Responses→Anthropic bridge finalizes parallel tool calls whose
// arguments arrived packed in function_call_arguments.done (no prior delta),
// resToAnthHandleFuncArgsDone used state.ContentBlockIndex directly instead of
// looking up OutputIndexToBlockIdx. After the first tool's block was closed
// (ContentBlockIndex++), the second tool's .done emitted a content_block_delta
// on an index that was never content_block_start'ed — Claude Code reports
// "Content block not found".
//
// This test drives the full finalize path: CC chunks with two parallel
// tool_calls → ChatCompletionsChunkToResponsesEvents → FinalizeChatCompletionsResponsesStream
// → ResponsesEventToAnthropicEvents, and asserts every content_block_delta
// targets a block that was previously content_block_start'ed.
func TestStreamingParallelToolUseNoGhostDelta(t *testing.T) {
ccState := NewChatCompletionsToResponsesStreamState("glm-5.2")
anthropicState := NewResponsesEventToAnthropicState()
anthropicState.Model = "glm-5.2"
// Chunk 1: first tool_call arrives with id + name + packed arguments.
chatChunk1 := &ChatCompletionsChunk{
ID: "chatcmpl-1",
Model: "glm-5.2",
Choices: []ChatChunkChoice{{
Index: 0,
Delta: ChatDelta{
ToolCalls: []ChatToolCall{{
Index: intPtr(0),
ID: "call_weather",
Type: "function",
Function: ChatFunctionCall{
Name: "get_weather",
Arguments: `{"city":"Tokyo"}`,
},
}},
},
}},
}
// Chunk 2: second tool_call arrives with id + name + packed arguments.
chatChunk2 := &ChatCompletionsChunk{
ID: "chatcmpl-1",
Model: "glm-5.2",
Choices: []ChatChunkChoice{{
Index: 0,
Delta: ChatDelta{
ToolCalls: []ChatToolCall{{
Index: intPtr(1),
ID: "call_time",
Type: "function",
Function: ChatFunctionCall{
Name: "get_time",
Arguments: `{}`,
},
}},
},
}},
}
// Chunk 3: finish.
chatChunk3 := &ChatCompletionsChunk{
ID: "chatcmpl-1",
Model: "glm-5.2",
Choices: []ChatChunkChoice{{
Index: 0,
Delta: ChatDelta{},
FinishReason: strPtr("tool_calls"),
}},
}
// Feed chunks through the CC→Responses bridge, then through Responses→Anthropic.
var allAnthropicEvents []AnthropicStreamEvent
for _, chunk := range []*ChatCompletionsChunk{chatChunk1, chatChunk2, chatChunk3} {
responsesEvents := ChatCompletionsChunkToResponsesEvents(chunk, ccState)
for _, rEvent := range responsesEvents {
allAnthropicEvents = append(allAnthropicEvents, ResponsesEventToAnthropicEvents(&rEvent, anthropicState)...)
}
}
// Finalize: closeChatToolItems emits function_call_arguments.done for each tool.
finalResponsesEvents := FinalizeChatCompletionsResponsesStream(ccState)
for _, rEvent := range finalResponsesEvents {
allAnthropicEvents = append(allAnthropicEvents, ResponsesEventToAnthropicEvents(&rEvent, anthropicState)...)
}
// Build the set of block indices that were content_block_start'ed.
startedBlocks := make(map[int]string) // index → block type
for _, e := range allAnthropicEvents {
if e.Type == "content_block_start" && e.ContentBlock != nil {
startedBlocks[*e.Index] = e.ContentBlock.Type
}
}
// Assert: every content_block_delta targets a started block (no ghost deltas).
for _, e := range allAnthropicEvents {
if e.Type != "content_block_delta" || e.Index == nil {
continue
}
idx := *e.Index
_, ok := startedBlocks[idx]
require.Truef(t, ok,
"content_block_delta on index %d which was never content_block_start'ed (ghost delta bug #4193)", idx)
}
// Assert: every content_block_stop targets a started block.
for _, e := range allAnthropicEvents {
if e.Type != "content_block_stop" || e.Index == nil {
continue
}
idx := *e.Index
_, ok := startedBlocks[idx]
require.Truef(t, ok,
"content_block_stop on index %d which was never content_block_start'ed", idx)
}
// Assert: both tool_use blocks were opened.
var toolUseBlocks []int
for idx, blockType := range startedBlocks {
if blockType == "tool_use" {
toolUseBlocks = append(toolUseBlocks, idx)
}
}
assert.Len(t, toolUseBlocks, 2, "both parallel tool_use blocks should be opened")
// Assert: stop_reason is tool_use.
var sawMessageDelta bool
for _, e := range allAnthropicEvents {
if e.Type == "message_delta" {
sawMessageDelta = true
assert.Equal(t, "tool_use", e.Delta.StopReason)
}
}
assert.True(t, sawMessageDelta, "message_delta should be emitted")
}
// TestStreamingParallelToolUseSecondToolPackedArgsDone is a focused unit test
// for the exact bug: two tools, the first streams its arguments via deltas
// (CurrentToolHadDelta=true → closeCurrentBlock), the second has arguments
// packed only in .done (CurrentToolHadDelta=false). Before the fix, the second
// tool's .done emitted content_block_delta on state.ContentBlockIndex which
// had already been incremented past the second tool's block.
func TestStreamingParallelToolUseSecondToolPackedArgsDone(t *testing.T) {
state := NewResponsesEventToAnthropicState()
// response.created
ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{
Type: "response.created",
Response: &ResponsesResponse{ID: "resp_par", Model: "glm-5.2"},
}, state)
// Tool 1: output_item.added (index 0)
ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{
Type: "response.output_item.added",
OutputIndex: 0,
Item: &ResponsesOutput{Type: "function_call", CallID: "call_a", Name: "tool_a"},
}, state)
// Tool 1: arguments streamed via delta (CurrentToolHadDelta = true)
ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{
Type: "response.function_call_arguments.delta",
OutputIndex: 0,
Delta: `{"x":1}`,
}, state)
// Tool 1: arguments.done → CurrentToolHadDelta=true → closeCurrentBlock
// ContentBlockIndex goes from 0 → 1
eventsTool1Done := ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{
Type: "response.function_call_arguments.done",
OutputIndex: 0,
Arguments: `{"x":1}`,
}, state)
// Should only emit content_block_stop (delta already streamed)
for _, e := range eventsTool1Done {
assert.NotEqual(t, "content_block_delta", e.Type,
"tool 1 .done should not re-emit delta (args already streamed)")
}
// Tool 2: output_item.added (index 1) → opens block at ContentBlockIndex=1
ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{
Type: "response.output_item.added",
OutputIndex: 1,
Item: &ResponsesOutput{Type: "function_call", CallID: "call_b", Name: "tool_b"},
}, state)
// Tool 2: NO delta — arguments arrive packed in .done only.
// This is the exact scenario that triggered the ghost delta bug.
eventsTool2Done := ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{
Type: "response.function_call_arguments.done",
OutputIndex: 1,
Arguments: `{"y":2}`,
}, state)
// The fix ensures the delta targets index 1 (the tool 2 block), not
// state.ContentBlockIndex (which would be 1 before close, matching by
// luck in this 2-tool case, but wrong in 3+ tool cases or when the
// block is already closed).
//
// The critical assertion: the delta must be on index 1 and must be
// followed by content_block_stop on the same index.
var sawDelta, sawStop bool
var deltaIndex, stopIndex int
for _, e := range eventsTool2Done {
if e.Type == "content_block_delta" && e.Index != nil {
sawDelta = true
deltaIndex = *e.Index
assert.Equal(t, "input_json_delta", e.Delta.Type)
assert.Equal(t, `{"y":2}`, e.Delta.PartialJSON)
}
if e.Type == "content_block_stop" && e.Index != nil {
sawStop = true
stopIndex = *e.Index
}
}
assert.True(t, sawDelta, "tool 2 .done with packed args should emit content_block_delta")
assert.True(t, sawStop, "tool 2 .done should close the block")
assert.Equal(t, 1, deltaIndex, "delta must target the tool 2 block (index 1)")
assert.Equal(t, deltaIndex, stopIndex, "delta and stop must be on the same block")
}
// TestStreamingThreeParallelToolsAllPackedDone tests the most extreme case:
// three parallel tools, ALL with arguments packed in .done (no deltas at all).
// Before the fix, tool 2 and tool 3 would emit ghost deltas on wrong indices.
func TestStreamingThreeParallelToolsAllPackedDone(t *testing.T) {
state := NewResponsesEventToAnthropicState()
ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{
Type: "response.created",
Response: &ResponsesResponse{ID: "resp_3par", Model: "glm-5.2"},
}, state)
// Open three tool blocks at indices 0, 1, 2.
for i, name := range []string{"tool_a", "tool_b", "tool_c"} {
ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{
Type: "response.output_item.added",
OutputIndex: i,
Item: &ResponsesOutput{Type: "function_call", CallID: "call_" + name, Name: name},
}, state)
}
// Track started blocks.
started := map[int]bool{0: true, 1: true, 2: true}
// All three .done events with packed arguments (no prior delta).
for i, args := range []string{`{"a":1}`, `{"b":2}`, `{"c":3}`} {
events := ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{
Type: "response.function_call_arguments.done",
OutputIndex: i,
Arguments: args,
}, state)
for _, e := range events {
if e.Type == "content_block_delta" && e.Index != nil {
idx := *e.Index
require.Truef(t, started[idx],
"ghost delta: tool %d .done emitted content_block_delta on index %d (never started)", i, idx)
require.Equal(t, i, idx,
"tool %d .done delta should target its own block index %d, got %d", i, i, idx)
}
if e.Type == "content_block_stop" && e.Index != nil {
idx := *e.Index
require.Truef(t, started[idx],
"ghost stop: tool %d .done emitted content_block_stop on index %d (never started)", i, idx)
}
}
}
}
@@ -7,63 +7,93 @@ import (
"github.com/stretchr/testify/require"
)
func TestResToAnthFuncArgsDelta_ReadToolStreamsDeltas(t *testing.T) {
func TestResToAnthFuncArgsDelta_ReadToolWaitsForCompleteJSON(t *testing.T) {
state := NewResponsesEventToAnthropicState()
state.MessageStartSent = true
state.CurrentBlockType = "tool_use"
state.CurrentToolName = "Read"
state.OutputIndexToBlockIdx = map[int]int{0: 0}
evt := &ResponsesStreamEvent{
Type: "response.function_call_arguments.delta",
OutputIndex: 0,
Delta: `{"file_path":"/tmp/test.go"}`,
}
events := ResponsesEventToAnthropicEvents(evt, state)
require.Len(t, events, 1, "Read tool delta must produce content_block_delta")
assert.Equal(t, "content_block_delta", events[0].Type)
assert.Equal(t, "input_json_delta", events[0].Delta.Type)
assert.Equal(t, `{"file_path":"/tmp/test.go"}`, events[0].Delta.PartialJSON)
assert.True(t, state.CurrentToolHadDelta, "Read deltas should set CurrentToolHadDelta")
}
func TestResToAnthFuncArgsDelta_ReadToolWithoutDone(t *testing.T) {
state := NewResponsesEventToAnthropicState()
state.MessageStartSent = true
state.ContentBlockIndex = 0
state.ContentBlockOpen = true
state.CurrentBlockType = "tool_use"
state.CurrentToolName = "Read"
state.OutputIndexToBlockIdx = map[int]int{0: 0}
delta := &ResponsesStreamEvent{
events := ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{
Type: "response.function_call_arguments.delta",
OutputIndex: 0,
Delta: `{"file_path":"/tmp/test.go"}`,
}
events := ResponsesEventToAnthropicEvents(delta, state)
require.Len(t, events, 1, "delta should be streamed")
Delta: `{"file_path":"/tmp/te`,
}, state)
assert.Empty(t, events, "partial Read JSON must wait for sanitization")
assert.False(t, state.CurrentToolHadDelta)
completed := &ResponsesStreamEvent{
events = ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{
Type: "response.function_call_arguments.delta",
OutputIndex: 0,
Delta: `st.go","pages":""}`,
}, state)
require.Len(t, events, 1)
assert.Equal(t, "content_block_delta", events[0].Type)
assert.Equal(t, "input_json_delta", events[0].Delta.Type)
assert.JSONEq(t, `{"file_path":"/tmp/test.go"}`, events[0].Delta.PartialJSON)
assert.Equal(t, `{"file_path":"/tmp/test.go","pages":""}`, state.CurrentToolArgs)
assert.True(t, state.CurrentToolHadDelta)
events = ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{
Type: "response.function_call_arguments.done",
OutputIndex: 0,
Arguments: `{"file_path":"/tmp/test.go","pages":""}`,
}, state)
require.Len(t, events, 1)
assert.Equal(t, "content_block_stop", events[0].Type)
events = ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{
Type: "response.function_call_arguments.done",
OutputIndex: 0,
Arguments: `{"file_path":"/tmp/test.go","pages":""}`,
}, state)
assert.Empty(t, events, "duplicate done must be idempotent")
}
func TestResponsesEventToAnthropicEvents_ReadToolWithoutArgumentsDoneClosesOnCompleted(t *testing.T) {
state := NewResponsesEventToAnthropicState()
events := ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{
Type: "response.created",
Response: &ResponsesResponse{ID: "resp_read", Model: "gpt-5.5"},
}, state)
require.Len(t, events, 1)
assert.Equal(t, "message_start", events[0].Type)
events = ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{
Type: "response.output_item.added",
OutputIndex: 0,
Item: &ResponsesOutput{Type: "function_call", CallID: "call_read", Name: "Read"},
}, state)
require.Len(t, events, 1)
assert.Equal(t, "content_block_start", events[0].Type)
events = ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{
Type: "response.function_call_arguments.delta",
OutputIndex: 0,
Delta: `{"file_path":"/tmp/test.go","pages":""}`,
}, state)
require.Len(t, events, 1)
assert.Equal(t, "content_block_delta", events[0].Type)
assert.Equal(t, "input_json_delta", events[0].Delta.Type)
assert.JSONEq(t, `{"file_path":"/tmp/test.go"}`, events[0].Delta.PartialJSON)
events = ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{
Type: "response.completed",
Response: &ResponsesResponse{
Status: "completed",
},
}
events = ResponsesEventToAnthropicEvents(completed, state)
hasStop := false
for _, e := range events {
if e.Type == "content_block_stop" {
hasStop = true
}
}
assert.True(t, hasStop, "block should be closed even without .done event")
}, state)
require.Len(t, events, 3)
assert.Equal(t, "content_block_stop", events[0].Type)
assert.Equal(t, "message_delta", events[1].Type)
assert.Equal(t, "tool_use", events[1].Delta.StopReason)
assert.Equal(t, "message_stop", events[2].Type)
assert.Empty(t, FinalizeResponsesAnthropicStream(state), "terminal event already finalized the stream")
}
func TestResToAnthFuncArgsDelta_NonReadToolUnchanged(t *testing.T) {
func TestResToAnthFuncArgsDelta_NonReadToolStreamsPartialJSONImmediately(t *testing.T) {
state := NewResponsesEventToAnthropicState()
state.MessageStartSent = true
state.CurrentBlockType = "tool_use"
@@ -73,12 +103,13 @@ func TestResToAnthFuncArgsDelta_NonReadToolUnchanged(t *testing.T) {
evt := &ResponsesStreamEvent{
Type: "response.function_call_arguments.delta",
OutputIndex: 0,
Delta: `{"file_path":"/tmp/out.txt","content":"hello"}`,
Delta: `{"file_path":"/tmp/out`,
}
events := ResponsesEventToAnthropicEvents(evt, state)
require.Len(t, events, 1)
assert.Equal(t, "content_block_delta", events[0].Type)
assert.Equal(t, `{"file_path":"/tmp/out`, events[0].Delta.PartialJSON)
assert.True(t, state.CurrentToolHadDelta)
}
@@ -44,6 +44,29 @@ func TestAnthropicStreamingMaxTokens_MapsToIncomplete(t *testing.T) {
assert.Equal(t, "max_output_tokens", completed.Response.IncompleteDetails.Reason)
}
func TestAnthropicStreamingMaxTokens_FinalizeMapsToIncompleteWithoutMessageStop(t *testing.T) {
state := NewAnthropicEventToResponsesState()
AnthropicEventToResponsesEvents(&AnthropicStreamEvent{
Type: "message_start",
Message: &AnthropicResponse{ID: "msg_test", Model: "claude-opus-4-6", Role: "assistant"},
}, state)
AnthropicEventToResponsesEvents(&AnthropicStreamEvent{
Type: "message_delta",
Delta: &AnthropicDelta{StopReason: "max_tokens"},
Usage: &AnthropicUsage{OutputTokens: 4096},
}, state)
events := FinalizeAnthropicResponsesStream(state)
require.Len(t, events, 1)
assert.Equal(t, "response.incomplete", events[0].Type)
require.NotNil(t, events[0].Response)
assert.Equal(t, "incomplete", events[0].Response.Status)
require.NotNil(t, events[0].Response.IncompleteDetails)
assert.Equal(t, "max_output_tokens", events[0].Response.IncompleteDetails.Reason)
assert.Empty(t, FinalizeAnthropicResponsesStream(state), "repeated finalization must be idempotent")
}
func TestAnthropicStreamingEndTurn_MapsToCompleted(t *testing.T) {
state := NewAnthropicEventToResponsesState()
@@ -13,6 +13,7 @@ import (
const (
HeaderName = "Server-Timing"
AdminUIHeader = "X-Admin-UI-Request"
UserUIHeader = "X-User-UI-Request"
MetricDatabase = "db"
MetricRedis = "redis"
dependencyPrefix = "dep_"
+69 -9
View File
@@ -5,6 +5,7 @@ import (
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"net/url"
"os"
@@ -164,6 +165,24 @@ func ValidatedBaseURL(override string) (string, error) {
return ValidateBaseURL(EffectiveBaseURL(override))
}
// BaseURLValidator applies the caller's outbound URL trust policy before xAI
// endpoint paths are appended. The service layer uses this for API-key accounts
// so the global security.url_allowlist policy remains the single source of
// truth; OAuth callers keep using the strict trusted-host validator.
type BaseURLValidator func(string) (string, error)
func validatedBaseURLWithValidator(override string, validator BaseURLValidator) (string, error) {
if validator == nil {
return ValidatedBaseURL(override)
}
raw := EffectiveBaseURL(override)
validated, err := validator(raw)
if err != nil {
return "", err
}
return normalizeKnownBaseURLPath(validated)
}
type RuntimeSanityCheck struct {
Value string `json:"value"`
Valid bool `json:"valid"`
@@ -282,7 +301,16 @@ func ValidateTrustedBaseURL(raw string) (string, error) {
func normalizeKnownBaseURLPath(raw string) (string, error) {
parsed, err := url.Parse(raw)
if err != nil || parsed.Scheme == "" || parsed.Host == "" {
return "", fmt.Errorf("invalid url: %s", raw)
return "", errors.New("invalid base URL")
}
if parsed.User != nil {
return "", errors.New("base URL must not include userinfo")
}
if parsed.ForceQuery || parsed.RawQuery != "" {
return "", errors.New("base URL must not include a query")
}
if parsed.Fragment != "" {
return "", errors.New("base URL must not include a fragment")
}
path := strings.TrimRight(parsed.Path, "/")
if path == "" {
@@ -435,7 +463,11 @@ func ParseAuthorizationInput(raw string) AuthorizationInput {
}
func BuildResponsesURL(baseURL string) (string, error) {
validatedBaseURL, err := ValidatedBaseURL(baseURL)
return BuildResponsesURLWithValidator(baseURL, nil)
}
func BuildResponsesURLWithValidator(baseURL string, validator BaseURLValidator) (string, error) {
validatedBaseURL, err := validatedBaseURLWithValidator(baseURL, validator)
if err != nil {
return "", fmt.Errorf("invalid base url: %w", err)
}
@@ -443,7 +475,11 @@ func BuildResponsesURL(baseURL string) (string, error) {
}
func BuildChatCompletionsURL(baseURL string) (string, error) {
validatedBaseURL, err := ValidatedBaseURL(baseURL)
return BuildChatCompletionsURLWithValidator(baseURL, nil)
}
func BuildChatCompletionsURLWithValidator(baseURL string, validator BaseURLValidator) (string, error) {
validatedBaseURL, err := validatedBaseURLWithValidator(baseURL, validator)
if err != nil {
return "", fmt.Errorf("invalid base url: %w", err)
}
@@ -451,7 +487,11 @@ func BuildChatCompletionsURL(baseURL string) (string, error) {
}
func BuildImagesGenerationsURL(baseURL string) (string, error) {
validatedBaseURL, err := ValidatedBaseURL(baseURL)
return BuildImagesGenerationsURLWithValidator(baseURL, nil)
}
func BuildImagesGenerationsURLWithValidator(baseURL string, validator BaseURLValidator) (string, error) {
validatedBaseURL, err := validatedBaseURLWithValidator(baseURL, validator)
if err != nil {
return "", fmt.Errorf("invalid base url: %w", err)
}
@@ -459,7 +499,11 @@ func BuildImagesGenerationsURL(baseURL string) (string, error) {
}
func BuildImagesEditsURL(baseURL string) (string, error) {
validatedBaseURL, err := ValidatedBaseURL(baseURL)
return BuildImagesEditsURLWithValidator(baseURL, nil)
}
func BuildImagesEditsURLWithValidator(baseURL string, validator BaseURLValidator) (string, error) {
validatedBaseURL, err := validatedBaseURLWithValidator(baseURL, validator)
if err != nil {
return "", fmt.Errorf("invalid base url: %w", err)
}
@@ -467,7 +511,11 @@ func BuildImagesEditsURL(baseURL string) (string, error) {
}
func BuildVideosGenerationsURL(baseURL string) (string, error) {
validatedBaseURL, err := ValidatedBaseURL(baseURL)
return BuildVideosGenerationsURLWithValidator(baseURL, nil)
}
func BuildVideosGenerationsURLWithValidator(baseURL string, validator BaseURLValidator) (string, error) {
validatedBaseURL, err := validatedBaseURLWithValidator(baseURL, validator)
if err != nil {
return "", fmt.Errorf("invalid base url: %w", err)
}
@@ -475,7 +523,11 @@ func BuildVideosGenerationsURL(baseURL string) (string, error) {
}
func BuildVideosEditsURL(baseURL string) (string, error) {
validatedBaseURL, err := ValidatedBaseURL(baseURL)
return BuildVideosEditsURLWithValidator(baseURL, nil)
}
func BuildVideosEditsURLWithValidator(baseURL string, validator BaseURLValidator) (string, error) {
validatedBaseURL, err := validatedBaseURLWithValidator(baseURL, validator)
if err != nil {
return "", fmt.Errorf("invalid base url: %w", err)
}
@@ -483,7 +535,11 @@ func BuildVideosEditsURL(baseURL string) (string, error) {
}
func BuildVideosExtensionsURL(baseURL string) (string, error) {
validatedBaseURL, err := ValidatedBaseURL(baseURL)
return BuildVideosExtensionsURLWithValidator(baseURL, nil)
}
func BuildVideosExtensionsURLWithValidator(baseURL string, validator BaseURLValidator) (string, error) {
validatedBaseURL, err := validatedBaseURLWithValidator(baseURL, validator)
if err != nil {
return "", fmt.Errorf("invalid base url: %w", err)
}
@@ -491,7 +547,11 @@ func BuildVideosExtensionsURL(baseURL string) (string, error) {
}
func BuildVideoURL(baseURL, requestID string) (string, error) {
validatedBaseURL, err := ValidatedBaseURL(baseURL)
return BuildVideoURLWithValidator(baseURL, requestID, nil)
}
func BuildVideoURLWithValidator(baseURL, requestID string, validator BaseURLValidator) (string, error) {
validatedBaseURL, err := validatedBaseURLWithValidator(baseURL, validator)
if err != nil {
return "", fmt.Errorf("invalid base url: %w", err)
}
+48
View File
@@ -6,6 +6,7 @@ import (
"net/url"
"testing"
"github.com/Wei-Shaw/sub2api/internal/util/urlvalidator"
"github.com/stretchr/testify/require"
)
@@ -165,6 +166,53 @@ func TestValidateBaseURLAllowsPublicThirdPartyGrokAPI(t *testing.T) {
require.Error(t, err)
}
func TestValidateBaseURLsRejectEmptyQueryDelimiter(t *testing.T) {
_, err := ValidateBaseURL("https://grok.example.test/v1?")
require.Error(t, err)
_, err = ValidateTrustedBaseURL("https://api.x.ai/v1?")
require.Error(t, err)
}
func TestBuildResponsesURLWithValidatorUsesCallerPolicy(t *testing.T) {
validator := func(raw string) (string, error) {
return urlvalidator.ValidateURLFormat(raw, true)
}
target, err := BuildResponsesURLWithValidator("http://grok.example.test/v1/", validator)
require.NoError(t, err)
require.Equal(t, "http://grok.example.test/v1/responses", target)
}
func TestBuildResponsesURLPreservesUnsafeOverrideCustomPath(t *testing.T) {
t.Setenv(EnvAllowUnsafeURLOverrides, "true")
target, err := BuildResponsesURL("http://localhost:8080/custom")
require.NoError(t, err)
require.Equal(t, "http://localhost:8080/custom/responses", target)
}
func TestBuildResponsesURLWithValidatorRejectsBaseURLComponents(t *testing.T) {
permissive := func(raw string) (string, error) { return raw, nil }
tests := []struct {
name string
raw string
}{
{name: "userinfo", raw: "https://user:secret@grok.example.test/v1"},
{name: "query", raw: "https://grok.example.test/v1?token=secret"},
{name: "empty query delimiter", raw: "https://grok.example.test/v1?"},
{name: "fragment", raw: "https://grok.example.test/v1#secret"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := BuildResponsesURLWithValidator(tt.raw, permissive)
require.Error(t, err)
require.NotContains(t, err.Error(), "secret")
})
}
}
func TestValidateXAIURLsAllowUnsafeDevOverride(t *testing.T) {
t.Setenv(EnvAllowUnsafeURLOverrides, "true")
+535 -23
View File
@@ -73,6 +73,12 @@ func NewAccountRepository(client *dbent.Client, sqlDB *sql.DB, schedulerCache se
return newAccountRepositoryWithSQL(client, sqlDB, schedulerCache)
}
// NewAdminAccountRepository exposes the account repository's atomic duplication capability
// as an explicit dependency of the admin service.
func NewAdminAccountRepository(client *dbent.Client, sqlDB *sql.DB, schedulerCache service.SchedulerCache) service.AdminAccountRepository {
return newAccountRepositoryWithSQL(client, sqlDB, schedulerCache)
}
// newAccountRepositoryWithSQL 是内部构造函数,支持依赖注入 SQL 执行器。
// 这种设计便于单元测试时注入 mock 对象。
func newAccountRepositoryWithSQL(client *dbent.Client, sqlq sqlExecutor, schedulerCache service.SchedulerCache) *accountRepository {
@@ -80,11 +86,21 @@ func newAccountRepositoryWithSQL(client *dbent.Client, sqlq sqlExecutor, schedul
}
func (r *accountRepository) Create(ctx context.Context, account *service.Account) error {
if err := createAccountRecord(ctx, r.client, account); err != nil {
return err
}
if err := enqueueSchedulerOutbox(ctx, r.sql, service.SchedulerOutboxEventAccountChanged, &account.ID, nil, buildSchedulerGroupPayload(account.GroupIDs)); err != nil {
logger.LegacyPrintf("repository.account", "[SchedulerOutbox] enqueue account create failed: account=%d err=%v", account.ID, err)
}
return nil
}
func createAccountRecord(ctx context.Context, client *dbent.Client, account *service.Account) error {
if account == nil {
return service.ErrAccountNilInput
}
builder := r.client.Account.Create().
builder := client.Account.Create().
SetName(account.Name).
SetNillableNotes(account.Notes).
SetPlatform(account.Platform).
@@ -146,8 +162,58 @@ func (r *accountRepository) Create(ctx context.Context, account *service.Account
account.ID = created.ID
account.CreatedAt = created.CreatedAt
account.UpdatedAt = created.UpdatedAt
if err := enqueueSchedulerOutbox(ctx, r.sql, service.SchedulerOutboxEventAccountChanged, &account.ID, nil, buildSchedulerGroupPayload(account.GroupIDs)); err != nil {
logger.LegacyPrintf("repository.account", "[SchedulerOutbox] enqueue account create failed: account=%d err=%v", account.ID, err)
return nil
}
// CreateWithAccountGroups atomically persists an account, its exact per-group priorities,
// and the scheduler outbox event used to publish the new routing snapshot.
func (r *accountRepository) CreateWithAccountGroups(ctx context.Context, account *service.Account, groups []service.AccountGroup) error {
if account == nil {
return service.ErrAccountNilInput
}
tx, err := r.client.Tx(ctx)
if err != nil && !errors.Is(err, dbent.ErrTxStarted) {
return err
}
var txClient *dbent.Client
if err == nil {
defer func() { _ = tx.Rollback() }()
txClient = tx.Client()
} else {
// Reuse a caller-owned transaction when this repository is already transactional.
txClient = r.client
}
if err := createAccountRecord(ctx, txClient, account); err != nil {
return err
}
groupIDs := make([]int64, 0, len(groups))
if len(groups) > 0 {
builders := make([]*dbent.AccountGroupCreate, 0, len(groups))
for i := range groups {
groups[i].AccountID = account.ID
groupIDs = append(groupIDs, groups[i].GroupID)
builders = append(builders, txClient.AccountGroup.Create().
SetAccountID(account.ID).
SetGroupID(groups[i].GroupID).
SetPriority(groups[i].Priority),
)
}
if _, err := txClient.AccountGroup.CreateBulk(builders...).Save(ctx); err != nil {
return err
}
}
account.GroupIDs = groupIDs
account.AccountGroups = append([]service.AccountGroup(nil), groups...)
if err := enqueueSchedulerOutbox(ctx, txClient, service.SchedulerOutboxEventAccountChanged, &account.ID, nil, buildSchedulerGroupPayload(groupIDs)); err != nil {
return err
}
if tx != nil {
if err := tx.Commit(); err != nil {
return err
}
}
return nil
}
@@ -433,6 +499,9 @@ func (r *accountRepository) UpdateCredentials(ctx context.Context, id int64, cre
if err != nil {
return translatePersistenceError(err, service.ErrAccountNotFound, nil)
}
if err := enqueueSchedulerOutbox(ctx, r.sql, service.SchedulerOutboxEventAccountChanged, &id, nil, nil); err != nil {
logger.LegacyPrintf("repository.account", "[SchedulerOutbox] enqueue credentials update failed: account=%d err=%v", id, err)
}
r.syncSchedulerAccountSnapshot(ctx, id)
return nil
}
@@ -717,29 +786,55 @@ func (r *accountRepository) ListActive(ctx context.Context) ([]service.Account,
return r.accountsToService(ctx, accounts)
}
func (r *accountRepository) ListOAuthRefreshCandidates(ctx context.Context) ([]service.Account, error) {
func (r *accountRepository) ListOAuthRefreshCandidatePage(ctx context.Context, options service.OAuthRefreshPageOptions) (*service.OAuthRefreshCandidatePage, error) {
if r.sql == nil {
return nil, errors.New("account repository SQL executor not configured")
}
if len(options.Platforms) == 0 {
return nil, errors.New("oauth refresh candidate platforms cannot be empty")
}
if options.Limit <= 0 || options.Limit > 1000 {
return nil, errors.New("oauth refresh candidate page limit must be between 1 and 1000")
}
// (cond) IS NOT TRUE 把 NULL 和 FALSE 都视为"可被刷新"。直接写
// NOT (a AND b) 在 PG 三值逻辑下会把 a 或 b 为 NULL 的行(即绝大多数
// 健康账号:temp_unschedulable_until=NULL)也排除,导致后台 token
// 刷新工作器漏掉所有正常账号 → access_token 到期后请求开始 401。
rows, err := r.sql.QueryContext(ctx, `
query := `
SELECT id
FROM accounts
WHERE deleted_at IS NULL
AND status = 'active'
AND type IN ('oauth', 'setup-token')
AND platform IN ('anthropic', 'openai', 'gemini', 'antigravity')
AND platform = ANY($1)
AND id > $2`
if options.ActiveOnly {
query += `
AND status = 'active'`
}
if options.IncludeSetupToken {
query += `
AND type IN ('oauth', 'setup-token')`
} else {
query += `
AND type = 'oauth'`
}
if options.RequireRefreshToken {
query += `
AND credentials ? 'refresh_token'
AND btrim(credentials->>'refresh_token') <> ''
AND btrim(credentials->>'refresh_token') <> ''`
}
if options.ExcludeRetryCooldown {
query += `
AND (
temp_unschedulable_until > NOW()
AND temp_unschedulable_reason LIKE 'token refresh retry exhausted:%'
) IS NOT TRUE
ORDER BY priority ASC, id ASC
`)
) IS NOT TRUE`
}
query += `
ORDER BY id ASC
LIMIT $3`
rows, err := r.sql.QueryContext(ctx, query, pq.Array(options.Platforms), options.AfterID, options.Limit)
if err != nil {
return nil, err
}
@@ -757,20 +852,33 @@ func (r *accountRepository) ListOAuthRefreshCandidates(ctx context.Context) ([]s
return nil, err
}
if len(ids) == 0 {
return []service.Account{}, nil
return &service.OAuthRefreshCandidatePage{Accounts: []service.Account{}}, nil
}
accounts, err := r.GetByIDs(ctx, ids)
if err != nil {
return nil, err
}
out := make([]service.Account, 0, len(accounts))
accountsByID := make(map[int64]*service.Account, len(accounts))
for _, account := range accounts {
if account != nil {
accountsByID[account.ID] = account
}
}
out := make([]service.Account, 0, len(accounts))
for _, id := range ids {
if account := accountsByID[id]; account != nil {
out = append(out, *account)
}
}
return out, nil
page := &service.OAuthRefreshCandidatePage{
Accounts: out,
HasMore: len(ids) == options.Limit,
}
if len(ids) > 0 {
page.NextAfterID = ids[len(ids)-1]
}
return page, nil
}
func (r *accountRepository) ListByPlatform(ctx context.Context, platform string) ([]service.Account, error) {
@@ -859,6 +967,297 @@ func (r *accountRepository) SetError(ctx context.Context, id int64, errorMsg str
return nil
}
func (r *accountRepository) SetGrokCredentialErrorIfMatch(
ctx context.Context,
id int64,
snapshot service.GrokCredentialMutationSnapshot,
errorMsg string,
) (bool, error) {
result, err := r.sql.ExecContext(ctx, `
WITH updated AS (
UPDATE accounts AS a
SET status = $1,
error_message = $2,
schedulable = false,
updated_at = NOW()
WHERE a.id = $3
AND a.deleted_at IS NULL
AND a.status = $4
AND a.platform = $5
AND a.type = $6
AND a.schedulable IS TRUE
AND (a.temp_unschedulable_until IS NULL OR a.temp_unschedulable_until <= NOW())
AND (a.rate_limit_reset_at IS NULL OR a.rate_limit_reset_at <= NOW())
AND (a.overload_until IS NULL OR a.overload_until <= NOW())
AND (a.auto_pause_on_expired IS NOT TRUE OR a.expires_at IS NULL OR a.expires_at > NOW())
AND a.credentials = $7::jsonb
AND a.proxy_id IS NOT DISTINCT FROM $8
AND ($2 <> $9 OR (
a.proxy_id IS NOT NULL AND NOT EXISTS (
SELECT 1 FROM proxies p WHERE p.id = a.proxy_id AND p.deleted_at IS NULL
)
))
RETURNING a.id
)
INSERT INTO scheduler_outbox (event_type, account_id, group_id, payload)
SELECT $10, updated.id, NULL, NULL FROM updated
`, service.StatusError, errorMsg, id, service.StatusActive, service.PlatformGrok, service.AccountTypeOAuth,
snapshot.CredentialsJSON, snapshot.ProxyID, string(service.GrokCredentialReasonProxyInvalid),
service.SchedulerOutboxEventAccountChanged)
if err != nil {
return false, err
}
affected, err := result.RowsAffected()
if err != nil || affected == 0 {
return false, err
}
r.syncSchedulerAccountSnapshotDetached(ctx, id)
return true, nil
}
// SetGrokOAuthErrorIfCredentialsUnchanged atomically quarantines a structurally
// invalid Grok OAuth account only if it is still active and its complete JSONB
// credential document matches the state observed by reconciliation. Exact
// JSONB equality includes _token_version when present and prevents a concurrent
// reauthorization from being overwritten by a stale check-then-mutate path.
func (r *accountRepository) SetGrokOAuthErrorIfCredentialsUnchanged(
ctx context.Context,
id int64,
expectedCredentials map[string]any,
errorMsg string,
) (bool, error) {
if r == nil || r.sql == nil {
return false, errors.New("account repository SQL executor is not configured")
}
expectedJSON, err := json.Marshal(normalizeJSONMap(expectedCredentials))
if err != nil {
return false, err
}
result, err := r.sql.ExecContext(ctx, `
WITH updated AS (
UPDATE accounts AS a
SET status = $1,
error_message = $2,
schedulable = FALSE,
updated_at = NOW()
WHERE a.id = $3
AND a.deleted_at IS NULL
AND a.platform = $4
AND a.type = $5
AND a.status = $6
AND a.credentials = $7::jsonb
AND NULLIF(BTRIM(a.credentials->>'refresh_token'), '') IS NULL
RETURNING a.id
)
INSERT INTO scheduler_outbox (event_type, account_id, group_id, payload)
SELECT $8, updated.id, NULL, NULL FROM updated
`,
service.StatusError,
errorMsg,
id,
service.PlatformGrok,
service.AccountTypeOAuth,
service.StatusActive,
string(expectedJSON),
service.SchedulerOutboxEventAccountChanged,
)
if err != nil {
return false, err
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return false, err
}
if rowsAffected == 0 {
return false, nil
}
r.syncSchedulerAccountSnapshotDetached(ctx, id)
return true, nil
}
// UpdateGrokOAuthCredentialsIfUnchanged persists provider-issued replacement
// credentials only while the complete Grok OAuth credential document and
// proxy still match the fresh snapshot used by the upstream refresh call. The
// scheduler outbox insert is part of the same PostgreSQL statement, so a
// durable invalidation failure rolls the credential update back as well.
func (r *accountRepository) UpdateGrokOAuthCredentialsIfUnchanged(
ctx context.Context,
id int64,
expectedCredentials map[string]any,
expectedProxyID *int64,
credentials map[string]any,
) (bool, error) {
if r == nil || r.sql == nil {
return false, errors.New("account repository SQL executor is not configured")
}
expectedJSON, err := json.Marshal(normalizeJSONMap(expectedCredentials))
if err != nil {
return false, err
}
credentialsJSON, err := json.Marshal(normalizeJSONMap(credentials))
if err != nil {
return false, err
}
result, err := r.sql.ExecContext(ctx, `
WITH updated AS (
UPDATE accounts AS a
SET credentials = $1::jsonb,
updated_at = NOW()
WHERE a.id = $2
AND a.deleted_at IS NULL
AND a.platform = $3
AND a.type = $4
AND a.credentials = $5::jsonb
AND a.proxy_id IS NOT DISTINCT FROM $6
RETURNING a.id
)
INSERT INTO scheduler_outbox (event_type, account_id, group_id, payload)
SELECT $7, updated.id, NULL, NULL FROM updated
`,
string(credentialsJSON),
id,
service.PlatformGrok,
service.AccountTypeOAuth,
string(expectedJSON),
expectedProxyID,
service.SchedulerOutboxEventAccountChanged,
)
if err != nil {
return false, err
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return false, err
}
if rowsAffected == 0 {
return false, nil
}
r.syncSchedulerAccountSnapshotDetached(ctx, id)
return true, nil
}
// SetGrokOAuthRefreshErrorIfCredentialsUnchanged is the background-refresh
// counterpart to reconciliation's stricter missing-refresh-token mutation. It
// matches the complete credential document used by the failed upstream attempt
// but deliberately does not require the refresh token to be absent.
func (r *accountRepository) SetGrokOAuthRefreshErrorIfCredentialsUnchanged(
ctx context.Context,
id int64,
expectedCredentials map[string]any,
expectedProxyID *int64,
errorMsg string,
) (bool, error) {
if r == nil || r.sql == nil {
return false, errors.New("account repository SQL executor is not configured")
}
expectedJSON, err := json.Marshal(normalizeJSONMap(expectedCredentials))
if err != nil {
return false, err
}
result, err := r.sql.ExecContext(ctx, `
WITH updated AS (
UPDATE accounts AS a
SET status = $1,
error_message = $2,
schedulable = FALSE,
updated_at = NOW()
WHERE a.id = $3
AND a.deleted_at IS NULL
AND a.platform = $4
AND a.type = $5
AND a.status = $6
AND a.credentials = $7::jsonb
AND a.proxy_id IS NOT DISTINCT FROM $8
RETURNING a.id
)
INSERT INTO scheduler_outbox (event_type, account_id, group_id, payload)
SELECT $9, updated.id, NULL, NULL FROM updated
`,
service.StatusError,
errorMsg,
id,
service.PlatformGrok,
service.AccountTypeOAuth,
service.StatusActive,
string(expectedJSON),
expectedProxyID,
service.SchedulerOutboxEventAccountChanged,
)
if err != nil {
return false, err
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return false, err
}
if rowsAffected == 0 {
return false, nil
}
r.syncSchedulerAccountSnapshotDetached(ctx, id)
return true, nil
}
// SetGrokOAuthRefreshTempUnschedulableIfCredentialsUnchanged applies a bounded
// transient refresh quarantine only while the active Grok OAuth credential
// document still matches the exact upstream attempt.
func (r *accountRepository) SetGrokOAuthRefreshTempUnschedulableIfCredentialsUnchanged(
ctx context.Context,
id int64,
expectedCredentials map[string]any,
expectedProxyID *int64,
until time.Time,
reason string,
) (bool, error) {
if r == nil || r.sql == nil {
return false, errors.New("account repository SQL executor is not configured")
}
expectedJSON, err := json.Marshal(normalizeJSONMap(expectedCredentials))
if err != nil {
return false, err
}
result, err := r.sql.ExecContext(ctx, `
WITH updated AS (
UPDATE accounts AS a
SET temp_unschedulable_until = $1,
temp_unschedulable_reason = $2,
updated_at = NOW()
WHERE a.id = $3
AND a.deleted_at IS NULL
AND a.platform = $4
AND a.type = $5
AND a.status = $6
AND a.credentials = $7::jsonb
AND a.proxy_id IS NOT DISTINCT FROM $8
AND (a.temp_unschedulable_until IS NULL OR a.temp_unschedulable_until < $1)
RETURNING a.id
)
INSERT INTO scheduler_outbox (event_type, account_id, group_id, payload)
SELECT $9, updated.id, NULL, NULL FROM updated
`,
until,
reason,
id,
service.PlatformGrok,
service.AccountTypeOAuth,
service.StatusActive,
string(expectedJSON),
expectedProxyID,
service.SchedulerOutboxEventAccountChanged,
)
if err != nil {
return false, err
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return false, err
}
if rowsAffected == 0 {
return false, nil
}
r.syncSchedulerAccountSnapshotDetached(ctx, id)
return true, nil
}
// syncSchedulerAccountSnapshot 在账号状态变更时主动同步快照到调度器缓存。
// 当账号被设置为错误、禁用、不可调度或临时不可调度时调用,
// 确保调度器和粘性会话逻辑能及时感知账号的最新状态,避免继续使用不可用账号。
@@ -881,6 +1280,16 @@ func (r *accountRepository) syncSchedulerAccountSnapshot(ctx context.Context, ac
}
}
func (r *accountRepository) syncSchedulerAccountSnapshotDetached(ctx context.Context, accountID int64) {
base := context.Background()
if ctx != nil {
base = context.WithoutCancel(ctx)
}
propagationCtx, cancel := context.WithTimeout(base, 2*time.Second)
defer cancel()
r.syncSchedulerAccountSnapshot(propagationCtx, accountID)
}
func (r *accountRepository) deleteSchedulerAccountSnapshot(ctx context.Context, accountID int64) {
if r == nil || r.schedulerCache == nil || accountID <= 0 {
return
@@ -1050,8 +1459,42 @@ func (r *accountRepository) BindGroups(ctx context.Context, accountID int64, gro
}
func (r *accountRepository) ListSchedulable(ctx context.Context) ([]service.Account, error) {
now := time.Now()
accounts, err := r.client.Account.Query().
accounts, err := r.schedulableAccountsQuery(time.Now()).All(ctx)
if err != nil {
return nil, err
}
return r.accountsToService(ctx, accounts)
}
func (r *accountRepository) ListSchedulableAccountLoads(ctx context.Context) ([]service.AccountWithConcurrency, error) {
accounts, err := r.schedulableAccountsQuery(time.Now()).
Select(
dbaccount.FieldID,
dbaccount.FieldConcurrency,
dbaccount.FieldLoadFactor,
).
All(ctx)
if err != nil {
return nil, err
}
loads := make([]service.AccountWithConcurrency, 0, len(accounts))
for _, account := range accounts {
projection := service.Account{
ID: account.ID,
Concurrency: account.Concurrency,
LoadFactor: account.LoadFactor,
}
loads = append(loads, service.AccountWithConcurrency{
ID: account.ID,
MaxConcurrency: projection.EffectiveLoadFactor(),
})
}
return loads, nil
}
func (r *accountRepository) schedulableAccountsQuery(now time.Time) *dbent.AccountQuery {
return r.client.Account.Query().
Where(
dbaccount.StatusEQ(service.StatusActive),
dbaccount.SchedulableEQ(true),
@@ -1060,12 +1503,7 @@ func (r *accountRepository) ListSchedulable(ctx context.Context) ([]service.Acco
dbaccount.Or(dbaccount.OverloadUntilIsNil(), dbaccount.OverloadUntilLTE(now)),
dbaccount.Or(dbaccount.RateLimitResetAtIsNil(), dbaccount.RateLimitResetAtLTE(now)),
).
Order(dbent.Asc(dbaccount.FieldPriority)).
All(ctx)
if err != nil {
return nil, err
}
return r.accountsToService(ctx, accounts)
Order(dbent.Asc(dbaccount.FieldPriority))
}
func (r *accountRepository) ListSchedulableByGroupID(ctx context.Context, groupID int64) ([]service.Account, error) {
@@ -1319,6 +1757,35 @@ func (r *accountRepository) SetRateLimitedIfLater(ctx context.Context, id int64,
return nil
}
// ClearRateLimitIfObserved clears exactly the Grok rate-limit generation seen
// by a successful request. Matching both timestamps prevents a stale success
// from erasing a later clear/re-arm generation with an equal or shorter reset.
func (r *accountRepository) ClearRateLimitIfObserved(ctx context.Context, id int64, observedLimitedAt, observedResetAt time.Time) (bool, error) {
updated, err := r.client.Account.Update().
Where(
dbaccount.IDEQ(id),
dbaccount.PlatformEQ(service.PlatformGrok),
dbaccount.TypeEQ(service.AccountTypeOAuth),
dbaccount.RateLimitedAtEQ(observedLimitedAt),
dbaccount.RateLimitResetAtEQ(observedResetAt),
).
ClearRateLimitedAt().
ClearRateLimitResetAt().
Save(ctx)
if err != nil {
return false, err
}
if updated == 0 {
r.syncSchedulerAccountSnapshot(ctx, id)
return false, nil
}
if err := enqueueSchedulerOutbox(ctx, r.sql, service.SchedulerOutboxEventAccountChanged, &id, nil, nil); err != nil {
logger.LegacyPrintf("repository.account", "[SchedulerOutbox] enqueue observed rate-limit clear failed: account=%d err=%v", id, err)
}
r.syncSchedulerAccountSnapshot(ctx, id)
return true, nil
}
func (r *accountRepository) SetModelRateLimit(ctx context.Context, id int64, scope string, resetAt time.Time, reason ...string) error {
if scope == "" {
return nil
@@ -1414,6 +1881,51 @@ func (r *accountRepository) SetTempUnschedulable(ctx context.Context, id int64,
return nil
}
func (r *accountRepository) SetGrokCredentialTempUnschedulableIfMatch(
ctx context.Context,
id int64,
snapshot service.GrokCredentialMutationSnapshot,
until time.Time,
reason string,
) (bool, error) {
result, err := r.sql.ExecContext(ctx, `
WITH updated AS (
UPDATE accounts AS a
SET temp_unschedulable_until = CASE
WHEN a.temp_unschedulable_until IS NULL OR a.temp_unschedulable_until < $1 THEN $1
ELSE a.temp_unschedulable_until
END,
temp_unschedulable_reason = $2,
updated_at = NOW()
WHERE a.id = $3
AND a.deleted_at IS NULL
AND a.status = $4
AND a.platform = $5
AND a.type = $6
AND a.schedulable IS TRUE
AND (a.temp_unschedulable_until IS NULL OR a.temp_unschedulable_until <= NOW())
AND (a.rate_limit_reset_at IS NULL OR a.rate_limit_reset_at <= NOW())
AND (a.overload_until IS NULL OR a.overload_until <= NOW())
AND (a.auto_pause_on_expired IS NOT TRUE OR a.expires_at IS NULL OR a.expires_at > NOW())
AND a.credentials = $7::jsonb
AND a.proxy_id IS NOT DISTINCT FROM $8
RETURNING a.id
)
INSERT INTO scheduler_outbox (event_type, account_id, group_id, payload)
SELECT $9, updated.id, NULL, NULL FROM updated
`, until, reason, id, service.StatusActive, service.PlatformGrok, service.AccountTypeOAuth,
snapshot.CredentialsJSON, snapshot.ProxyID, service.SchedulerOutboxEventAccountChanged)
if err != nil {
return false, err
}
affected, err := result.RowsAffected()
if err != nil || affected == 0 {
return false, err
}
r.syncSchedulerAccountSnapshotDetached(ctx, id)
return true, nil
}
func (r *accountRepository) ClearTempUnschedulable(ctx context.Context, id int64) error {
_, err := r.sql.ExecContext(ctx, `
UPDATE accounts
@@ -0,0 +1,73 @@
//go:build integration
package repository
import (
"context"
"fmt"
"testing"
"time"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/stretchr/testify/require"
)
func TestCreateWithAccountGroupsPersistsPausedCopyAtomically(t *testing.T) {
ctx := context.Background()
client := testEntClient(t)
repo := newAccountRepositoryWithSQL(client, integrationDB, nil)
suffix := time.Now().UnixNano()
group, err := client.Group.Create().
SetName(fmt.Sprintf("duplicate-atomic-%d", suffix)).
SetPlatform(service.PlatformAnthropic).
Save(ctx)
require.NoError(t, err)
success := &service.Account{
Name: fmt.Sprintf("duplicate-success-%d", suffix),
Platform: service.PlatformAnthropic,
Type: service.AccountTypeAPIKey,
Status: service.StatusActive,
Schedulable: false,
Credentials: map[string]any{"api_key": "secret"},
Extra: map[string]any{},
}
require.NoError(t, repo.CreateWithAccountGroups(ctx, success, []service.AccountGroup{{GroupID: group.ID, Priority: 37}}))
t.Cleanup(func() {
_, _ = integrationDB.ExecContext(context.Background(), "DELETE FROM scheduler_outbox WHERE account_id = $1", success.ID)
_, _ = integrationDB.ExecContext(context.Background(), "DELETE FROM account_groups WHERE account_id = $1", success.ID)
_, _ = integrationDB.ExecContext(context.Background(), "DELETE FROM accounts WHERE id = $1", success.ID)
_, _ = integrationDB.ExecContext(context.Background(), "DELETE FROM groups WHERE id = $1", group.ID)
})
var schedulable bool
require.NoError(t, integrationDB.QueryRowContext(ctx, "SELECT schedulable FROM accounts WHERE id = $1", success.ID).Scan(&schedulable))
require.False(t, schedulable)
var priority int
require.NoError(t, integrationDB.QueryRowContext(ctx, "SELECT priority FROM account_groups WHERE account_id = $1 AND group_id = $2", success.ID, group.ID).Scan(&priority))
require.Equal(t, 37, priority)
var outboxCount int
require.NoError(t, integrationDB.QueryRowContext(ctx, "SELECT COUNT(*) FROM scheduler_outbox WHERE account_id = $1", success.ID).Scan(&outboxCount))
require.Equal(t, 1, outboxCount)
failure := &service.Account{
Name: fmt.Sprintf("duplicate-failure-%d", suffix),
Platform: service.PlatformAnthropic,
Type: service.AccountTypeAPIKey,
Status: service.StatusActive,
Schedulable: false,
Credentials: map[string]any{"api_key": "secret"},
Extra: map[string]any{},
}
err = repo.CreateWithAccountGroups(ctx, failure, []service.AccountGroup{{GroupID: int64(^uint64(0) >> 1), Priority: 1}})
require.Error(t, err)
var accountCount, groupCount, failedOutboxCount int
require.NoError(t, integrationDB.QueryRowContext(ctx, "SELECT COUNT(*) FROM accounts WHERE name = $1", failure.Name).Scan(&accountCount))
require.NoError(t, integrationDB.QueryRowContext(ctx, "SELECT COUNT(*) FROM account_groups WHERE account_id = $1", failure.ID).Scan(&groupCount))
require.NoError(t, integrationDB.QueryRowContext(ctx, "SELECT COUNT(*) FROM scheduler_outbox WHERE account_id = $1", failure.ID).Scan(&failedOutboxCount))
require.Zero(t, accountCount)
require.Zero(t, groupCount)
require.Zero(t, failedOutboxCount)
}
@@ -4,6 +4,8 @@ package repository
import (
"context"
"database/sql"
"strings"
"testing"
"time"
@@ -11,6 +13,7 @@ import (
"github.com/Wei-Shaw/sub2api/ent/accountgroup"
"github.com/Wei-Shaw/sub2api/internal/pkg/pagination"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
)
@@ -25,13 +28,34 @@ type schedulerCacheRecorder struct {
setAccounts []*service.Account
deleteIDs []int64
accounts map[int64]*service.Account
setCtxErr error
}
func (s *schedulerCacheRecorder) GetSnapshot(ctx context.Context, bucket service.SchedulerBucket) ([]*service.Account, bool, error) {
return nil, false, nil
}
func (s *schedulerCacheRecorder) SetSnapshot(ctx context.Context, bucket service.SchedulerBucket, accounts []service.Account) error {
func (s *schedulerCacheRecorder) CaptureBucketWriteToken(ctx context.Context, bucket service.SchedulerBucket) (service.SchedulerBucketWriteToken, error) {
return service.SchedulerBucketWriteToken{Bucket: bucket, Epoch: 1}, nil
}
func (s *schedulerCacheRecorder) SetSnapshot(ctx context.Context, bucket service.SchedulerBucket, token service.SchedulerBucketWriteToken, accounts []service.Account) error {
return nil
}
func (s *schedulerCacheRecorder) RetireBucket(ctx context.Context, bucket service.SchedulerBucket) error {
return nil
}
func (s *schedulerCacheRecorder) ReopenBucket(ctx context.Context, bucket service.SchedulerBucket) (service.SchedulerBucketWriteToken, error) {
return service.SchedulerBucketWriteToken{Bucket: bucket, Epoch: 1}, nil
}
func (s *schedulerCacheRecorder) TryAcquireGroupLifecycleLease(_ context.Context, groupID int64, _ time.Duration) (service.SchedulerGroupLifecycleLease, bool, error) {
return service.SchedulerGroupLifecycleLease{GroupID: groupID, OwnerToken: "scheduler-cache-recorder"}, true, nil
}
func (s *schedulerCacheRecorder) ReleaseGroupLifecycleLease(context.Context, service.SchedulerGroupLifecycleLease) error {
return nil
}
@@ -43,6 +67,7 @@ func (s *schedulerCacheRecorder) GetAccount(ctx context.Context, accountID int64
}
func (s *schedulerCacheRecorder) SetAccount(ctx context.Context, account *service.Account) error {
s.setCtxErr = ctx.Err()
s.setAccounts = append(s.setAccounts, account)
if s.accounts == nil {
s.accounts = make(map[int64]*service.Account)
@@ -53,6 +78,31 @@ func (s *schedulerCacheRecorder) SetAccount(ctx context.Context, account *servic
return nil
}
type failAtomicSchedulerOutboxSQLExecutor struct {
sqlExecutor
}
func (e *failAtomicSchedulerOutboxSQLExecutor) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error) {
if strings.Contains(query, "WITH updated AS") && strings.Contains(query, "INSERT INTO scheduler_outbox") && len(args) > 0 {
args = append([]any(nil), args...)
args[len(args)-1] = nil // event_type is NOT NULL; the whole statement must roll back.
}
return e.sqlExecutor.ExecContext(ctx, query, args...)
}
type cancelAfterAtomicMutationSQLExecutor struct {
sqlExecutor
cancel context.CancelFunc
}
func (e *cancelAfterAtomicMutationSQLExecutor) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error) {
result, err := e.sqlExecutor.ExecContext(ctx, query, args...)
if err == nil && strings.Contains(query, "WITH updated AS") && strings.Contains(query, "INSERT INTO scheduler_outbox") {
e.cancel()
}
return result, err
}
func (s *schedulerCacheRecorder) DeleteAccount(ctx context.Context, accountID int64) error {
s.deleteIDs = append(s.deleteIDs, accountID)
if s.accounts != nil {
@@ -180,6 +230,34 @@ func (s *AccountRepoSuite) TestUpdate_SyncSchedulerSnapshotOnCredentialsChange()
s.Require().Equal("gpt-5.2", mapping["gpt-5"])
}
func (s *AccountRepoSuite) TestUpdateCredentials_SyncsSnapshotAndDurableOutbox() {
account := mustCreateAccount(s.T(), s.client, &service.Account{
Name: "sync-refresh-credentials",
Status: service.StatusActive,
Schedulable: true,
Credentials: map[string]any{"access_token": "old-token"},
})
cacheRecorder := &schedulerCacheRecorder{}
s.repo.schedulerCache = cacheRecorder
_, err := s.repo.sql.ExecContext(s.ctx, "TRUNCATE scheduler_outbox")
s.Require().NoError(err)
s.Require().NoError(s.repo.UpdateCredentials(s.ctx, account.ID, map[string]any{"access_token": "new-token"}))
s.Require().Len(cacheRecorder.setAccounts, 1)
s.Require().Equal("new-token", cacheRecorder.setAccounts[0].GetCredential("access_token"))
var outboxCount int
err = scanSingleRow(
s.ctx,
s.repo.sql,
"SELECT COUNT(*) FROM scheduler_outbox WHERE event_type = $1 AND account_id = $2",
[]any{service.SchedulerOutboxEventAccountChanged, account.ID},
&outboxCount,
)
s.Require().NoError(err)
s.Require().Equal(1, outboxCount)
}
func (s *AccountRepoSuite) TestDelete() {
account := mustCreateAccount(s.T(), s.client, &service.Account{Name: "to-delete"})
@@ -236,6 +314,88 @@ func (s *AccountRepoSuite) TestList() {
s.Require().Equal(int64(2), page.Total)
}
func (s *AccountRepoSuite) TestListOAuthRefreshCandidatePage_GrokCursorAndExclusions() {
now := time.Now().UTC()
valid1 := mustCreateAccount(s.T(), s.client, &service.Account{
Name: "grok-oauth-page-1",
Platform: service.PlatformGrok,
Type: service.AccountTypeOAuth,
Status: service.StatusActive,
Credentials: map[string]any{
"access_token": "access-1",
"refresh_token": "refresh-1",
"expires_at": now.Add(30 * time.Minute).Format(time.RFC3339),
},
})
mustCreateAccount(s.T(), s.client, &service.Account{
Name: "grok-api-key-excluded",
Platform: service.PlatformGrok,
Type: service.AccountTypeAPIKey,
Status: service.StatusActive,
Credentials: map[string]any{
"api_key": "api-key",
"refresh_token": "must-not-make-api-key-eligible",
},
})
valid2 := mustCreateAccount(s.T(), s.client, &service.Account{
Name: "grok-oauth-page-2",
Platform: service.PlatformGrok,
Type: service.AccountTypeOAuth,
Status: service.StatusActive,
Credentials: map[string]any{"refresh_token": "refresh-2"},
})
mustCreateAccount(s.T(), s.client, &service.Account{
Name: "grok-oauth-blank-refresh-excluded",
Platform: service.PlatformGrok,
Type: service.AccountTypeOAuth,
Status: service.StatusActive,
Credentials: map[string]any{"refresh_token": " "},
})
valid3 := mustCreateAccount(s.T(), s.client, &service.Account{
Name: "grok-oauth-page-3",
Platform: service.PlatformGrok,
Type: service.AccountTypeOAuth,
Status: service.StatusActive,
Credentials: map[string]any{"refresh_token": "refresh-3"},
})
cooldown := mustCreateAccount(s.T(), s.client, &service.Account{
Name: "grok-oauth-retry-cooldown-excluded",
Platform: service.PlatformGrok,
Type: service.AccountTypeOAuth,
Status: service.StatusActive,
Credentials: map[string]any{"refresh_token": "refresh-cooldown"},
})
s.Require().NoError(s.repo.SetTempUnschedulable(s.ctx, cooldown.ID, now.Add(10*time.Minute), "token refresh retry exhausted: timeout"))
mustCreateAccount(s.T(), s.client, &service.Account{
Name: "openai-oauth-excluded",
Platform: service.PlatformOpenAI,
Type: service.AccountTypeOAuth,
Status: service.StatusActive,
Credentials: map[string]any{"refresh_token": "refresh-openai"},
})
options := service.OAuthRefreshPageOptions{
Platforms: []string{service.PlatformGrok},
Limit: 2,
ActiveOnly: true,
RequireRefreshToken: true,
ExcludeRetryCooldown: true,
}
firstPage, err := s.repo.ListOAuthRefreshCandidatePage(s.ctx, options)
s.Require().NoError(err)
first := firstPage.Accounts
s.Require().Len(first, 2)
s.Require().Equal([]int64{valid1.ID, valid2.ID}, []int64{first[0].ID, first[1].ID})
options.AfterID = first[len(first)-1].ID
secondPage, err := s.repo.ListOAuthRefreshCandidatePage(s.ctx, options)
s.Require().NoError(err)
second := secondPage.Accounts
s.Require().Len(second, 1)
s.Require().Equal(valid3.ID, second[0].ID)
s.Require().NotContains([]int64{first[0].ID, first[1].ID}, second[0].ID)
}
func (s *AccountRepoSuite) TestListWithFilters() {
tests := []struct {
name string
@@ -722,6 +882,56 @@ func (s *AccountRepoSuite) TestSetRateLimitedIfLaterDoesNotShortenReset() {
s.Require().WithinDuration(later, *cacheRecorder.setAccounts[1].RateLimitResetAt, time.Second)
}
func (s *AccountRepoSuite) TestClearRateLimitIfObservedProtectsRearmed429Generation() {
account := mustCreateAccount(s.T(), s.client, &service.Account{
Name: "acc-rl-conditional-clear",
Platform: service.PlatformGrok,
Type: service.AccountTypeOAuth,
})
firstReset := time.Now().Add(30 * time.Minute).UTC().Truncate(time.Second)
rearmedReset := time.Now().Add(5 * time.Minute).UTC().Truncate(time.Second)
s.Require().NoError(s.repo.SetRateLimitedIfLater(s.ctx, account.ID, firstReset))
staleGeneration, err := s.repo.GetByID(s.ctx, account.ID)
s.Require().NoError(err)
s.Require().NotNil(staleGeneration.RateLimitedAt)
s.Require().NotNil(staleGeneration.RateLimitResetAt)
cleared, err := s.repo.ClearRateLimitIfObserved(s.ctx, account.ID, *staleGeneration.RateLimitedAt, *staleGeneration.RateLimitResetAt)
s.Require().NoError(err)
s.Require().True(cleared)
// A newer generation may legitimately re-arm a shorter boundary after the
// first generation was cleared. The stale success must not erase it.
s.Require().NoError(s.repo.SetRateLimitedIfLater(s.ctx, account.ID, rearmedReset))
cleared, err = s.repo.ClearRateLimitIfObserved(s.ctx, account.ID, *staleGeneration.RateLimitedAt, *staleGeneration.RateLimitResetAt)
s.Require().NoError(err)
s.Require().False(cleared)
got, err := s.repo.GetByID(s.ctx, account.ID)
s.Require().NoError(err)
s.Require().NotNil(got.RateLimitedAt)
s.Require().NotNil(got.RateLimitResetAt)
s.Require().WithinDuration(rearmedReset, *got.RateLimitResetAt, time.Second)
// An admin can retype the row while the successful OAuth request is still
// in flight. The stale OAuth recovery must not cross into API-key state even
// when both observed timestamps still match.
_, err = s.client.Account.UpdateOneID(account.ID).
SetType(service.AccountTypeAPIKey).
Save(s.ctx)
s.Require().NoError(err)
cleared, err = s.repo.ClearRateLimitIfObserved(s.ctx, account.ID, *got.RateLimitedAt, *got.RateLimitResetAt)
s.Require().NoError(err)
s.Require().False(cleared)
retyped, err := s.repo.GetByID(s.ctx, account.ID)
s.Require().NoError(err)
s.Require().Equal(service.AccountTypeAPIKey, retyped.Type)
s.Require().NotNil(retyped.RateLimitedAt)
s.Require().NotNil(retyped.RateLimitResetAt)
s.Require().WithinDuration(rearmedReset, *retyped.RateLimitResetAt, time.Second)
}
func (s *AccountRepoSuite) TestClearRateLimit() {
account := mustCreateAccount(s.T(), s.client, &service.Account{Name: "acc-clear"})
until := time.Now().Add(1 * time.Hour)
@@ -848,6 +1058,10 @@ func (s *AccountRepoSuite) TestUpdateLastUsed() {
func (s *AccountRepoSuite) TestSetError() {
account := mustCreateAccount(s.T(), s.client, &service.Account{Name: "acc-err", Status: service.StatusActive, Schedulable: true})
cacheRecorder := &schedulerCacheRecorder{}
s.repo.schedulerCache = cacheRecorder
_, err := s.repo.sql.ExecContext(s.ctx, "TRUNCATE scheduler_outbox")
s.Require().NoError(err)
s.Require().NoError(s.repo.SetError(s.ctx, account.ID, "something went wrong"))
@@ -856,6 +1070,296 @@ func (s *AccountRepoSuite) TestSetError() {
s.Require().Equal(service.StatusError, got.Status)
s.Require().Equal("something went wrong", got.ErrorMessage)
s.Require().False(got.Schedulable)
s.Require().Len(cacheRecorder.setAccounts, 1)
s.Require().Equal(account.ID, cacheRecorder.setAccounts[0].ID)
s.Require().Equal(service.StatusError, cacheRecorder.setAccounts[0].Status)
s.Require().False(cacheRecorder.setAccounts[0].Schedulable)
var outboxCount int
err = scanSingleRow(
s.ctx,
s.repo.sql,
"SELECT COUNT(*) FROM scheduler_outbox WHERE event_type = $1 AND account_id = $2",
[]any{service.SchedulerOutboxEventAccountChanged, account.ID},
&outboxCount,
)
s.Require().NoError(err)
s.Require().Equal(1, outboxCount)
}
func (s *AccountRepoSuite) TestSetGrokOAuthErrorIfCredentialsUnchanged_AppliesAndSyncsSchedulerState() {
account := mustCreateAccount(s.T(), s.client, &service.Account{
Name: "grok-conditional-error-applied",
Platform: service.PlatformGrok,
Type: service.AccountTypeOAuth,
Status: service.StatusActive,
Schedulable: true,
Credentials: map[string]any{"access_token": "observed", "_token_version": int64(7)},
})
observed, err := s.repo.GetByID(s.ctx, account.ID)
s.Require().NoError(err)
cacheRecorder := &schedulerCacheRecorder{}
s.repo.schedulerCache = cacheRecorder
_, err = s.repo.sql.ExecContext(s.ctx, "TRUNCATE scheduler_outbox")
s.Require().NoError(err)
applied, err := s.repo.SetGrokOAuthErrorIfCredentialsUnchanged(
s.ctx,
account.ID,
observed.Credentials,
"missing refresh token",
)
s.Require().NoError(err)
s.Require().True(applied)
got, err := s.repo.GetByID(s.ctx, account.ID)
s.Require().NoError(err)
s.Require().Equal(service.StatusError, got.Status)
s.Require().False(got.Schedulable)
s.Require().Equal("missing refresh token", got.ErrorMessage)
s.Require().Len(cacheRecorder.setAccounts, 1)
s.Require().Equal(service.StatusError, cacheRecorder.setAccounts[0].Status)
var outboxCount int
err = scanSingleRow(
s.ctx,
s.repo.sql,
"SELECT COUNT(*) FROM scheduler_outbox WHERE event_type = $1 AND account_id = $2",
[]any{service.SchedulerOutboxEventAccountChanged, account.ID},
&outboxCount,
)
s.Require().NoError(err)
s.Require().Equal(1, outboxCount)
}
func (s *AccountRepoSuite) TestSetGrokOAuthErrorIfCredentialsUnchanged_SkipsConcurrentReauthorization() {
account := mustCreateAccount(s.T(), s.client, &service.Account{
Name: "grok-conditional-error-reauthorized",
Platform: service.PlatformGrok,
Type: service.AccountTypeOAuth,
Status: service.StatusActive,
Schedulable: true,
Credentials: map[string]any{"access_token": "observed", "_token_version": int64(7)},
})
observed, err := s.repo.GetByID(s.ctx, account.ID)
s.Require().NoError(err)
s.Require().NoError(s.repo.UpdateCredentials(s.ctx, account.ID, map[string]any{
"access_token": "fresh-access",
"refresh_token": "fresh-refresh",
"expires_at": time.Now().UTC().Add(4 * time.Hour).Format(time.RFC3339),
"_token_version": int64(8),
}))
cacheRecorder := &schedulerCacheRecorder{}
s.repo.schedulerCache = cacheRecorder
_, err = s.repo.sql.ExecContext(s.ctx, "TRUNCATE scheduler_outbox")
s.Require().NoError(err)
applied, err := s.repo.SetGrokOAuthErrorIfCredentialsUnchanged(
s.ctx,
account.ID,
observed.Credentials,
"stale reconciliation",
)
s.Require().NoError(err)
s.Require().False(applied)
got, err := s.repo.GetByID(s.ctx, account.ID)
s.Require().NoError(err)
s.Require().Equal(service.StatusActive, got.Status)
s.Require().True(got.Schedulable)
s.Require().Equal("fresh-refresh", got.GetGrokRefreshToken())
s.Require().Empty(cacheRecorder.setAccounts, "a lost compare-and-set race must not rewrite the scheduler snapshot")
var outboxCount int
err = scanSingleRow(
s.ctx,
s.repo.sql,
"SELECT COUNT(*) FROM scheduler_outbox WHERE event_type = $1 AND account_id = $2",
[]any{service.SchedulerOutboxEventAccountChanged, account.ID},
&outboxCount,
)
s.Require().NoError(err)
s.Require().Zero(outboxCount, "a lost compare-and-set race must not enqueue a stale account change")
}
func (s *AccountRepoSuite) TestUpdateGrokOAuthCredentialsIfUnchanged_AppliesAndPublishesSchedulerState() {
account := mustCreateAccount(s.T(), s.client, &service.Account{
Name: "grok-refresh-success-cas-applied",
Platform: service.PlatformGrok,
Type: service.AccountTypeOAuth,
Status: service.StatusActive,
Schedulable: true,
Credentials: map[string]any{
"access_token": "attempted-access",
"refresh_token": "attempted-refresh",
"_token_version": int64(10),
},
})
observed, err := s.repo.GetByID(s.ctx, account.ID)
s.Require().NoError(err)
cacheRecorder := &schedulerCacheRecorder{}
s.repo.schedulerCache = cacheRecorder
_, err = s.repo.sql.ExecContext(s.ctx, "TRUNCATE scheduler_outbox")
s.Require().NoError(err)
applied, err := s.repo.UpdateGrokOAuthCredentialsIfUnchanged(
s.ctx,
account.ID,
observed.Credentials,
observed.ProxyID,
map[string]any{
"access_token": "rotated-access",
"refresh_token": "rotated-refresh",
"_token_version": int64(11),
},
)
s.Require().NoError(err)
s.Require().True(applied)
got, err := s.repo.GetByID(s.ctx, account.ID)
s.Require().NoError(err)
s.Require().Equal("rotated-refresh", got.GetGrokRefreshToken())
s.Require().Len(cacheRecorder.setAccounts, 1)
s.Require().Equal("rotated-refresh", cacheRecorder.setAccounts[0].GetGrokRefreshToken())
s.Require().NoError(cacheRecorder.setCtxErr)
var outboxCount int
err = scanSingleRow(
s.ctx,
s.repo.sql,
"SELECT COUNT(*) FROM scheduler_outbox WHERE event_type = $1 AND account_id = $2",
[]any{service.SchedulerOutboxEventAccountChanged, account.ID},
&outboxCount,
)
s.Require().NoError(err)
s.Require().Equal(1, outboxCount)
}
func (s *AccountRepoSuite) TestUpdateGrokOAuthCredentialsIfUnchanged_SkipsConcurrentReauthorization() {
account := mustCreateAccount(s.T(), s.client, &service.Account{
Name: "grok-refresh-success-cas-reauthorized",
Platform: service.PlatformGrok,
Type: service.AccountTypeOAuth,
Status: service.StatusActive,
Schedulable: true,
Credentials: map[string]any{
"access_token": "attempted-access",
"refresh_token": "attempted-refresh",
"_token_version": int64(20),
},
})
observed, err := s.repo.GetByID(s.ctx, account.ID)
s.Require().NoError(err)
s.Require().NoError(s.repo.UpdateCredentials(s.ctx, account.ID, map[string]any{
"access_token": "reauthorized-access",
"refresh_token": "reauthorized-refresh",
"_token_version": int64(21),
}))
cacheRecorder := &schedulerCacheRecorder{}
s.repo.schedulerCache = cacheRecorder
_, err = s.repo.sql.ExecContext(s.ctx, "TRUNCATE scheduler_outbox")
s.Require().NoError(err)
applied, err := s.repo.UpdateGrokOAuthCredentialsIfUnchanged(
s.ctx,
account.ID,
observed.Credentials,
observed.ProxyID,
map[string]any{
"access_token": "provider-access",
"refresh_token": "provider-refresh",
"_token_version": int64(22),
},
)
s.Require().NoError(err)
s.Require().False(applied)
got, err := s.repo.GetByID(s.ctx, account.ID)
s.Require().NoError(err)
s.Require().Equal("reauthorized-refresh", got.GetGrokRefreshToken())
s.Require().Empty(cacheRecorder.setAccounts)
var outboxCount int
err = scanSingleRow(
s.ctx,
s.repo.sql,
"SELECT COUNT(*) FROM scheduler_outbox WHERE event_type = $1 AND account_id = $2",
[]any{service.SchedulerOutboxEventAccountChanged, account.ID},
&outboxCount,
)
s.Require().NoError(err)
s.Require().Zero(outboxCount)
}
func (s *AccountRepoSuite) TestGrokOAuthConditionalMutation_DetachesBoundedSnapshotSync() {
account := mustCreateAccount(s.T(), s.client, &service.Account{
Name: "grok-conditional-detached-sync",
Platform: service.PlatformGrok,
Type: service.AccountTypeOAuth,
Status: service.StatusActive,
Schedulable: true,
Credentials: map[string]any{"access_token": "observed"},
})
observed, err := s.repo.GetByID(s.ctx, account.ID)
s.Require().NoError(err)
ctx, cancel := context.WithCancel(context.Background())
cacheRecorder := &schedulerCacheRecorder{}
repo := newAccountRepositoryWithSQL(s.client, &cancelAfterAtomicMutationSQLExecutor{
sqlExecutor: s.repo.sql,
cancel: cancel,
}, cacheRecorder)
applied, err := repo.SetGrokOAuthErrorIfCredentialsUnchanged(
ctx,
account.ID,
observed.Credentials,
"missing refresh token",
)
s.Require().NoError(err)
s.Require().True(applied)
s.Require().ErrorIs(ctx.Err(), context.Canceled)
s.Require().Len(cacheRecorder.setAccounts, 1)
s.Require().NoError(cacheRecorder.setCtxErr, "immediate scheduler propagation must use a bounded detached context")
}
func TestGrokOAuthConditionalMutationRollsBackWhenOutboxInsertFails(t *testing.T) {
client := testEntClient(t)
account := mustCreateAccount(t, client, &service.Account{
Name: "grok-conditional-atomic-outbox-failure",
Platform: service.PlatformGrok,
Type: service.AccountTypeOAuth,
Status: service.StatusActive,
Schedulable: true,
Credentials: map[string]any{"access_token": "observed"},
})
t.Cleanup(func() {
_, _ = integrationDB.ExecContext(context.Background(), "DELETE FROM scheduler_outbox WHERE account_id = $1", account.ID)
_ = client.Account.DeleteOneID(account.ID).Exec(context.Background())
})
repo := newAccountRepositoryWithSQL(client, &failAtomicSchedulerOutboxSQLExecutor{sqlExecutor: integrationDB}, nil)
applied, err := repo.SetGrokOAuthErrorIfCredentialsUnchanged(
context.Background(),
account.ID,
account.Credentials,
"missing refresh token",
)
require.Error(t, err)
require.False(t, applied)
got, readErr := repo.GetByID(context.Background(), account.ID)
require.NoError(t, readErr)
require.Equal(t, service.StatusActive, got.Status)
require.True(t, got.Schedulable)
require.Empty(t, got.ErrorMessage)
var outboxCount int
require.NoError(t, integrationDB.QueryRowContext(
context.Background(),
"SELECT COUNT(*) FROM scheduler_outbox WHERE account_id = $1",
account.ID,
).Scan(&outboxCount))
require.Zero(t, outboxCount)
}
func (s *AccountRepoSuite) TestUpdateErrorStatusUnschedulesAccount() {
@@ -0,0 +1,107 @@
//go:build integration
package repository
import (
"context"
"testing"
"time"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/stretchr/testify/require"
)
func TestListSchedulableAccountLoadsMatchesListSchedulable(t *testing.T) {
ctx := context.Background()
tx := testEntTx(t)
client := tx.Client()
repo := newAccountRepositoryWithSQL(client, tx, nil)
now := time.Now()
past := now.Add(-time.Hour)
future := now.Add(time.Hour)
create := func(name string) *service.Account {
return mustCreateAccount(t, client, &service.Account{Name: name, Schedulable: true})
}
positiveLoad := create("projection-positive-load")
_, err := client.Account.UpdateOneID(positiveLoad.ID).SetConcurrency(2).SetLoadFactor(9).SetPriority(30).Save(ctx)
require.NoError(t, err)
concurrencyFallback := create("projection-concurrency-fallback")
_, err = client.Account.UpdateOneID(concurrencyFallback.ID).SetConcurrency(4).SetPriority(10).Save(ctx)
require.NoError(t, err)
zeroFallback := create("projection-zero-fallback")
_, err = client.Account.UpdateOneID(zeroFallback.ID).SetConcurrency(0).SetLoadFactor(0).SetPriority(20).Save(ctx)
require.NoError(t, err)
disabled := create("projection-disabled")
_, err = client.Account.UpdateOneID(disabled.ID).SetStatus(service.StatusDisabled).Save(ctx)
require.NoError(t, err)
unschedulable := create("projection-unschedulable")
_, err = client.Account.UpdateOneID(unschedulable.ID).SetSchedulable(false).Save(ctx)
require.NoError(t, err)
expired := create("projection-expired")
_, err = client.Account.UpdateOneID(expired.ID).SetExpiresAt(past).SetAutoPauseOnExpired(true).Save(ctx)
require.NoError(t, err)
expiredAllowed := create("projection-expired-allowed")
_, err = client.Account.UpdateOneID(expiredAllowed.ID).SetExpiresAt(past).SetAutoPauseOnExpired(false).Save(ctx)
require.NoError(t, err)
overloaded := create("projection-overloaded")
_, err = client.Account.UpdateOneID(overloaded.ID).SetOverloadUntil(future).Save(ctx)
require.NoError(t, err)
overloadCleared := create("projection-overload-cleared")
_, err = client.Account.UpdateOneID(overloadCleared.ID).SetOverloadUntil(past).Save(ctx)
require.NoError(t, err)
rateLimited := create("projection-rate-limited")
_, err = client.Account.UpdateOneID(rateLimited.ID).SetRateLimitResetAt(future).Save(ctx)
require.NoError(t, err)
rateLimitCleared := create("projection-rate-limit-cleared")
_, err = client.Account.UpdateOneID(rateLimitCleared.ID).SetRateLimitResetAt(past).Save(ctx)
require.NoError(t, err)
tempBlocked := create("projection-temp-blocked")
_, err = client.Account.UpdateOneID(tempBlocked.ID).SetTempUnschedulableUntil(future).Save(ctx)
require.NoError(t, err)
tempCleared := create("projection-temp-cleared")
_, err = client.Account.UpdateOneID(tempCleared.ID).SetTempUnschedulableUntil(past).Save(ctx)
require.NoError(t, err)
accounts, err := repo.ListSchedulable(ctx)
require.NoError(t, err)
loads, err := repo.ListSchedulableAccountLoads(ctx)
require.NoError(t, err)
accountIDs := make([]int64, 0, len(accounts))
wantByID := make(map[int64]int, len(accounts))
for i := range accounts {
accountIDs = append(accountIDs, accounts[i].ID)
wantByID[accounts[i].ID] = accounts[i].EffectiveLoadFactor()
}
loadIDs := make([]int64, 0, len(loads))
byID := make(map[int64]int, len(loads))
for _, load := range loads {
loadIDs = append(loadIDs, load.ID)
byID[load.ID] = load.MaxConcurrency
}
require.Equal(t, accountIDs, loadIDs)
targetIDs := map[int64]struct{}{
positiveLoad.ID: {}, concurrencyFallback.ID: {}, zeroFallback.ID: {},
}
targetOrder := make([]int64, 0, len(targetIDs))
for _, id := range loadIDs {
if _, ok := targetIDs[id]; ok {
targetOrder = append(targetOrder, id)
}
}
require.Equal(t, []int64{concurrencyFallback.ID, zeroFallback.ID, positiveLoad.ID}, targetOrder)
require.Equal(t, wantByID, byID)
require.Equal(t, 9, byID[positiveLoad.ID])
require.Equal(t, 4, byID[concurrencyFallback.ID])
require.Equal(t, 1, byID[zeroFallback.ID])
for _, included := range []*service.Account{expiredAllowed, overloadCleared, rateLimitCleared, tempCleared} {
require.Contains(t, byID, included.ID)
}
for _, excluded := range []*service.Account{disabled, unschedulable, expired, overloaded, rateLimited, tempBlocked} {
require.NotContains(t, byID, excluded.ID)
}
}
@@ -0,0 +1,82 @@
package repository
import (
"context"
"fmt"
"strings"
"testing"
"github.com/DATA-DOG/go-sqlmock"
dbent "github.com/Wei-Shaw/sub2api/ent"
_ "github.com/Wei-Shaw/sub2api/ent/runtime"
"github.com/stretchr/testify/require"
"entgo.io/ent/dialect"
entsql "entgo.io/ent/dialect/sql"
)
type captureEntQueryMatcher struct {
actual *string
}
func (m captureEntQueryMatcher) Match(_, actual string) error {
if m.actual == nil {
return fmt.Errorf("query capture target is nil")
}
*m.actual = actual
return nil
}
func TestListSchedulableAccountLoadsUsesSingleProjectionQuery(t *testing.T) {
var capturedSQL string
db, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(captureEntQueryMatcher{actual: &capturedSQL}))
require.NoError(t, err)
t.Cleanup(func() { _ = db.Close() })
driver := entsql.OpenDB(dialect.Postgres, db)
client := dbent.NewClient(dbent.Driver(driver))
t.Cleanup(func() { _ = client.Close() })
repo := newAccountRepositoryWithSQL(client, db, nil)
mock.ExpectQuery("schedulable account load projection").
WillReturnRows(sqlmock.NewRows([]string{"id", "concurrency", "load_factor"}).
AddRow(int64(11), 3, nil).
AddRow(int64(12), 2, 7))
loads, err := repo.ListSchedulableAccountLoads(context.Background())
require.NoError(t, err)
require.Len(t, loads, 2)
require.Equal(t, int64(11), loads[0].ID)
require.Equal(t, 3, loads[0].MaxConcurrency)
require.Equal(t, int64(12), loads[1].ID)
require.Equal(t, 7, loads[1].MaxConcurrency)
require.NoError(t, mock.ExpectationsWereMet(), "projection path must execute exactly one query")
normalized := normalizeSQLWhitespace(capturedSQL)
selectClause, _, found := strings.Cut(normalized, " FROM ")
require.True(t, found, "unexpected projection SQL: %s", normalized)
require.Equal(t, 2, strings.Count(selectClause, ","), "projection must select exactly three columns: %s", selectClause)
require.Contains(t, selectClause, `"id"`)
require.Contains(t, selectClause, `"concurrency"`)
require.Contains(t, selectClause, `"load_factor"`)
require.NotContains(t, selectClause, "credentials")
require.NotContains(t, selectClause, "extra")
require.NotContains(t, selectClause, "proxy_id")
require.NotContains(t, normalized, "account_groups")
require.NotContains(t, normalized, "proxies")
for _, predicateColumn := range []string{
"status",
"schedulable",
"temp_unschedulable_until",
"expires_at",
"auto_pause_on_expired",
"overload_until",
"rate_limit_reset_at",
"deleted_at",
} {
require.Contains(t, normalized, predicateColumn)
}
_, orderClause, hasOrder := strings.Cut(normalized, " ORDER BY ")
require.True(t, hasOrder, "projection query must preserve schedulable account order: %s", normalized)
require.Contains(t, orderClause, `"priority" ASC`)
}
@@ -3,12 +3,14 @@ package repository
import (
"context"
"database/sql"
"database/sql/driver"
"regexp"
"strings"
"testing"
"time"
sqlmock "github.com/DATA-DOG/go-sqlmock"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/stretchr/testify/require"
)
@@ -24,28 +26,262 @@ func TestAccountRepository_SetTempUnschedulable_NoRowsAffectedDoesNotWriteOutbox
require.NotContains(t, strings.Join(exec.execQueries, "\n"), "scheduler_outbox")
}
func TestAccountRepository_ListOAuthRefreshCandidates_SQLFilter(t *testing.T) {
func TestAccountRepository_GrokCredentialConditionalMutationsAreEligibleAndAtomicallyPropagated(t *testing.T) {
proxyID := int64(77)
snapshot := service.GrokCredentialMutationSnapshot{
CredentialsJSON: `{"access_token":"access","refresh_token":"refresh","_token_version":123}`,
ProxyID: &proxyID,
}
t.Run("permanent", func(t *testing.T) {
exec := &recordingSQLExecutor{result: rowsAffectedResult(0)}
repo := newAccountRepositoryWithSQL(nil, exec, nil)
updated, err := repo.SetGrokCredentialErrorIfMatch(context.Background(), 42, snapshot, "revoked")
require.NoError(t, err)
require.False(t, updated)
require.Len(t, exec.execQueries, 1)
normalized := normalizeSQLWhitespace(exec.execQueries[0])
require.Contains(t, normalized, "WITH updated AS ( UPDATE accounts AS a")
require.Contains(t, normalized, "a.schedulable IS TRUE")
require.Contains(t, normalized, "a.temp_unschedulable_until IS NULL OR a.temp_unschedulable_until <= NOW()")
require.Contains(t, normalized, "a.rate_limit_reset_at IS NULL OR a.rate_limit_reset_at <= NOW()")
require.Contains(t, normalized, "a.overload_until IS NULL OR a.overload_until <= NOW()")
require.Contains(t, normalized, "a.credentials = $7::jsonb")
require.Contains(t, normalized, "a.proxy_id IS NOT DISTINCT FROM $8")
require.Contains(t, normalized, "NOT EXISTS ( SELECT 1 FROM proxies p")
require.Contains(t, normalized, "INSERT INTO scheduler_outbox")
require.Len(t, exec.execArgs[0], 10)
require.Equal(t, snapshot.CredentialsJSON, exec.execArgs[0][6])
require.Equal(t, &proxyID, exec.execArgs[0][7])
require.Equal(t, string(service.GrokCredentialReasonProxyInvalid), exec.execArgs[0][8])
require.Equal(t, service.SchedulerOutboxEventAccountChanged, exec.execArgs[0][9])
})
t.Run("transient", func(t *testing.T) {
exec := &recordingSQLExecutor{result: rowsAffectedResult(0)}
repo := newAccountRepositoryWithSQL(nil, exec, nil)
updated, err := repo.SetGrokCredentialTempUnschedulableIfMatch(
context.Background(), 42, snapshot, time.Now().Add(time.Minute), "temporary",
)
require.NoError(t, err)
require.False(t, updated)
require.Len(t, exec.execQueries, 1)
normalized := normalizeSQLWhitespace(exec.execQueries[0])
require.Contains(t, normalized, "WITH updated AS ( UPDATE accounts AS a")
require.Contains(t, normalized, "a.schedulable IS TRUE")
require.Contains(t, normalized, "a.temp_unschedulable_until IS NULL OR a.temp_unschedulable_until <= NOW()")
require.Contains(t, normalized, "a.rate_limit_reset_at IS NULL OR a.rate_limit_reset_at <= NOW()")
require.Contains(t, normalized, "a.overload_until IS NULL OR a.overload_until <= NOW()")
require.Contains(t, normalized, "a.credentials = $7::jsonb")
require.Contains(t, normalized, "a.proxy_id IS NOT DISTINCT FROM $8")
require.Contains(t, normalized, "INSERT INTO scheduler_outbox")
require.Len(t, exec.execArgs[0], 9)
require.Equal(t, snapshot.CredentialsJSON, exec.execArgs[0][6])
require.Equal(t, &proxyID, exec.execArgs[0][7])
require.Equal(t, service.SchedulerOutboxEventAccountChanged, exec.execArgs[0][8])
})
}
func TestAccountRepository_GrokCredentialCommitCarriesOutboxAcrossCallerCancellation(t *testing.T) {
snapshot := service.GrokCredentialMutationSnapshot{CredentialsJSON: `{"access_token":"access","refresh_token":"refresh"}`}
tests := []struct {
name string
mutate func(context.Context, *accountRepository) (bool, error)
}{
{
name: "permanent",
mutate: func(ctx context.Context, repo *accountRepository) (bool, error) {
return repo.SetGrokCredentialErrorIfMatch(ctx, 42, snapshot, string(service.GrokCredentialReasonRevoked))
},
},
{
name: "transient",
mutate: func(ctx context.Context, repo *accountRepository) (bool, error) {
return repo.SetGrokCredentialTempUnschedulableIfMatch(ctx, 42, snapshot, time.Now().Add(time.Minute), string(service.GrokCredentialReasonRefreshTransient))
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
exec := &recordingSQLExecutor{result: rowsAffectedResult(1), afterExec: cancel}
repo := newAccountRepositoryWithSQL(nil, exec, nil)
updated, err := tt.mutate(ctx, repo)
require.NoError(t, err)
require.True(t, updated)
require.ErrorIs(t, ctx.Err(), context.Canceled)
require.Len(t, exec.execQueries, 1, "state update and scheduler outbox must share one atomic SQL statement")
require.Contains(t, normalizeSQLWhitespace(exec.execQueries[0]), "INSERT INTO scheduler_outbox")
})
}
}
func TestAccountRepository_SetGrokOAuthErrorIfCredentialsUnchanged_RequiresActiveExactCredentialMatch(t *testing.T) {
exec := &recordingSQLExecutor{result: rowsAffectedResult(0)}
repo := newAccountRepositoryWithSQL(nil, exec, nil)
applied, err := repo.SetGrokOAuthErrorIfCredentialsUnchanged(
context.Background(),
42,
map[string]any{"access_token": "observed", "_token_version": int64(7)},
"missing refresh token",
)
require.NoError(t, err)
require.False(t, applied)
require.Len(t, exec.execQueries, 1, "the account mutation and conditional outbox insert must be one statement")
normalized := normalizeSQLWhitespace(exec.execQueries[0])
require.Contains(t, normalized, "WITH updated AS")
require.Contains(t, normalized, "INSERT INTO scheduler_outbox")
require.Contains(t, normalized, "FROM updated")
require.Contains(t, normalized, "platform = $4")
require.Contains(t, normalized, "type = $5")
require.Contains(t, normalized, "status = $6")
require.Contains(t, normalized, "credentials = $7::jsonb")
require.Contains(t, normalized, "NULLIF(BTRIM(a.credentials->>'refresh_token'), '') IS NULL")
require.Len(t, exec.execArgs, 1)
require.Equal(t, service.StatusActive, exec.execArgs[0][5])
require.Contains(t, exec.execArgs[0][6], `"_token_version":7`)
}
func TestAccountRepository_SetGrokOAuthErrorIfCredentialsUnchanged_AppliedWritesOutbox(t *testing.T) {
exec := &recordingSQLExecutor{result: rowsAffectedResult(1)}
repo := newAccountRepositoryWithSQL(nil, exec, nil)
applied, err := repo.SetGrokOAuthErrorIfCredentialsUnchanged(
context.Background(),
42,
map[string]any{"access_token": "observed"},
"missing refresh token",
)
require.NoError(t, err)
require.True(t, applied)
require.Len(t, exec.execQueries, 1)
normalized := normalizeSQLWhitespace(exec.execQueries[0])
require.Contains(t, normalized, "WITH updated AS")
require.Contains(t, normalized, "INSERT INTO scheduler_outbox")
require.Contains(t, normalized, "SELECT $8, updated.id, NULL, NULL FROM updated")
}
func TestAccountRepository_SetGrokOAuthRefreshErrorIfCredentialsUnchanged_UsesAttemptCredentialsAndProxy(t *testing.T) {
exec := &recordingSQLExecutor{result: rowsAffectedResult(0)}
repo := newAccountRepositoryWithSQL(nil, exec, nil)
proxyID := int64(17)
applied, err := repo.SetGrokOAuthRefreshErrorIfCredentialsUnchanged(
context.Background(),
42,
map[string]any{"refresh_token": "attempted", "_token_version": int64(7)},
&proxyID,
"revoked",
)
require.NoError(t, err)
require.False(t, applied)
require.Len(t, exec.execQueries, 1)
normalized := normalizeSQLWhitespace(exec.execQueries[0])
require.Contains(t, normalized, "credentials = $7::jsonb")
require.Contains(t, normalized, "proxy_id IS NOT DISTINCT FROM $8")
require.NotContains(t, normalized, "credentials->>'refresh_token'",
"background invalid_grant CAS must accept the attempted refresh token; only reconciliation requires it missing")
require.Equal(t, &proxyID, exec.execArgs[0][7])
require.Contains(t, normalized, "INSERT INTO scheduler_outbox")
require.Len(t, exec.execArgs[0], 9)
}
func TestAccountRepository_SetGrokOAuthRefreshTempUnschedulableIfCredentialsUnchanged_UsesAttemptCredentialsAndProxy(t *testing.T) {
exec := &recordingSQLExecutor{result: rowsAffectedResult(0)}
repo := newAccountRepositoryWithSQL(nil, exec, nil)
proxyID := int64(19)
applied, err := repo.SetGrokOAuthRefreshTempUnschedulableIfCredentialsUnchanged(
context.Background(),
42,
map[string]any{"refresh_token": "attempted", "_token_version": int64(8)},
&proxyID,
time.Now().Add(10*time.Minute),
"retry exhausted",
)
require.NoError(t, err)
require.False(t, applied)
require.Len(t, exec.execQueries, 1)
normalized := normalizeSQLWhitespace(exec.execQueries[0])
require.Contains(t, normalized, "credentials = $7::jsonb")
require.Contains(t, normalized, "proxy_id IS NOT DISTINCT FROM $8")
require.Contains(t, normalized, "a.temp_unschedulable_until IS NULL OR a.temp_unschedulable_until < $1")
require.Len(t, exec.execArgs[0], 9)
require.Equal(t, &proxyID, exec.execArgs[0][7])
require.Contains(t, normalized, "INSERT INTO scheduler_outbox")
}
func TestAccountRepository_UpdateGrokOAuthCredentialsIfUnchanged_UsesExactAttemptStateAndAtomicOutbox(t *testing.T) {
exec := &recordingSQLExecutor{result: rowsAffectedResult(1)}
repo := newAccountRepositoryWithSQL(nil, exec, nil)
proxyID := int64(29)
applied, err := repo.UpdateGrokOAuthCredentialsIfUnchanged(
context.Background(),
42,
map[string]any{"refresh_token": "attempted", "_token_version": int64(9)},
&proxyID,
map[string]any{"refresh_token": "rotated", "_token_version": int64(10)},
)
require.NoError(t, err)
require.True(t, applied)
require.Len(t, exec.execQueries, 1)
normalized := normalizeSQLWhitespace(exec.execQueries[0])
require.Contains(t, normalized, "WITH updated AS")
require.Contains(t, normalized, "credentials = $1::jsonb")
require.Contains(t, normalized, "credentials = $5::jsonb")
require.Contains(t, normalized, "proxy_id IS NOT DISTINCT FROM $6")
require.Contains(t, normalized, "INSERT INTO scheduler_outbox")
require.Len(t, exec.execArgs[0], 7)
require.Equal(t, &proxyID, exec.execArgs[0][5])
}
func TestAccountRepository_ListOAuthRefreshCandidatePage_SQLFilter(t *testing.T) {
db, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherRegexp))
require.NoError(t, err)
defer func() { _ = db.Close() }()
var capturedSQL string
var capturedArgs []any
mock.ExpectQuery("SELECT id").
WillReturnRows(sqlmock.NewRows([]string{"id"})).
WillDelayFor(0)
repo := newAccountRepositoryWithSQL(nil, captureQuerySQL{db: db, captured: &capturedSQL}, nil)
repo := newAccountRepositoryWithSQL(nil, captureQuerySQL{db: db, captured: &capturedSQL, args: &capturedArgs}, nil)
accounts, err := repo.ListOAuthRefreshCandidates(context.Background())
page, err := repo.ListOAuthRefreshCandidatePage(context.Background(), service.OAuthRefreshPageOptions{
Platforms: []string{service.PlatformAnthropic, service.PlatformOpenAI, service.PlatformGemini, service.PlatformAntigravity, service.PlatformGrok},
AfterID: 100,
Limit: 200,
ActiveOnly: true,
IncludeSetupToken: true,
RequireRefreshToken: true,
ExcludeRetryCooldown: true,
})
require.NoError(t, err)
require.Empty(t, accounts)
require.Empty(t, page.Accounts)
normalized := normalizeSQLWhitespace(capturedSQL)
require.Contains(t, normalized, "deleted_at IS NULL")
require.Contains(t, normalized, "status = 'active'")
// setup-token 的 access_token 同为 8h 短期令牌,必须与 oauth 一起纳入后台刷新候选
require.Contains(t, normalized, "type IN ('oauth', 'setup-token')")
require.Contains(t, normalized, "platform IN ('anthropic', 'openai', 'gemini', 'antigravity')")
require.Contains(t, normalized, "platform = ANY($1)")
require.NotContains(t, normalized, "platform IN ('anthropic'",
"candidate platforms must come from the refresher registry instead of a second hard-coded list")
require.Contains(t, normalized, "credentials ? 'refresh_token'")
require.Contains(t, normalized, "btrim(credentials->>'refresh_token') <> ''")
require.Contains(t, normalized, "temp_unschedulable_until > NOW()")
@@ -54,14 +290,52 @@ func TestAccountRepository_ListOAuthRefreshCandidates_SQLFilter(t *testing.T) {
"must use IS NOT TRUE so accounts with NULL temp_unschedulable_until are not silently excluded by PG 3-valued logic")
require.NotContains(t, normalized, "AND NOT (",
"plain NOT (...) excludes NULL temp_unschedulable_until rows (the common healthy case)")
require.Contains(t, normalized, "ORDER BY priority ASC, id ASC")
require.Contains(t, normalized, "id > $2")
require.Contains(t, normalized, "ORDER BY id ASC")
require.Contains(t, normalized, "LIMIT $3")
require.NotContains(t, normalized, "credentials->>'expires_at'")
require.Len(t, capturedArgs, 3)
require.Equal(t, int64(100), capturedArgs[1])
require.Equal(t, 200, capturedArgs[2])
valuer, ok := capturedArgs[0].(interface{ Value() (driver.Value, error) })
require.True(t, ok)
platforms, err := valuer.Value()
require.NoError(t, err)
require.Contains(t, platforms, service.PlatformGrok)
require.NoError(t, mock.ExpectationsWereMet())
}
func TestAccountRepository_ListOAuthRefreshCandidatePage_ReconciliationExcludesAPIKeys(t *testing.T) {
db, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherRegexp))
require.NoError(t, err)
defer func() { _ = db.Close() }()
var capturedSQL string
mock.ExpectQuery("SELECT id").WillReturnRows(sqlmock.NewRows([]string{"id"}))
repo := newAccountRepositoryWithSQL(nil, captureQuerySQL{db: db, captured: &capturedSQL}, nil)
page, err := repo.ListOAuthRefreshCandidatePage(context.Background(), service.OAuthRefreshPageOptions{
Platforms: []string{service.PlatformGrok},
AfterID: 0,
Limit: 50,
})
require.NoError(t, err)
require.Empty(t, page.Accounts)
normalized := normalizeSQLWhitespace(capturedSQL)
require.Contains(t, normalized, "type = 'oauth'")
require.NotContains(t, normalized, "type IN ('oauth', 'setup-token')")
require.NotContains(t, normalized, "type = 'api-key'")
require.NotContains(t, normalized, "credentials ? 'refresh_token'",
"reconciliation must be able to find structurally invalid OAuth rows")
require.Contains(t, normalized, "ORDER BY id ASC")
require.NoError(t, mock.ExpectationsWereMet())
}
type captureQuerySQL struct {
db *sql.DB
captured *string
args *[]any
}
func (c captureQuerySQL) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error) {
@@ -72,6 +346,9 @@ func (c captureQuerySQL) QueryContext(ctx context.Context, query string, args ..
if c.captured != nil {
*c.captured = query
}
if c.args != nil {
*c.args = append([]any(nil), args...)
}
return c.db.QueryContext(ctx, query, args...)
}
@@ -87,14 +364,20 @@ func (r rowsAffectedResult) RowsAffected() (int64, error) { return int64(r), nil
type recordingSQLExecutor struct {
result sql.Result
err error
afterExec func()
execQueries []string
execArgs [][]any
}
func (e *recordingSQLExecutor) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error) {
e.execQueries = append(e.execQueries, query)
e.execArgs = append(e.execArgs, append([]any(nil), args...))
if e.err != nil {
return nil, e.err
}
if e.afterExec != nil {
e.afterExec()
}
return e.result, nil
}
@@ -153,14 +153,29 @@ func grokOAuthStatusError(code, message string, resp *req.Response) error {
statusCode := http.StatusBadGateway
errorCode := code
upstreamStatus := 0
if resp != nil && resp.StatusCode == http.StatusForbidden {
statusCode = http.StatusForbidden
errorCode = "GROK_OAUTH_ENTITLEMENT_DENIED"
}
body := ""
if resp != nil {
upstreamStatus = resp.StatusCode
body = logredact.RedactText(resp.String())
if resp.StatusCode == http.StatusForbidden && grokOAuthHasExplicitEntitlementDenial(body) {
statusCode = http.StatusForbidden
errorCode = "GROK_OAUTH_ENTITLEMENT_DENIED"
}
}
return infraerrors.Newf(statusCode, errorCode, "%s: status %d, body: %s", message, upstreamStatus, body)
}
func grokOAuthHasExplicitEntitlementDenial(body string) bool {
lower := strings.ToLower(body)
compact := strings.NewReplacer(" ", "", "\n", "", "\r", "", "\t", "").Replace(lower)
for _, field := range []string{"error", "code", "reason"} {
for _, value := range []string{"access_denied", "entitlement_denied", "subscription_required", "no_active_subscription"} {
if strings.Contains(compact, `"`+field+`":"`+value+`"`) {
return true
}
}
}
return strings.Contains(lower, "entitlement denied") ||
strings.Contains(lower, "subscription required") ||
strings.Contains(lower, "no active grok subscription")
}
@@ -50,15 +50,7 @@ func TestGrokOAuthClientExchangeAndRefreshUseFormFields(t *testing.T) {
t.Setenv(xai.EnvTokenURL, server.URL)
client := NewGrokOAuthClient()
exchanged, err := client.ExchangeCode(
context.Background(),
"auth-code",
"verifier",
"http://127.0.0.1:56121/callback",
"",
"client-id",
)
exchanged, err := client.ExchangeCode(context.Background(), "auth-code", "verifier", "http://127.0.0.1:56121/callback", "", "client-id")
require.NoError(t, err)
require.Equal(t, "exchange-access", exchanged.AccessToken)
require.Equal(t, "exchange-refresh", exchanged.RefreshToken)
@@ -72,18 +64,30 @@ func TestGrokOAuthClientExchangeAndRefreshUseFormFields(t *testing.T) {
require.Equal(t, int64(7200), refreshed.ExpiresIn)
}
func TestGrokOAuthClientRefreshForbiddenClassifiesEntitlement(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusForbidden)
_, _ = w.Write([]byte(`{"error":"subscription required"}`))
}))
defer server.Close()
t.Setenv(xai.EnvTokenURL, server.URL)
func TestGrokOAuthClientRefreshForbiddenClassifiesOnlyExplicitEntitlement(t *testing.T) {
tests := []struct {
name string
body string
wantReason string
}{
{name: "explicit entitlement", body: `{"error":"access_denied"}`, wantReason: "GROK_OAUTH_ENTITLEMENT_DENIED"},
{name: "generic forbidden", body: `{"error":"forbidden"}`, wantReason: "GROK_OAUTH_TOKEN_REFRESH_FAILED"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusForbidden)
_, _ = w.Write([]byte(tt.body))
}))
defer server.Close()
t.Setenv(xai.EnvTokenURL, server.URL)
client := NewGrokOAuthClient()
_, err := client.RefreshToken(context.Background(), "refresh-token", "", "client-id")
require.Error(t, err)
require.Contains(t, strings.ToUpper(err.Error()), "GROK_OAUTH_ENTITLEMENT_DENIED")
client := NewGrokOAuthClient()
_, err := client.RefreshToken(context.Background(), "refresh-token", "", "client-id")
require.Error(t, err)
require.Contains(t, strings.ToUpper(err.Error()), tt.wantReason)
})
}
}
func TestGrokOAuthClientStatusErrorRedactsSensitiveResponseBody(t *testing.T) {
@@ -105,3 +109,13 @@ func TestGrokOAuthClientStatusErrorRedactsSensitiveResponseBody(t *testing.T) {
require.NotContains(t, errText, "refresh-secret")
require.NotContains(t, errText, "verifier-secret")
}
func TestGrokOAuthEntitlementDenialRequiresExplicitEvidence(t *testing.T) {
t.Parallel()
require.True(t, grokOAuthHasExplicitEntitlementDenial(`{"error":"access_denied"}`))
require.True(t, grokOAuthHasExplicitEntitlementDenial(`{"code":"entitlement_denied"}`))
require.True(t, grokOAuthHasExplicitEntitlementDenial(`{"message":"no active Grok subscription"}`))
require.False(t, grokOAuthHasExplicitEntitlementDenial(`{"error":"forbidden","message":"request forbidden"}`))
require.False(t, grokOAuthHasExplicitEntitlementDenial(`<html>403 Forbidden</html>`))
}
@@ -101,6 +101,40 @@ func TestBuildOpsErrorLogsWhere_CyberPolicyStatusExemption(t *testing.T) {
if strings.Contains(whereRecovered, "status_code") {
t.Fatalf("upstream phase with IncludeRecoveredUpstream must not add any status_code clause\nfull: %s", whereRecovered)
}
// account_auth uses the same explicit provider-health opt-in but remains a
// distinct phase from inference upstream errors.
whereAccountAuth, _ := buildOpsErrorLogsWhere(&service.OpsErrorLogFilter{Phase: "account_auth", IncludeRecoveredUpstream: true})
if strings.Contains(whereAccountAuth, "status_code") {
t.Fatalf("account_auth phase with IncludeRecoveredUpstream must expose recovered rows\nfull: %s", whereAccountAuth)
}
if !strings.Contains(whereAccountAuth, "e.error_phase = $") {
t.Fatalf("account_auth recovered filter must retain its explicit phase\nfull: %s", whereAccountAuth)
}
whereProviderHealth, _ := buildOpsErrorLogsWhere(&service.OpsErrorLogFilter{
ErrorPhasesAny: []string{"upstream", "account_auth"},
IncludeRecoveredUpstream: true,
})
if strings.Contains(whereProviderHealth, "status_code") {
t.Fatalf("provider-health ANY filter must expose recovered inference and credential rows\nfull: %s", whereProviderHealth)
}
if !strings.Contains(whereProviderHealth, "e.error_phase = ANY($") {
t.Fatalf("provider-health filter must preserve distinct phase values\nfull: %s", whereProviderHealth)
}
whereUserAccountAuth, _ := buildOpsErrorLogsWhere(&service.OpsErrorLogFilter{ErrorPhasesAny: []string{"account_auth"}})
if !strings.Contains(whereUserAccountAuth, "COALESCE(e.status_code, 0) >= 400") {
t.Fatalf("request-error account_auth filters must exclude recovered successes\nfull: %s", whereUserAccountAuth)
}
whereMixed, _ := buildOpsErrorLogsWhere(&service.OpsErrorLogFilter{
ErrorPhasesAny: []string{"account_auth", "request"},
IncludeRecoveredUpstream: true,
})
if !strings.Contains(whereMixed, "COALESCE(e.status_code, 0) >= 400") {
t.Fatalf("recovered opt-in must not bypass the guard for non-provider phases\nfull: %s", whereMixed)
}
}
func TestBuildOpsErrorLogsWhere_MatchDeletedKeyOwner(t *testing.T) {
+37 -5
View File
@@ -160,7 +160,7 @@ func opsInsertErrorLogArgs(input *service.OpsInsertErrorLogInput) []any {
opsNullString(input.ErrorBody),
opsNullString(input.ErrorSource),
opsNullString(input.ErrorOwner),
opsNullInt(input.UpstreamStatusCode),
opsNullableIntPointer(input.UpstreamStatusCode),
opsNullString(input.UpstreamErrorMessage),
opsNullString(input.UpstreamErrorDetail),
opsNullString(input.UpstreamErrorsJSON),
@@ -582,7 +582,7 @@ LIMIT 1`
s := clientIP.String
out.ClientIP = &s
}
if upstreamStatusCode.Valid && upstreamStatusCode.Int64 > 0 {
if upstreamStatusCode.Valid {
v := int(upstreamStatusCode.Int64)
out.UpstreamStatusCode = &v
}
@@ -978,13 +978,13 @@ func buildOpsErrorLogsWhere(filter *service.OpsErrorLogFilter) (string, []any) {
resolvedFilter = filter.Resolved
}
// Keep list endpoints scoped to client errors unless the caller explicitly opts
// into recovered upstream rows (Phase=="upstream" + IncludeRecoveredUpstream,
// ops 专用上游列表)。请求错误语义的端点即便过滤 phase=upstream 也保留该守卫。
// into recovered provider-health rows (upstream/account_auth). Request-error
// endpoints never set the opt-in and retain this guard.
// cyber_policy is exempt from the status >= 400 guard: streaming cyber hits arrive with
// status 200 (the SSE stream opened successfully before upstream returned response.failed),
// but they are always client-visible blocked requests that belong in admin + user error
// lists. Without the exemption the entire streaming-path cyber sink would be invisible.
if phaseFilter != "upstream" || filter == nil || !filter.IncludeRecoveredUpstream {
if !opsFilterIncludesRecoveredProviderRows(filter, phaseFilter) {
clauses = append(clauses, "(COALESCE(e.status_code, 0) >= 400 OR e.error_type = 'cyber_policy')")
}
@@ -1117,6 +1117,28 @@ func buildOpsErrorLogsWhere(filter *service.OpsErrorLogFilter) (string, []any) {
return "WHERE " + strings.Join(clauses, " AND "), args
}
func opsFilterIncludesRecoveredProviderRows(filter *service.OpsErrorLogFilter, phaseFilter string) bool {
if filter == nil || !filter.IncludeRecoveredUpstream {
return false
}
if phaseFilter != "" {
return phaseFilter == "upstream" || phaseFilter == "account_auth"
}
if len(filter.ErrorPhasesAny) == 0 {
return false
}
sawProviderPhase := false
for _, rawPhase := range filter.ErrorPhasesAny {
switch strings.TrimSpace(strings.ToLower(rawPhase)) {
case "upstream", "account_auth":
sawProviderPhase = true
default:
return false
}
}
return sawProviderPhase
}
func buildOpsSystemLogsWhere(filter *service.OpsSystemLogFilter) (string, []any, bool) {
clauses := make([]string, 0, 10)
args := make([]any, 0, 10)
@@ -1269,6 +1291,16 @@ func opsNullInt(v any) any {
}
}
// opsNullableIntPointer distinguishes an absent value from an explicitly
// observed zero. Credential-stage failures intentionally persist upstream
// status 0 because no inference request was sent.
func opsNullableIntPointer(v *int) any {
if v == nil {
return sql.NullInt64{}
}
return sql.NullInt64{Int64: int64(*v), Valid: true}
}
func opsNullInt16(v *int16) any {
if v == nil {
return sql.NullInt64{}
@@ -0,0 +1,37 @@
//go:build unit
package repository
import (
"database/sql"
"testing"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/stretchr/testify/require"
)
func TestOpsInsertErrorLogArgsPreservesExplicitZeroUpstreamStatus(t *testing.T) {
zero := 0
args := opsInsertErrorLogArgs(&service.OpsInsertErrorLogInput{UpstreamStatusCode: &zero})
require.Len(t, args, 41)
encoded, ok := args[27].(sql.NullInt64)
require.True(t, ok)
require.True(t, encoded.Valid)
require.Zero(t, encoded.Int64)
}
func TestOpsNullableIntPointerDistinguishesNilZeroAndStatus(t *testing.T) {
missing := opsNullableIntPointer(nil).(sql.NullInt64)
require.False(t, missing.Valid)
zeroValue := 0
zero := opsNullableIntPointer(&zeroValue).(sql.NullInt64)
require.True(t, zero.Valid)
require.Zero(t, zero.Int64)
statusValue := 503
status := opsNullableIntPointer(&statusValue).(sql.NullInt64)
require.True(t, status.Valid)
require.EqualValues(t, 503, status.Int64)
}
@@ -91,4 +91,21 @@ func TestGetErrorLogByID_DeletedKeyOwner(t *testing.T) {
require.Equal(t, "sk-valid", valid.APIKeyPrefix)
require.Empty(t, valid.AttemptedKeyPrefix, "attempted prefix and api key prefix are mutually exclusive")
require.Nil(t, valid.DeletedKeyOwnerUserID, "valid key error has no deleted owner")
// ── Case 4: account_auth with no inference attempt preserves explicit 0 ──
zero := 0
credentialFailureID, err := repo.InsertErrorLog(ctx, &service.OpsInsertErrorLogInput{
ErrorPhase: "account_auth",
ErrorType: "upstream_error",
Severity: "error",
StatusCode: 503,
UpstreamStatusCode: &zero,
CreatedAt: time.Now(),
})
require.NoError(t, err)
credentialFailure, err := repo.GetErrorLogByID(ctx, credentialFailureID)
require.NoError(t, err)
require.NotNil(t, credentialFailure.UpstreamStatusCode)
require.Zero(t, *credentialFailure.UpstreamStatusCode)
}
+287 -13
View File
@@ -2,6 +2,8 @@ package repository
import (
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"log/slog"
@@ -20,6 +22,8 @@ const (
schedulerActivePrefix = "sched:active:"
schedulerReadyPrefix = "sched:ready:"
schedulerVersionPrefix = "sched:ver:"
schedulerEpochPrefix = "sched:epoch:"
schedulerRetiredPrefix = "sched:retired:"
schedulerSnapshotPrefix = "sched:"
schedulerLockPrefix = "sched:lock:"
@@ -31,7 +35,116 @@ const (
snapshotGraceTTLSeconds = 60
)
const (
schedulerGroupLifecycleLockPrefix = "sched:group:lifecycle-lock:"
schedulerGroupLifecycleOwnerTokenBytes = 16
)
var (
// epoch 标识 bucket writer 的代际,retired key 是持久退休标记。
// Capture、allocate、activate 都在 Lua 内同时校验两者:-1 表示已退休,-2 表示 epoch 无效或与 token 代际不匹配;
// allocate 与 activate 的双重校验可拦截快照写入期间发生的 Retire。
// Retire 仅在首次退休时推进 epoch,Reopen 只清除标记并沿用该代际,因此重复调用保持幂等。
captureBucketWriteTokenScript = redis.NewScript(`
if redis.call('EXISTS', KEYS[2]) == 1 then
return -1
end
local currentEpoch = redis.call('GET', KEYS[1])
if currentEpoch == false then
redis.call('SET', KEYS[1], '1')
return 1
end
local parsedEpoch = tonumber(currentEpoch)
if parsedEpoch == nil or parsedEpoch < 1 then
return -2
end
return parsedEpoch
`)
allocateSnapshotVersionScript = redis.NewScript(`
if redis.call('EXISTS', KEYS[2]) == 1 then
return -1
end
local currentEpoch = tonumber(redis.call('GET', KEYS[1]))
local expectedEpoch = tonumber(ARGV[1])
if currentEpoch == nil or expectedEpoch == nil or currentEpoch ~= expectedEpoch then
return -2
end
return redis.call('INCR', KEYS[3])
`)
retireBucketScript = redis.NewScript(`
local retired = redis.call('GET', KEYS[2])
local currentEpoch = tonumber(redis.call('GET', KEYS[1])) or 0
if retired == false then
currentEpoch = currentEpoch + 1
if currentEpoch < 1 then
currentEpoch = 1
end
redis.call('SET', KEYS[1], tostring(currentEpoch))
redis.call('SET', KEYS[2], tostring(currentEpoch))
elseif currentEpoch < 1 then
currentEpoch = tonumber(retired) or 1
redis.call('SET', KEYS[1], tostring(currentEpoch))
end
redis.call('SREM', KEYS[3], ARGV[1])
local currentActive = redis.call('GET', KEYS[5])
if currentActive ~= false then
redis.call('EXPIRE', ARGV[2] .. currentActive, tonumber(ARGV[3]))
end
redis.call('DEL', KEYS[4], KEYS[5])
return currentEpoch
`)
reopenBucketScript = redis.NewScript(`
local currentEpochRaw = redis.call('GET', KEYS[1])
local currentEpoch = tonumber(currentEpochRaw)
local retiredEpochRaw = redis.call('GET', KEYS[2])
if retiredEpochRaw == false then
if currentEpochRaw == false then
redis.call('SET', KEYS[1], '1')
return 1
end
if currentEpoch == nil or currentEpoch < 1 then
return -2
end
return currentEpoch
end
local retiredEpoch = tonumber(retiredEpochRaw)
if retiredEpoch == nil or retiredEpoch < 1 then
return -2
end
if currentEpoch == nil or currentEpoch < retiredEpoch then
currentEpoch = retiredEpoch
end
redis.call('SET', KEYS[1], tostring(currentEpoch))
redis.call('DEL', KEYS[2])
redis.call('SREM', KEYS[3], ARGV[1])
local currentActive = redis.call('GET', KEYS[5])
if currentActive ~= false then
redis.call('EXPIRE', ARGV[2] .. currentActive, tonumber(ARGV[3]))
end
redis.call('DEL', KEYS[4], KEYS[5])
return currentEpoch
`)
// 释放租约必须先比较所有者令牌再删除,过期持有者的延迟释放不能误删继任租约。
releaseGroupLifecycleLeaseScript = redis.NewScript(`
if redis.call('GET', KEYS[1]) == ARGV[1] then
return redis.call('DEL', KEYS[1])
end
return 0
`)
// activateSnapshotScript 原子 CAS 切换快照版本。
// 仅当新版本号 >= 当前激活版本时才切换,防止并发写入导致版本回滚。
// 旧快照使用 EXPIRE 设置宽限期而非立即 DEL,避免与 reader 竞态。
@@ -40,13 +153,28 @@ var (
// KEYS[2] = readyKey (sched:ready:{bucket})
// KEYS[3] = bucketSetKey (sched:buckets)
// KEYS[4] = snapshotKey (新写入的快照 key)
// KEYS[5] = epochKey
// KEYS[6] = retiredKey
// ARGV[1] = 新版本号字符串
// ARGV[2] = bucket 字符串 (用于 SADD)
// ARGV[3] = 快照 key 前缀 (用于构造旧快照 key)
// ARGV[4] = 宽限期 TTL 秒数
// ARGV[5] = writer epoch
//
// 返回 1 = 已激活, 0 = 版本过旧未激活
activateSnapshotScript = redis.NewScript(`
if redis.call('EXISTS', KEYS[6]) == 1 then
redis.call('DEL', KEYS[4])
return -1
end
local currentEpoch = tonumber(redis.call('GET', KEYS[5]))
local expectedEpoch = tonumber(ARGV[5])
if currentEpoch == nil or expectedEpoch == nil or currentEpoch ~= expectedEpoch then
redis.call('DEL', KEYS[4])
return -2
end
local currentActive = redis.call('GET', KEYS[1])
local newVersion = tonumber(ARGV[1])
@@ -151,19 +279,139 @@ func (c *schedulerCache) GetSnapshot(ctx context.Context, bucket service.Schedul
return accounts, true, nil
}
func (c *schedulerCache) SetSnapshot(ctx context.Context, bucket service.SchedulerBucket, accounts []service.Account) error {
// Phase 1: 分配新版本号并写入快照数据。
// INCR 保证每个调用方获得唯一递增版本号。
// 写入的 snapshotKey 是新的版本化 key,reader 尚不知晓,因此无竞态。
versionKey := schedulerBucketKey(schedulerVersionPrefix, bucket)
version, err := c.rdb.Incr(ctx, versionKey).Result()
func (c *schedulerCache) CaptureBucketWriteToken(ctx context.Context, bucket service.SchedulerBucket) (service.SchedulerBucketWriteToken, error) {
result, err := captureBucketWriteTokenScript.Run(ctx, c.rdb, []string{
schedulerBucketKey(schedulerEpochPrefix, bucket),
schedulerBucketKey(schedulerRetiredPrefix, bucket),
}).Int64()
if err != nil {
return service.SchedulerBucketWriteToken{}, err
}
if err := schedulerBucketWriteResultError(result, bucket); err != nil {
return service.SchedulerBucketWriteToken{}, err
}
return service.SchedulerBucketWriteToken{Bucket: bucket, Epoch: result}, nil
}
func (c *schedulerCache) RetireBucket(ctx context.Context, bucket service.SchedulerBucket) error {
snapshotKeyPrefix := fmt.Sprintf("%s%d:%s:%s:v", schedulerSnapshotPrefix, bucket.GroupID, bucket.Platform, bucket.Mode)
result, err := retireBucketScript.Run(ctx, c.rdb, []string{
schedulerBucketKey(schedulerEpochPrefix, bucket),
schedulerBucketKey(schedulerRetiredPrefix, bucket),
schedulerBucketSetKey,
schedulerBucketKey(schedulerReadyPrefix, bucket),
schedulerBucketKey(schedulerActivePrefix, bucket),
}, bucket.String(), snapshotKeyPrefix, snapshotGraceTTLSeconds).Int64()
if err != nil {
return err
}
if result < 1 {
return fmt.Errorf("retire scheduler bucket %s returned invalid epoch %d", bucket.String(), result)
}
return nil
}
versionStr := strconv.FormatInt(version, 10)
snapshotKey := schedulerSnapshotKey(bucket, versionStr)
func (c *schedulerCache) ReopenBucket(ctx context.Context, bucket service.SchedulerBucket) (service.SchedulerBucketWriteToken, error) {
snapshotKeyPrefix := fmt.Sprintf("%s%d:%s:%s:v", schedulerSnapshotPrefix, bucket.GroupID, bucket.Platform, bucket.Mode)
result, err := reopenBucketScript.Run(ctx, c.rdb, []string{
schedulerBucketKey(schedulerEpochPrefix, bucket),
schedulerBucketKey(schedulerRetiredPrefix, bucket),
schedulerBucketSetKey,
schedulerBucketKey(schedulerReadyPrefix, bucket),
schedulerBucketKey(schedulerActivePrefix, bucket),
}, bucket.String(), snapshotKeyPrefix, snapshotGraceTTLSeconds).Int64()
if err != nil {
return service.SchedulerBucketWriteToken{}, err
}
if err := schedulerBucketWriteResultError(result, bucket); err != nil {
return service.SchedulerBucketWriteToken{}, err
}
return service.SchedulerBucketWriteToken{Bucket: bucket, Epoch: result}, nil
}
func (c *schedulerCache) TryAcquireGroupLifecycleLease(ctx context.Context, groupID int64, ttl time.Duration) (service.SchedulerGroupLifecycleLease, bool, error) {
if groupID <= 0 {
return service.SchedulerGroupLifecycleLease{}, false, fmt.Errorf("%w: group id must be positive", service.ErrSchedulerGroupLifecycleLeaseInvalid)
}
if ttl <= 0 {
return service.SchedulerGroupLifecycleLease{}, false, fmt.Errorf("%w: ttl must be positive", service.ErrSchedulerGroupLifecycleLeaseInvalid)
}
ownerToken, err := newSchedulerGroupLifecycleOwnerToken()
if err != nil {
return service.SchedulerGroupLifecycleLease{}, false, err
}
acquired, err := c.rdb.SetNX(ctx, schedulerGroupLifecycleLockKey(groupID), ownerToken, ttl).Result()
if err != nil {
return service.SchedulerGroupLifecycleLease{}, false, err
}
if !acquired {
return service.SchedulerGroupLifecycleLease{}, false, nil
}
return service.SchedulerGroupLifecycleLease{GroupID: groupID, OwnerToken: ownerToken}, true, nil
}
func (c *schedulerCache) ReleaseGroupLifecycleLease(ctx context.Context, lease service.SchedulerGroupLifecycleLease) error {
if !lease.ValidFor(lease.GroupID) {
return service.ErrSchedulerGroupLifecycleLeaseInvalid
}
result, err := releaseGroupLifecycleLeaseScript.Run(
ctx,
c.rdb,
[]string{schedulerGroupLifecycleLockKey(lease.GroupID)},
lease.OwnerToken,
).Int64()
if err != nil {
return err
}
if result == 0 {
return fmt.Errorf("%w: group=%d", service.ErrSchedulerGroupLifecycleLeaseLost, lease.GroupID)
}
if result != 1 {
return fmt.Errorf("release scheduler group lifecycle lease returned %d", result)
}
return nil
}
func newSchedulerGroupLifecycleOwnerToken() (string, error) {
raw := make([]byte, schedulerGroupLifecycleOwnerTokenBytes)
if _, err := rand.Read(raw); err != nil {
return "", fmt.Errorf("generate scheduler group lifecycle owner token: %w", err)
}
return hex.EncodeToString(raw), nil
}
func (c *schedulerCache) SetSnapshot(ctx context.Context, bucket service.SchedulerBucket, token service.SchedulerBucketWriteToken, accounts []service.Account) error {
if !token.ValidFor(bucket) {
return fmt.Errorf("%w: bucket=%s", service.ErrSchedulerBucketWriteFenced, bucket.String())
}
// 分配版本与激活指针是两个 fencing 边界;中间写入的数据只有通过第二次校验才能发布。
version, err := c.allocateSnapshotVersion(ctx, bucket, token)
if err != nil {
return err
}
if err := c.writeSnapshotVersion(ctx, bucket, version, accounts); err != nil {
return err
}
return c.activateSnapshotVersion(ctx, bucket, token, version)
}
func (c *schedulerCache) allocateSnapshotVersion(ctx context.Context, bucket service.SchedulerBucket, token service.SchedulerBucketWriteToken) (string, error) {
result, err := allocateSnapshotVersionScript.Run(ctx, c.rdb, []string{
schedulerBucketKey(schedulerEpochPrefix, bucket),
schedulerBucketKey(schedulerRetiredPrefix, bucket),
schedulerBucketKey(schedulerVersionPrefix, bucket),
}, token.Epoch).Int64()
if err != nil {
return "", err
}
if err := schedulerBucketWriteResultError(result, bucket); err != nil {
return "", err
}
return strconv.FormatInt(result, 10), nil
}
func (c *schedulerCache) writeSnapshotVersion(ctx context.Context, bucket service.SchedulerBucket, version string, accounts []service.Account) error {
snapshotKey := schedulerSnapshotKey(bucket, version)
cacheableAccounts, err := c.writeAccounts(ctx, accounts)
if err != nil {
return err
@@ -191,7 +439,12 @@ func (c *schedulerCache) SetSnapshot(ctx context.Context, bucket service.Schedul
}
}
// Phase 2: 原子 CAS 激活版本。
return nil
}
func (c *schedulerCache) activateSnapshotVersion(ctx context.Context, bucket service.SchedulerBucket, token service.SchedulerBucketWriteToken, version string) error {
snapshotKey := schedulerSnapshotKey(bucket, version)
// Phase 2: 原子 CAS 切换版本,同时再次校验退休状态与 writer epoch。
// Lua 脚本保证:仅当新版本 >= 当前激活版本时才切换 active 指针,
// 防止并发写入导致版本回滚。
// 旧快照使用 EXPIRE 宽限期而非立即 DEL,避免 reader 竞态。
@@ -199,15 +452,32 @@ func (c *schedulerCache) SetSnapshot(ctx context.Context, bucket service.Schedul
readyKey := schedulerBucketKey(schedulerReadyPrefix, bucket)
snapshotKeyPrefix := fmt.Sprintf("%s%d:%s:%s:v", schedulerSnapshotPrefix, bucket.GroupID, bucket.Platform, bucket.Mode)
keys := []string{activeKey, readyKey, schedulerBucketSetKey, snapshotKey}
args := []any{versionStr, bucket.String(), snapshotKeyPrefix, snapshotGraceTTLSeconds}
keys := []string{
activeKey,
readyKey,
schedulerBucketSetKey,
snapshotKey,
schedulerBucketKey(schedulerEpochPrefix, bucket),
schedulerBucketKey(schedulerRetiredPrefix, bucket),
}
args := []any{version, bucket.String(), snapshotKeyPrefix, snapshotGraceTTLSeconds, token.Epoch}
_, err = activateSnapshotScript.Run(ctx, c.rdb, keys, args...).Result()
result, err := activateSnapshotScript.Run(ctx, c.rdb, keys, args...).Int64()
if err != nil {
return err
}
return schedulerBucketWriteResultError(result, bucket)
}
return nil
func schedulerBucketWriteResultError(result int64, bucket service.SchedulerBucket) error {
switch result {
case -1:
return fmt.Errorf("%w: bucket=%s", service.ErrSchedulerBucketRetired, bucket.String())
case -2:
return fmt.Errorf("%w: bucket=%s", service.ErrSchedulerBucketWriteFenced, bucket.String())
default:
return nil
}
}
func (c *schedulerCache) GetAccount(ctx context.Context, accountID int64) (*service.Account, error) {
@@ -336,6 +606,10 @@ func schedulerBucketKey(prefix string, bucket service.SchedulerBucket) string {
return fmt.Sprintf("%s%d:%s:%s", prefix, bucket.GroupID, bucket.Platform, bucket.Mode)
}
func schedulerGroupLifecycleLockKey(groupID int64) string {
return schedulerGroupLifecycleLockPrefix + strconv.FormatInt(groupID, 10)
}
func schedulerSnapshotKey(bucket service.SchedulerBucket, version string) string {
return fmt.Sprintf("%s%d:%s:%s:v%s", schedulerSnapshotPrefix, bucket.GroupID, bucket.Platform, bucket.Mode, version)
}
@@ -67,7 +67,9 @@ func TestSchedulerCacheSnapshotUsesSlimMetadataButKeepsFullAccount(t *testing.T)
},
}
require.NoError(t, cache.SetSnapshot(ctx, bucket, []service.Account{account}))
token, err := cache.CaptureBucketWriteToken(ctx, bucket)
require.NoError(t, err)
require.NoError(t, cache.SetSnapshot(ctx, bucket, token, []service.Account{account}))
snapshot, hit, err := cache.GetSnapshot(ctx, bucket)
require.NoError(t, err)
@@ -102,3 +104,73 @@ func TestSchedulerCacheSnapshotUsesSlimMetadataButKeepsFullAccount(t *testing.T)
require.Len(t, full.AccountGroups, 1)
require.NotNil(t, full.AccountGroups[0].Group)
}
func TestSchedulerCacheRetireAndReopenFencesOldEpochIntegration(t *testing.T) {
ctx := context.Background()
rdb := testRedis(t)
cache := NewSchedulerCache(rdb)
bucket := service.SchedulerBucket{GroupID: 77, Platform: service.PlatformAntigravity, Mode: service.SchedulerModeForced}
account := service.Account{ID: 7701, Platform: service.PlatformAntigravity, Type: service.AccountTypeOAuth}
oldToken, err := cache.CaptureBucketWriteToken(ctx, bucket)
require.NoError(t, err)
require.NoError(t, cache.SetSnapshot(ctx, bucket, oldToken, []service.Account{account}))
require.NoError(t, cache.RetireBucket(ctx, bucket))
require.NoError(t, cache.RetireBucket(ctx, bucket))
_, hit, err := cache.GetSnapshot(ctx, bucket)
require.NoError(t, err)
require.False(t, hit)
_, err = cache.CaptureBucketWriteToken(ctx, bucket)
require.ErrorIs(t, err, service.ErrSchedulerBucketRetired)
require.ErrorIs(t, cache.SetSnapshot(ctx, bucket, oldToken, []service.Account{account}), service.ErrSchedulerBucketRetired)
newToken, err := cache.ReopenBucket(ctx, bucket)
require.NoError(t, err)
require.Greater(t, newToken.Epoch, oldToken.Epoch)
require.ErrorIs(t, cache.SetSnapshot(ctx, bucket, oldToken, []service.Account{account}), service.ErrSchedulerBucketWriteFenced)
require.NoError(t, cache.SetSnapshot(ctx, bucket, newToken, []service.Account{account}))
snapshot, hit, err := cache.GetSnapshot(ctx, bucket)
require.NoError(t, err)
require.True(t, hit)
require.Len(t, snapshot, 1)
require.Equal(t, account.ID, snapshot[0].ID)
}
func TestSchedulerCacheGroupLifecycleLeaseOwnerAndTTLIntegration(t *testing.T) {
ctx := context.Background()
rdb := testRedis(t)
cache := NewSchedulerCache(rdb)
const groupID int64 = 78
const ttl = 500 * time.Millisecond
first, acquired, err := cache.TryAcquireGroupLifecycleLease(ctx, groupID, ttl)
require.NoError(t, err)
require.True(t, acquired)
pttl, err := rdb.PTTL(ctx, schedulerGroupLifecycleLockKey(groupID)).Result()
require.NoError(t, err)
require.Positive(t, pttl)
require.LessOrEqual(t, pttl, ttl)
var second service.SchedulerGroupLifecycleLease
require.Eventually(t, func() bool {
var acquireErr error
second, acquired, acquireErr = cache.TryAcquireGroupLifecycleLease(ctx, groupID, time.Minute)
return acquireErr == nil && acquired
}, 5*time.Second, 20*time.Millisecond)
require.NotEqual(t, first.OwnerToken, second.OwnerToken)
require.ErrorIs(t, cache.ReleaseGroupLifecycleLease(ctx, first), service.ErrSchedulerGroupLifecycleLeaseLost)
_, acquired, err = cache.TryAcquireGroupLifecycleLease(ctx, groupID, time.Minute)
require.NoError(t, err)
require.False(t, acquired, "a stale release must not delete the successor lease")
require.NoError(t, cache.ReleaseGroupLifecycleLease(ctx, second))
require.ErrorIs(t, cache.ReleaseGroupLifecycleLease(ctx, second), service.ErrSchedulerGroupLifecycleLeaseLost)
third, acquired, err := cache.TryAcquireGroupLifecycleLease(ctx, groupID, time.Minute)
require.NoError(t, err)
require.True(t, acquired)
require.True(t, third.ValidFor(groupID))
require.NoError(t, cache.ReleaseGroupLifecycleLease(ctx, third))
}
@@ -4,6 +4,8 @@ package repository
import (
"context"
"encoding/hex"
"strings"
"testing"
"time"
@@ -14,13 +16,18 @@ import (
)
func newSchedulerCacheUnit(t *testing.T) *schedulerCache {
cache, _ := newSchedulerCacheUnitWithRedis(t)
return cache
}
func newSchedulerCacheUnitWithRedis(t *testing.T) (*schedulerCache, *miniredis.Miniredis) {
t.Helper()
mr := miniredis.RunT(t)
rdb := redis.NewClient(&redis.Options{Addr: mr.Addr()})
t.Cleanup(func() { _ = rdb.Close() })
cache, ok := newSchedulerCacheWithChunkSizes(rdb, defaultSchedulerSnapshotMGetChunkSize, defaultSchedulerSnapshotWriteChunkSize).(*schedulerCache)
require.True(t, ok)
return cache
return cache, mr
}
func TestSchedulerCacheWriteAccountsSkipsUnencodableTimes(t *testing.T) {
@@ -229,3 +236,378 @@ func TestBuildSchedulerMetadataAccount_KeepsSparkShadowRoutingIdentity(t *testin
require.Equal(t, map[string]any{"gpt-5.4": "gpt-5.4-openai-compact"}, got.Credentials["compact_model_mapping"])
require.Nil(t, got.Credentials["access_token"])
}
func TestSchedulerCacheBucketRetirementFencesWritersAndReopen(t *testing.T) {
ctx := context.Background()
cache, mr := newSchedulerCacheUnitWithRedis(t)
bucket := service.SchedulerBucket{GroupID: 41, Platform: service.PlatformOpenAI, Mode: service.SchedulerModeSingle}
otherBucket := service.SchedulerBucket{GroupID: 42, Platform: service.PlatformOpenAI, Mode: service.SchedulerModeSingle}
account := service.Account{ID: 4101, Platform: service.PlatformOpenAI, Type: service.AccountTypeAPIKey}
token, err := cache.CaptureBucketWriteToken(ctx, bucket)
require.NoError(t, err)
require.True(t, token.ValidFor(bucket))
require.NoError(t, cache.SetSnapshot(ctx, bucket, token, []service.Account{account}))
// A token is bound to the full bucket identity, not just an epoch number.
err = cache.SetSnapshot(ctx, otherBucket, token, []service.Account{account})
require.ErrorIs(t, err, service.ErrSchedulerBucketWriteFenced)
_, err = cache.rdb.Get(ctx, schedulerBucketKey(schedulerVersionPrefix, otherBucket)).Result()
require.ErrorIs(t, err, redis.Nil)
otherAccount := service.Account{ID: 4201, Platform: service.PlatformOpenAI, Type: service.AccountTypeAPIKey}
otherToken, err := cache.CaptureBucketWriteToken(ctx, otherBucket)
require.NoError(t, err)
require.NoError(t, cache.SetSnapshot(ctx, otherBucket, otherToken, []service.Account{otherAccount}))
otherEpoch := otherToken.Epoch
activeVersion, err := cache.rdb.Get(ctx, schedulerBucketKey(schedulerActivePrefix, bucket)).Result()
require.NoError(t, err)
require.NoError(t, cache.RetireBucket(ctx, bucket))
retiredEpoch, err := cache.rdb.Get(ctx, schedulerBucketKey(schedulerEpochPrefix, bucket)).Int64()
require.NoError(t, err)
require.Greater(t, retiredEpoch, token.Epoch)
// Retirement is idempotent and does not advance the epoch again.
require.NoError(t, cache.RetireBucket(ctx, bucket))
retiredEpochAgain, err := cache.rdb.Get(ctx, schedulerBucketKey(schedulerEpochPrefix, bucket)).Int64()
require.NoError(t, err)
require.Equal(t, retiredEpoch, retiredEpochAgain)
// New readers miss because ready/active were removed atomically. A reader that
// captured activeVersion before retirement may still finish against that version.
_, hit, err := cache.GetSnapshot(ctx, bucket)
require.NoError(t, err)
require.False(t, hit)
ids, err := cache.rdb.ZRange(ctx, schedulerSnapshotKey(bucket, activeVersion), 0, -1).Result()
require.NoError(t, err)
require.Equal(t, []string{"4101"}, ids)
ttl, err := cache.rdb.TTL(ctx, schedulerSnapshotKey(bucket, activeVersion)).Result()
require.NoError(t, err)
require.Positive(t, ttl)
require.LessOrEqual(t, ttl, time.Duration(snapshotGraceTTLSeconds)*time.Second)
buckets, err := cache.ListBuckets(ctx)
require.NoError(t, err)
require.NotContains(t, buckets, bucket)
require.Contains(t, buckets, otherBucket)
otherSnapshot, otherHit, err := cache.GetSnapshot(ctx, otherBucket)
require.NoError(t, err)
require.True(t, otherHit)
require.Len(t, otherSnapshot, 1)
require.Equal(t, otherAccount.ID, otherSnapshot[0].ID)
otherEpochAfter, err := cache.rdb.Get(ctx, schedulerBucketKey(schedulerEpochPrefix, otherBucket)).Int64()
require.NoError(t, err)
require.Equal(t, otherEpoch, otherEpochAfter)
_, err = cache.CaptureBucketWriteToken(ctx, bucket)
require.ErrorIs(t, err, service.ErrSchedulerBucketRetired)
versionBeforeRejectedWrite, err := cache.rdb.Get(ctx, schedulerBucketKey(schedulerVersionPrefix, bucket)).Int64()
require.NoError(t, err)
err = cache.SetSnapshot(ctx, bucket, token, []service.Account{account})
require.ErrorIs(t, err, service.ErrSchedulerBucketRetired)
versionAfterRejectedWrite, err := cache.rdb.Get(ctx, schedulerBucketKey(schedulerVersionPrefix, bucket)).Int64()
require.NoError(t, err)
require.Equal(t, versionBeforeRejectedWrite, versionAfterRejectedWrite, "fenced writers must not allocate a new version")
retired, err := cache.rdb.Exists(ctx, schedulerBucketKey(schedulerRetiredPrefix, bucket)).Result()
require.NoError(t, err)
require.EqualValues(t, 1, retired, "ordinary writers must never clear the tombstone")
mr.FastForward(time.Duration(snapshotGraceTTLSeconds+1) * time.Second)
exists, err := cache.rdb.Exists(ctx, schedulerSnapshotKey(bucket, activeVersion)).Result()
require.NoError(t, err)
require.Zero(t, exists, "retired active snapshot must expire after the in-flight grace period")
newToken, err := cache.ReopenBucket(ctx, bucket)
require.NoError(t, err)
require.True(t, newToken.ValidFor(bucket))
require.Equal(t, retiredEpoch, newToken.Epoch)
reopenedAgain, err := cache.ReopenBucket(ctx, bucket)
require.NoError(t, err)
require.Equal(t, newToken, reopenedAgain, "reopen must be idempotent within one retirement generation")
err = cache.SetSnapshot(ctx, bucket, token, []service.Account{account})
require.ErrorIs(t, err, service.ErrSchedulerBucketWriteFenced)
require.NoError(t, cache.SetSnapshot(ctx, bucket, newToken, []service.Account{account}))
reopenedWhileOpen, err := cache.ReopenBucket(ctx, bucket)
require.NoError(t, err)
require.Equal(t, newToken, reopenedWhileOpen)
snapshot, hit, err := cache.GetSnapshot(ctx, bucket)
require.NoError(t, err)
require.True(t, hit)
require.Len(t, snapshot, 1)
require.Equal(t, account.ID, snapshot[0].ID)
}
func TestSchedulerCacheActivationIsFencedAfterRetire(t *testing.T) {
ctx := context.Background()
cache := newSchedulerCacheUnit(t)
bucket := service.SchedulerBucket{GroupID: 51, Platform: service.PlatformAnthropic, Mode: service.SchedulerModeMixed}
account := service.Account{ID: 5101, Platform: service.PlatformAnthropic, Type: service.AccountTypeAPIKey}
token, err := cache.CaptureBucketWriteToken(ctx, bucket)
require.NoError(t, err)
version, err := cache.allocateSnapshotVersion(ctx, bucket, token)
require.NoError(t, err)
require.NoError(t, cache.writeSnapshotVersion(ctx, bucket, version, []service.Account{account}))
// Deterministic race C: retirement and authoritative reopen both happen after
// INCR/write but before the old writer activates.
require.NoError(t, cache.RetireBucket(ctx, bucket))
_, err = cache.ReopenBucket(ctx, bucket)
require.NoError(t, err)
err = cache.activateSnapshotVersion(ctx, bucket, token, version)
require.ErrorIs(t, err, service.ErrSchedulerBucketWriteFenced)
exists, err := cache.rdb.Exists(ctx, schedulerSnapshotKey(bucket, version)).Result()
require.NoError(t, err)
require.Zero(t, exists, "fenced activation must delete its unpublished snapshot")
exists, err = cache.rdb.Exists(
ctx,
schedulerBucketKey(schedulerReadyPrefix, bucket),
schedulerBucketKey(schedulerActivePrefix, bucket),
).Result()
require.NoError(t, err)
require.Zero(t, exists)
buckets, err := cache.ListBuckets(ctx)
require.NoError(t, err)
require.NotContains(t, buckets, bucket)
}
func TestSchedulerCacheConcurrentReopenReturnsSameToken(t *testing.T) {
ctx := context.Background()
cache := newSchedulerCacheUnit(t)
bucket := service.SchedulerBucket{GroupID: 53, Platform: service.PlatformOpenAI, Mode: service.SchedulerModeForced}
account := service.Account{ID: 5301, Platform: service.PlatformOpenAI, Type: service.AccountTypeAPIKey}
oldToken, err := cache.CaptureBucketWriteToken(ctx, bucket)
require.NoError(t, err)
require.NoError(t, cache.RetireBucket(ctx, bucket))
type reopenResult struct {
token service.SchedulerBucketWriteToken
err error
}
start := make(chan struct{})
results := make(chan reopenResult, 2)
for range 2 {
go func() {
<-start
token, err := cache.ReopenBucket(ctx, bucket)
results <- reopenResult{token: token, err: err}
}()
}
close(start)
first := <-results
second := <-results
require.NoError(t, first.err)
require.NoError(t, second.err)
require.Equal(t, first.token, second.token)
require.Greater(t, first.token.Epoch, oldToken.Epoch)
require.ErrorIs(t, cache.SetSnapshot(ctx, bucket, oldToken, []service.Account{account}), service.ErrSchedulerBucketWriteFenced)
require.NoError(t, cache.SetSnapshot(ctx, bucket, first.token, []service.Account{account}))
}
func TestSchedulerCacheReopenExpiresPreviousActiveSnapshot(t *testing.T) {
ctx := context.Background()
cache, mr := newSchedulerCacheUnitWithRedis(t)
bucket := service.SchedulerBucket{GroupID: 52, Platform: service.PlatformGemini, Mode: service.SchedulerModeForced}
account := service.Account{ID: 5201, Platform: service.PlatformGemini, Type: service.AccountTypeAPIKey}
oldToken, err := cache.CaptureBucketWriteToken(ctx, bucket)
require.NoError(t, err)
require.NoError(t, cache.SetSnapshot(ctx, bucket, oldToken, []service.Account{account}))
oldVersion, err := cache.rdb.Get(ctx, schedulerBucketKey(schedulerActivePrefix, bucket)).Result()
require.NoError(t, err)
retiredEpoch := oldToken.Epoch + 1
require.NoError(t, cache.rdb.Set(ctx, schedulerBucketKey(schedulerEpochPrefix, bucket), retiredEpoch, 0).Err())
require.NoError(t, cache.rdb.Set(ctx, schedulerBucketKey(schedulerRetiredPrefix, bucket), retiredEpoch, 0).Err())
newToken, err := cache.ReopenBucket(ctx, bucket)
require.NoError(t, err)
require.Equal(t, retiredEpoch, newToken.Epoch)
_, hit, err := cache.GetSnapshot(ctx, bucket)
require.NoError(t, err)
require.False(t, hit)
ttl, err := cache.rdb.TTL(ctx, schedulerSnapshotKey(bucket, oldVersion)).Result()
require.NoError(t, err)
require.Positive(t, ttl)
require.LessOrEqual(t, ttl, time.Duration(snapshotGraceTTLSeconds)*time.Second)
require.ErrorIs(t, cache.SetSnapshot(ctx, bucket, oldToken, []service.Account{account}), service.ErrSchedulerBucketWriteFenced)
mr.FastForward(time.Duration(snapshotGraceTTLSeconds+1) * time.Second)
exists, err := cache.rdb.Exists(ctx, schedulerSnapshotKey(bucket, oldVersion)).Result()
require.NoError(t, err)
require.Zero(t, exists)
require.NoError(t, cache.SetSnapshot(ctx, bucket, newToken, []service.Account{account}))
}
func TestSchedulerCacheGroupLifecycleLeaseConcurrentAcquireSingleOwner(t *testing.T) {
ctx := context.Background()
cache := newSchedulerCacheUnit(t)
const groupID int64 = 71
type result struct {
lease service.SchedulerGroupLifecycleLease
acquired bool
err error
}
start := make(chan struct{})
results := make(chan result, 32)
for range 32 {
go func() {
<-start
lease, acquired, err := cache.TryAcquireGroupLifecycleLease(ctx, groupID, time.Minute)
results <- result{lease: lease, acquired: acquired, err: err}
}()
}
close(start)
var owner service.SchedulerGroupLifecycleLease
acquiredCount := 0
for range 32 {
got := <-results
require.NoError(t, got.err)
if got.acquired {
acquiredCount++
owner = got.lease
require.True(t, got.lease.ValidFor(groupID))
} else {
require.Equal(t, service.SchedulerGroupLifecycleLease{}, got.lease)
}
}
require.Equal(t, 1, acquiredCount)
require.Len(t, owner.OwnerToken, schedulerGroupLifecycleOwnerTokenBytes*2)
require.Equal(t, strings.ToLower(owner.OwnerToken), owner.OwnerToken)
decodedOwner, err := hex.DecodeString(owner.OwnerToken)
require.NoError(t, err)
require.Len(t, decodedOwner, schedulerGroupLifecycleOwnerTokenBytes)
require.NoError(t, cache.ReleaseGroupLifecycleLease(ctx, owner))
next, acquired, err := cache.TryAcquireGroupLifecycleLease(ctx, groupID, time.Minute)
require.NoError(t, err)
require.True(t, acquired)
require.True(t, next.ValidFor(groupID))
require.NotEqual(t, owner.OwnerToken, next.OwnerToken)
require.NoError(t, cache.ReleaseGroupLifecycleLease(ctx, next))
}
func TestSchedulerCacheGroupLifecycleLeaseStaleReleaseCannotDeleteSuccessor(t *testing.T) {
ctx := context.Background()
cache, mr := newSchedulerCacheUnitWithRedis(t)
const groupID int64 = 72
const ttl = time.Minute
first, acquired, err := cache.TryAcquireGroupLifecycleLease(ctx, groupID, ttl)
require.NoError(t, err)
require.True(t, acquired)
mr.FastForward(ttl + time.Second)
second, acquired, err := cache.TryAcquireGroupLifecycleLease(ctx, groupID, ttl)
require.NoError(t, err)
require.True(t, acquired)
require.NotEqual(t, first.OwnerToken, second.OwnerToken)
require.ErrorIs(t, cache.ReleaseGroupLifecycleLease(ctx, first), service.ErrSchedulerGroupLifecycleLeaseLost)
owner, err := cache.rdb.Get(ctx, schedulerGroupLifecycleLockKey(groupID)).Result()
require.NoError(t, err)
require.Equal(t, second.OwnerToken, owner)
_, acquired, err = cache.TryAcquireGroupLifecycleLease(ctx, groupID, ttl)
require.NoError(t, err)
require.False(t, acquired)
require.NoError(t, cache.ReleaseGroupLifecycleLease(ctx, second))
require.ErrorIs(t, cache.ReleaseGroupLifecycleLease(ctx, second), service.ErrSchedulerGroupLifecycleLeaseLost)
}
func TestSchedulerCacheGroupLifecycleLeaseExpiredReleaseIsLost(t *testing.T) {
ctx := context.Background()
cache, mr := newSchedulerCacheUnitWithRedis(t)
const groupID int64 = 73
const ttl = time.Minute
lease, acquired, err := cache.TryAcquireGroupLifecycleLease(ctx, groupID, ttl)
require.NoError(t, err)
require.True(t, acquired)
mr.FastForward(ttl + time.Second)
require.ErrorIs(t, cache.ReleaseGroupLifecycleLease(ctx, lease), service.ErrSchedulerGroupLifecycleLeaseLost)
}
func TestSchedulerCacheGroupLifecycleLeaseWrongOwnerAndCrossGroupAreLost(t *testing.T) {
ctx := context.Background()
cache := newSchedulerCacheUnit(t)
const firstGroupID int64 = 74
const secondGroupID int64 = 75
first, acquired, err := cache.TryAcquireGroupLifecycleLease(ctx, firstGroupID, time.Minute)
require.NoError(t, err)
require.True(t, acquired)
second, acquired, err := cache.TryAcquireGroupLifecycleLease(ctx, secondGroupID, time.Minute)
require.NoError(t, err)
require.True(t, acquired, "different groups must acquire independently")
require.NotEqual(t, first.OwnerToken, second.OwnerToken)
wrongOwner := first
wrongOwner.OwnerToken = strings.Repeat("0", schedulerGroupLifecycleOwnerTokenBytes*2)
if wrongOwner.OwnerToken == first.OwnerToken {
wrongOwner.OwnerToken = strings.Repeat("1", schedulerGroupLifecycleOwnerTokenBytes*2)
}
require.ErrorIs(t, cache.ReleaseGroupLifecycleLease(ctx, wrongOwner), service.ErrSchedulerGroupLifecycleLeaseLost)
crossGroup := first
crossGroup.GroupID = secondGroupID
require.ErrorIs(t, cache.ReleaseGroupLifecycleLease(ctx, crossGroup), service.ErrSchedulerGroupLifecycleLeaseLost)
firstOwner, err := cache.rdb.Get(ctx, schedulerGroupLifecycleLockKey(firstGroupID)).Result()
require.NoError(t, err)
require.Equal(t, first.OwnerToken, firstOwner)
secondOwner, err := cache.rdb.Get(ctx, schedulerGroupLifecycleLockKey(secondGroupID)).Result()
require.NoError(t, err)
require.Equal(t, second.OwnerToken, secondOwner)
require.NoError(t, cache.ReleaseGroupLifecycleLease(ctx, first))
require.NoError(t, cache.ReleaseGroupLifecycleLease(ctx, second))
}
func TestSchedulerCacheGroupLifecycleLeaseCanceledContextFailsClosed(t *testing.T) {
cache := newSchedulerCacheUnit(t)
canceledCtx, cancel := context.WithCancel(context.Background())
cancel()
lease, acquired, err := cache.TryAcquireGroupLifecycleLease(canceledCtx, 76, time.Minute)
require.ErrorIs(t, err, context.Canceled)
require.False(t, acquired)
require.Equal(t, service.SchedulerGroupLifecycleLease{}, lease)
ctx := context.Background()
lease, acquired, err = cache.TryAcquireGroupLifecycleLease(ctx, 76, time.Minute)
require.NoError(t, err)
require.True(t, acquired)
require.ErrorIs(t, cache.ReleaseGroupLifecycleLease(canceledCtx, lease), context.Canceled)
owner, err := cache.rdb.Get(ctx, schedulerGroupLifecycleLockKey(lease.GroupID)).Result()
require.NoError(t, err)
require.Equal(t, lease.OwnerToken, owner)
require.NoError(t, cache.ReleaseGroupLifecycleLease(ctx, lease))
}
func TestSchedulerCacheGroupLifecycleLeaseRejectsInvalidInput(t *testing.T) {
ctx := context.Background()
cache := newSchedulerCacheUnit(t)
lease, acquired, err := cache.TryAcquireGroupLifecycleLease(ctx, 0, time.Minute)
require.ErrorIs(t, err, service.ErrSchedulerGroupLifecycleLeaseInvalid)
require.False(t, acquired)
require.Equal(t, service.SchedulerGroupLifecycleLease{}, lease)
lease, acquired, err = cache.TryAcquireGroupLifecycleLease(ctx, 73, 0)
require.ErrorIs(t, err, service.ErrSchedulerGroupLifecycleLeaseInvalid)
require.False(t, acquired)
require.Equal(t, service.SchedulerGroupLifecycleLease{}, lease)
canceledCtx, cancel := context.WithCancel(ctx)
cancel()
require.ErrorIs(t, cache.ReleaseGroupLifecycleLease(canceledCtx, service.SchedulerGroupLifecycleLease{}), service.ErrSchedulerGroupLifecycleLeaseInvalid)
keys, err := cache.rdb.DBSize(ctx).Result()
require.NoError(t, err)
require.Zero(t, keys)
}
+1
View File
@@ -68,6 +68,7 @@ var ProviderSet = wire.NewSet(
NewAPIKeyRepository,
NewGroupRepository,
NewAccountRepository,
NewAdminAccountRepository,
NewScheduledTestPlanRepository, // 定时测试计划仓储
NewScheduledTestResultRepository, // 定时测试结果仓储
NewProxyRepository,
@@ -1721,6 +1721,10 @@ func (s *stubAccountRepo) Create(ctx context.Context, account *service.Account)
return errors.New("not implemented")
}
func (s *stubAccountRepo) CreateWithAccountGroups(ctx context.Context, account *service.Account, groups []service.AccountGroup) error {
return errors.New("not implemented")
}
func (s *stubAccountRepo) GetByID(ctx context.Context, id int64) (*service.Account, error) {
return nil, service.ErrAccountNotFound
}
+1 -1
View File
@@ -52,7 +52,7 @@ func CORS(cfg config.CORSConfig) gin.HandlerFunc {
}
allowHeaders := []string{
"Content-Type", "Content-Length", "Accept-Encoding", "X-CSRF-Token", "Authorization",
"accept", "origin", "Cache-Control", "X-Requested-With", "X-API-Key", "X-Admin-UI-Request",
"accept", "origin", "Cache-Control", "X-Requested-With", "X-API-Key", "X-Admin-UI-Request", "X-User-UI-Request",
}
// OpenAI Node SDK 会发送 x-stainless-* 请求头,需在 CORS 中显式放行。
openAIProperties := []string{
@@ -104,6 +104,7 @@ func TestCORS_AllowedOrigin_HasAllowHeaders(t *testing.T) {
assert.NotEmpty(t, w.Header().Get("Access-Control-Allow-Headers"),
"允许的 origin 应收到 Allow-Headers")
assert.Contains(t, w.Header().Get("Access-Control-Allow-Headers"), "X-Admin-UI-Request")
assert.Contains(t, w.Header().Get("Access-Control-Allow-Headers"), "X-User-UI-Request")
assert.NotEmpty(t, w.Header().Get("Access-Control-Allow-Methods"),
"允许的 origin 应收到 Allow-Methods")
assert.Contains(t, w.Header().Get("Access-Control-Expose-Headers"), "Server-Timing")
@@ -25,7 +25,7 @@ func (w *serverTimingResponseWriter) Unwrap() http.ResponseWriter {
return w.ResponseWriter
}
// ServerTiming collects timing only for requests made by the Admin web UI.
// ServerTiming collects timing for Admin and User web UI requests when enabled.
func ServerTiming(enabled bool) gin.HandlerFunc {
if !enabled {
return func(c *gin.Context) {
@@ -33,7 +33,7 @@ func ServerTiming(enabled bool) gin.HandlerFunc {
}
}
return func(c *gin.Context) {
if !isAdminUIRequest(c) || c.Request == nil {
if !shouldCollectServerTiming(c) || c.Request == nil {
c.Next()
return
}
@@ -85,13 +85,19 @@ func (w *serverTimingResponseWriter) finalize() {
})
}
// ServerTimingHeaderValue returns a timing value only for an authenticated admin.
// ServerTimingHeaderValue returns a timing value only for authorized UI scopes.
// Admins may receive timing for any collected Admin/User UI request. Non-admin
// authenticated users may receive timing only on allowlisted user-facing paths.
// X-User-UI-Request is a scope signal and is never used as authorization.
func ServerTimingHeaderValue(c *gin.Context) string {
if c == nil || c.Request == nil {
return ""
}
role, ok := GetUserRoleFromContext(c)
if !ok || role != "admin" {
if !ok || role == "" {
return ""
}
if role != "admin" && !isUserTimingPath(c.Request.URL.Path) {
return ""
}
return servertiming.HeaderValue(c.Request.Context(), time.Now(), responseCacheStatus(c.Writer.Header()))
@@ -106,6 +112,10 @@ func ServerTimingResponseHeader(c *gin.Context) http.Header {
return http.Header{servertiming.HeaderName: []string{value}}
}
func shouldCollectServerTiming(c *gin.Context) bool {
return isAdminUIRequest(c) || isUserUIRequest(c)
}
func isAdminUIRequest(c *gin.Context) bool {
if c == nil || c.Request == nil || c.Request.URL == nil {
return false
@@ -117,6 +127,69 @@ func isAdminUIRequest(c *gin.Context) bool {
return path == "/api/v1/admin" || strings.HasPrefix(path, "/api/v1/admin/")
}
func isUserUIRequest(c *gin.Context) bool {
if c == nil || c.Request == nil || c.Request.URL == nil {
return false
}
if strings.TrimSpace(c.GetHeader(servertiming.UserUIHeader)) == "1" {
return true
}
return isUserTimingPath(c.Request.URL.Path)
}
// isUserTimingPath reports whether the path is a user-facing web API that may
// emit Server-Timing for authenticated callers (excluding public payment routes).
func isUserTimingPath(path string) bool {
path = strings.TrimSpace(path)
if path == "" {
return false
}
const prefix = "/api/v1"
if !strings.HasPrefix(path, prefix) {
return false
}
rest := strings.TrimPrefix(path, prefix)
if rest == "" {
return false
}
if !strings.HasPrefix(rest, "/") {
rest = "/" + rest
}
switch {
case rest == "/auth/me",
rest == "/auth/revoke-all-sessions",
rest == "/auth/oauth/bind-token":
return true
case rest == "/user", strings.HasPrefix(rest, "/user/"):
return true
case rest == "/keys", strings.HasPrefix(rest, "/keys/"):
return true
case rest == "/groups/available", rest == "/groups/rates":
return true
case rest == "/channels/available":
return true
case rest == "/usage", strings.HasPrefix(rest, "/usage/"):
return true
case rest == "/announcements", strings.HasPrefix(rest, "/announcements/"):
return true
case rest == "/redeem", strings.HasPrefix(rest, "/redeem/"):
return true
case rest == "/subscriptions", strings.HasPrefix(rest, "/subscriptions/"):
return true
case rest == "/channel-monitors", strings.HasPrefix(rest, "/channel-monitors/"):
return true
case strings.HasPrefix(rest, "/payment/"):
// Exclude public and webhook payment surfaces.
if strings.HasPrefix(rest, "/payment/public") || strings.HasPrefix(rest, "/payment/webhook") {
return false
}
return true
default:
return false
}
}
func responseCacheStatus(header http.Header) string {
for _, name := range []string{snapshotCacheHeader, usageCacheHeader} {
switch strings.ToLower(strings.TrimSpace(header.Get(name))) {
@@ -15,7 +15,8 @@ func runServerTimingRequest(
t *testing.T,
enabled bool,
path string,
marker string,
adminMarker string,
userMarker string,
role string,
handler gin.HandlerFunc,
) *httptest.ResponseRecorder {
@@ -32,8 +33,11 @@ func runServerTimingRequest(
recorder := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodGet, path, nil)
if marker != "" {
request.Header.Set(servertiming.AdminUIHeader, marker)
if adminMarker != "" {
request.Header.Set(servertiming.AdminUIHeader, adminMarker)
}
if userMarker != "" {
request.Header.Set(servertiming.UserUIHeader, userMarker)
}
engine.ServeHTTP(recorder, request)
return recorder
@@ -41,26 +45,36 @@ func runServerTimingRequest(
func TestServerTimingScopesAndRoleGate(t *testing.T) {
tests := []struct {
name string
enabled bool
path string
marker string
role string
wantHeader bool
name string
enabled bool
path string
adminMarker string
userMarker string
role string
wantHeader bool
}{
{name: "disabled", enabled: false, path: "/api/v1/admin/users", role: "admin"},
{name: "admin API path", enabled: true, path: "/api/v1/admin/users", role: "admin", wantHeader: true},
{name: "shared API marked by admin UI", enabled: true, path: "/api/v1/groups/available", marker: "1", role: "admin", wantHeader: true},
{name: "non admin role", enabled: true, path: "/api/v1/groups/available", marker: "1", role: "user"},
{name: "unauthenticated public request", enabled: true, path: "/api/v1/settings/public", marker: "1"},
{name: "unmarked shared API", enabled: true, path: "/api/v1/groups/available", role: "admin"},
{name: "invalid marker", enabled: true, path: "/api/v1/groups/available", marker: "true", role: "admin"},
{name: "shared API marked by admin UI", enabled: true, path: "/api/v1/groups/available", adminMarker: "1", role: "admin", wantHeader: true},
{name: "user role on allowlisted path", enabled: true, path: "/api/v1/groups/available", role: "user", wantHeader: true},
{name: "user role with user UI marker on allowlisted path", enabled: true, path: "/api/v1/keys", userMarker: "1", role: "user", wantHeader: true},
{name: "user role cannot use admin marker on non-user path", enabled: true, path: "/api/v1/settings/public", adminMarker: "1", role: "user"},
{name: "user marker alone does not authorize non-user path", enabled: true, path: "/api/v1/settings/public", userMarker: "1", role: "user"},
{name: "unauthenticated public request", enabled: true, path: "/api/v1/settings/public", adminMarker: "1"},
{name: "unauthenticated user path", enabled: true, path: "/api/v1/keys"},
{name: "unmarked shared API still scopes by path for admin", enabled: true, path: "/api/v1/groups/available", role: "admin", wantHeader: true},
{name: "invalid admin marker on non-scoped path", enabled: true, path: "/api/v1/settings/public", adminMarker: "true", role: "admin"},
{name: "admin prefix boundary", enabled: true, path: "/api/v1/administrator", role: "admin"},
{name: "auth me path", enabled: true, path: "/api/v1/auth/me", role: "user", wantHeader: true},
{name: "payment user path", enabled: true, path: "/api/v1/payment/plans", role: "user", wantHeader: true},
{name: "payment public excluded", enabled: true, path: "/api/v1/payment/public/orders/verify", userMarker: "1", role: "user"},
{name: "payment webhook excluded", enabled: true, path: "/api/v1/payment/webhook/stripe", userMarker: "1", role: "user"},
{name: "channel monitors path", enabled: true, path: "/api/v1/channel-monitors/1/status", role: "user", wantHeader: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
recorder := runServerTimingRequest(t, tt.enabled, tt.path, tt.marker, tt.role, func(c *gin.Context) {
recorder := runServerTimingRequest(t, tt.enabled, tt.path, tt.adminMarker, tt.userMarker, tt.role, func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"ok": true})
})
header := recorder.Header().Get(servertiming.HeaderName)
@@ -77,9 +91,49 @@ func TestServerTimingScopesAndRoleGate(t *testing.T) {
}
}
func TestIsUserTimingPath(t *testing.T) {
tests := []struct {
path string
want bool
}{
{"/api/v1/auth/me", true},
{"/api/v1/auth/revoke-all-sessions", true},
{"/api/v1/auth/oauth/bind-token", true},
{"/api/v1/auth/login", false},
{"/api/v1/user", true},
{"/api/v1/user/profile", true},
{"/api/v1/user/totp/status", true},
{"/api/v1/keys", true},
{"/api/v1/keys/12", true},
{"/api/v1/groups/available", true},
{"/api/v1/groups/rates", true},
{"/api/v1/groups", false},
{"/api/v1/channels/available", true},
{"/api/v1/channels", false},
{"/api/v1/usage/stats", true},
{"/api/v1/announcements", true},
{"/api/v1/redeem/history", true},
{"/api/v1/subscriptions/active", true},
{"/api/v1/channel-monitors", true},
{"/api/v1/payment/config", true},
{"/api/v1/payment/orders/my", true},
{"/api/v1/payment/public/orders/verify", false},
{"/api/v1/payment/webhook/easypay", false},
{"/api/v1/admin/users", false},
{"/api/v1/settings/public", false},
}
for _, tt := range tests {
t.Run(tt.path, func(t *testing.T) {
if got := isUserTimingPath(tt.path); got != tt.want {
t.Fatalf("isUserTimingPath(%q) = %v, want %v", tt.path, got, tt.want)
}
})
}
}
func TestServerTimingCollectorIsRequestScoped(t *testing.T) {
active := false
recorder := runServerTimingRequest(t, true, "/api/v1/keys", "1", "admin", func(c *gin.Context) {
recorder := runServerTimingRequest(t, true, "/api/v1/keys", "1", "", "admin", func(c *gin.Context) {
active = servertiming.Active(c.Request.Context())
c.Status(http.StatusNoContent)
})
@@ -91,8 +145,24 @@ func TestServerTimingCollectorIsRequestScoped(t *testing.T) {
}
}
func TestServerTimingCollectorForUserUIMarker(t *testing.T) {
active := false
// Use a non-allowlisted path so collection depends on the user UI marker.
recorder := runServerTimingRequest(t, true, "/api/v1/settings/public", "", "1", "admin", func(c *gin.Context) {
active = servertiming.Active(c.Request.Context())
c.JSON(http.StatusOK, gin.H{"ok": true})
})
if !active {
t.Fatal("collector was not attached for user UI marker")
}
// Admin role may emit even when the path is not user-allowlisted.
if recorder.Header().Get(servertiming.HeaderName) == "" {
t.Fatal("admin timing header missing for user-UI-marked request")
}
}
func TestServerTimingFinalizesBeforeEarlyCommit(t *testing.T) {
recorder := runServerTimingRequest(t, true, "/api/v1/admin/stream", "", "admin", func(c *gin.Context) {
recorder := runServerTimingRequest(t, true, "/api/v1/admin/stream", "", "", "admin", func(c *gin.Context) {
c.Status(http.StatusAccepted)
c.Writer.WriteHeaderNow()
})
@@ -102,7 +172,7 @@ func TestServerTimingFinalizesBeforeEarlyCommit(t *testing.T) {
}
func TestServerTimingFinalizesOnFlush(t *testing.T) {
recorder := runServerTimingRequest(t, true, "/api/v1/admin/export", "", "admin", func(c *gin.Context) {
recorder := runServerTimingRequest(t, true, "/api/v1/admin/export", "", "", "admin", func(c *gin.Context) {
c.Writer.Flush()
})
if got := recorder.Header().Get(servertiming.HeaderName); got == "" {
@@ -120,7 +190,7 @@ func TestServerTimingStatusResponses(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
recorder := runServerTimingRequest(t, true, "/api/v1/admin/test", "", "admin", func(c *gin.Context) {
recorder := runServerTimingRequest(t, true, "/api/v1/admin/test", "", "", "admin", func(c *gin.Context) {
c.Status(tt.status)
})
if recorder.Code != tt.status {
@@ -156,7 +226,7 @@ func TestServerTimingCacheOutcome(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
recorder := runServerTimingRequest(t, true, "/api/v1/admin/dashboard", "", "admin", func(c *gin.Context) {
recorder := runServerTimingRequest(t, true, "/api/v1/admin/dashboard", "", "", "admin", func(c *gin.Context) {
c.Header(tt.headerName, tt.value)
c.JSON(http.StatusOK, gin.H{"ok": true})
})
+2
View File
@@ -297,6 +297,7 @@ func registerAccountRoutes(admin *gin.RouterGroup, h *handler.Handlers) {
accounts.GET("", h.Admin.Account.List)
accounts.GET("/:id", h.Admin.Account.GetByID)
accounts.POST("", h.Admin.Account.Create)
accounts.POST("/:id/duplicate", h.Admin.Account.Duplicate)
accounts.POST("/check-mixed-channel", h.Admin.Account.CheckMixedChannel)
accounts.POST("/import/codex-session", h.Admin.Account.ImportCodexSession)
accounts.POST("/sync/crs", h.Admin.Account.SyncFromCRS)
@@ -400,6 +401,7 @@ func registerGrokOAuthRoutes(admin *gin.RouterGroup, h *handler.Handlers) {
grok.POST("/oauth/refresh-token", h.Admin.GrokOAuth.RefreshToken)
grok.POST("/oauth/create-from-oauth", h.Admin.GrokOAuth.CreateAccountFromOAuth)
grok.POST("/sso-to-oauth", h.Admin.GrokOAuth.CreateAccountsFromSSO)
grok.POST("/oauth/reconcile", h.Admin.GrokOAuth.ReconcileOAuthAccounts)
grok.POST("/accounts/:id/refresh", h.Admin.GrokOAuth.RefreshAccountToken)
grok.GET("/accounts/:id/quota", h.Admin.GrokOAuth.QueryQuota)
grok.POST("/accounts/:id/reset-quota", h.Admin.GrokOAuth.ResetQuota)
+9 -7
View File
@@ -42,6 +42,13 @@ func RegisterGatewayRoutes(
isOpenAIGatewayPlatform := func(c *gin.Context) bool {
return getGroupPlatform(c) == service.PlatformOpenAI
}
modelsHandler := func(c *gin.Context) {
if isOpenAIGatewayPlatform(c) && c.Query("client_version") != "" {
h.OpenAIGateway.CodexModels(c)
return
}
h.Gateway.Models(c)
}
imagesHandler := func(c *gin.Context) {
switch getGroupPlatform(c) {
case service.PlatformOpenAI:
@@ -140,13 +147,7 @@ func RegisterGatewayRoutes(
// Codex CLI / Codex app refresh their model picker from the provider's
// /models endpoint with a client_version query and expect the ChatGPT
// Codex manifest format; other clients keep the OpenAI-style list.
gateway.GET("/models", func(c *gin.Context) {
if isOpenAIGatewayPlatform(c) && c.Query("client_version") != "" {
h.OpenAIGateway.CodexModels(c)
return
}
h.Gateway.Models(c)
})
gateway.GET("/models", modelsHandler)
gateway.GET("/usage", h.Gateway.Usage)
// OpenAI Responses API: auto-route based on group platform
gateway.POST("/responses", func(c *gin.Context) {
@@ -235,6 +236,7 @@ func RegisterGatewayRoutes(
r.GET("/responses", bodyLimit, clientRequestID, opsErrorLogger, endpointNorm, gin.HandlerFunc(apiKeyAuth), requireGroupAnthropic, func(c *gin.Context) {
h.OpenAIGateway.ResponsesWebSocket(c)
})
r.GET("/models", bodyLimit, clientRequestID, opsErrorLogger, endpointNorm, gin.HandlerFunc(apiKeyAuth), requireGroupAnthropic, modelsHandler)
codexDirect := r.Group("/backend-api/codex")
codexDirect.Use(bodyLimit, clientRequestID, opsErrorLogger, endpointNorm, gin.HandlerFunc(apiKeyAuth), requireGroupAnthropic)
{
@@ -10,13 +10,15 @@ import (
func TestGatewayRoutesCodexModelsManifestPathIsRegistered(t *testing.T) {
router := newGatewayRoutesTestRouter()
registered := make(map[string]bool)
registered := make(map[string]string)
for _, route := range router.Routes() {
if route.Method == http.MethodGet {
registered[route.Path] = true
registered[route.Path] = route.Handler
}
}
require.True(t, registered["/backend-api/codex/models"], "GET /backend-api/codex/models should be registered")
require.True(t, registered["/v1/models"], "GET /v1/models should be registered")
require.NotEmpty(t, registered["/backend-api/codex/models"], "GET /backend-api/codex/models should be registered")
require.NotEmpty(t, registered["/v1/models"], "GET /v1/models should be registered")
require.NotEmpty(t, registered["/models"], "GET /models should be registered")
require.Equal(t, registered["/v1/models"], registered["/models"], "root alias should use the same platform-aware handler")
}
+10 -54
View File
@@ -6,7 +6,6 @@ import (
"errors"
"hash/fnv"
"log/slog"
"net/url"
"reflect"
"sort"
"strconv"
@@ -1268,16 +1267,13 @@ func (a *Account) GetGrokBaseURL() string {
if !a.IsGrok() {
return ""
}
baseURL := a.GetCredential("base_url")
if a.IsGrokOAuth() {
if strings.TrimSpace(baseURL) == "" || isOfficialGrokAPIBaseURL(baseURL) {
return xai.DefaultCLIBaseURL
}
if _, err := xai.ValidateTrustedBaseURL(baseURL); err == nil {
return baseURL
}
// OAuth bearer credentials are subscription credentials and may only be
// sent to the supported CLI gateway. Stored base_url values and unsafe
// development overrides apply exclusively to API-key accounts.
return xai.DefaultCLIBaseURL
}
baseURL := a.GetCredential("base_url")
if baseURL != "" {
return baseURL
}
@@ -1286,57 +1282,17 @@ func (a *Account) GetGrokBaseURL() string {
// GetGrokMediaBaseURL selects the upstream used by Grok Imagine APIs.
//
// OAuth text requests need the CLI subscription proxy, but that proxy has a
// smaller request-body limit than the official Imagine API. Media requests can
// contain large base64 inputs, so default OAuth accounts must use api.x.ai.
// API-key accounts and explicit unsafe development overrides retain their
// configured base URL.
// OAuth media credentials have the same trust boundary as OAuth text traffic:
// they are pinned to the supported CLI gateway even for large request bodies.
// API-key accounts retain their configured public/custom upstream behavior.
func (a *Account) GetGrokMediaBaseURL() string {
if !a.IsGrok() {
return ""
}
if !a.IsGrokOAuth() {
return a.GetGrokBaseURL()
if a.IsGrokOAuth() {
return xai.DefaultCLIBaseURL
}
baseURL := a.GetCredential("base_url")
if strings.TrimSpace(baseURL) == "" || isOfficialGrokAPIBaseURL(baseURL) || isOfficialGrokCLIBaseURL(baseURL) {
return xai.DefaultBaseURL
}
if _, err := xai.ValidateTrustedBaseURL(baseURL); err == nil {
return baseURL
}
return xai.DefaultBaseURL
}
func isOfficialGrokAPIBaseURL(raw string) bool {
return isOfficialGrokBaseURL(raw, xai.DefaultBaseURL)
}
func isOfficialGrokCLIBaseURL(raw string) bool {
return isOfficialGrokBaseURL(raw, xai.DefaultCLIBaseURL)
}
func isOfficialGrokBaseURL(raw, expected string) bool {
parsed, err := url.Parse(strings.TrimSpace(raw))
if err != nil || parsed == nil || parsed.Opaque != "" || parsed.User != nil || parsed.RawQuery != "" || parsed.Fragment != "" {
return false
}
defaultURL, err := url.Parse(expected)
if err != nil {
return false
}
if !strings.EqualFold(parsed.Scheme, defaultURL.Scheme) || !strings.EqualFold(parsed.Hostname(), defaultURL.Hostname()) {
return false
}
if port := parsed.Port(); port != "" {
portNumber, err := strconv.Atoi(port)
if err != nil || portNumber != 443 {
return false
}
}
path := strings.TrimRight(parsed.Path, "/")
return path == "" || path == strings.TrimRight(defaultURL.Path, "/")
return a.GetGrokBaseURL()
}
func (a *Account) GetGrokAccessToken() string {
@@ -255,7 +255,7 @@ func TestGetGrokBaseURLUsesSubscriptionProxyForOAuth(t *testing.T) {
expected: xai.DefaultCLIBaseURL,
},
{
name: "oauth non-default API port remains an explicit override",
name: "oauth non-default API port remains pinned to CLI proxy",
account: Account{
Type: AccountTypeOAuth,
Platform: PlatformGrok,
@@ -263,7 +263,7 @@ func TestGetGrokBaseURLUsesSubscriptionProxyForOAuth(t *testing.T) {
"base_url": "https://api.x.ai:8443/v1",
},
},
expected: "https://api.x.ai:8443/v1",
expected: xai.DefaultCLIBaseURL,
},
{
name: "oauth explicit custom base_url stays pinned to CLI proxy by default",
@@ -294,7 +294,7 @@ func TestGetGrokBaseURLUsesSubscriptionProxyForOAuth(t *testing.T) {
}
}
func TestGetGrokBaseURLAllowsExplicitOAuthOverrideWhenUnsafeOverridesEnabled(t *testing.T) {
func TestGetGrokBaseURLPinsOAuthWhenUnsafeOverridesEnabled(t *testing.T) {
t.Setenv(xai.EnvAllowUnsafeURLOverrides, "true")
account := Account{
Type: AccountTypeOAuth,
@@ -304,26 +304,26 @@ func TestGetGrokBaseURLAllowsExplicitOAuthOverrideWhenUnsafeOverridesEnabled(t *
},
}
require.Equal(t, "https://custom.example.com/v1", account.GetGrokBaseURL())
require.Equal(t, xai.DefaultCLIBaseURL, account.GetGrokBaseURL())
}
func TestGetGrokMediaBaseURLSeparatesOAuthMediaFromCLIProxy(t *testing.T) {
func TestGetGrokMediaBaseURLPinsOAuthMediaToCLIProxy(t *testing.T) {
tests := []struct {
name string
account Account
expected string
}{
{
name: "oauth without base_url uses official media API",
name: "oauth without base_url uses CLI subscription proxy",
account: Account{
Type: AccountTypeOAuth,
Platform: PlatformGrok,
Credentials: map[string]any{},
},
expected: xai.DefaultBaseURL,
expected: xai.DefaultCLIBaseURL,
},
{
name: "oauth stored CLI proxy uses official media API",
name: "oauth stored CLI proxy stays on CLI subscription proxy",
account: Account{
Type: AccountTypeOAuth,
Platform: PlatformGrok,
@@ -331,10 +331,10 @@ func TestGetGrokMediaBaseURLSeparatesOAuthMediaFromCLIProxy(t *testing.T) {
"base_url": xai.DefaultCLIBaseURL,
},
},
expected: xai.DefaultBaseURL,
expected: xai.DefaultCLIBaseURL,
},
{
name: "oauth stored CLI proxy variant uses official media API",
name: "oauth stored CLI proxy variant is canonicalized to CLI proxy",
account: Account{
Type: AccountTypeOAuth,
Platform: PlatformGrok,
@@ -342,10 +342,10 @@ func TestGetGrokMediaBaseURLSeparatesOAuthMediaFromCLIProxy(t *testing.T) {
"base_url": "HTTPS://CLI-CHAT-PROXY.GROK.COM:443/%76%31/",
},
},
expected: xai.DefaultBaseURL,
expected: xai.DefaultCLIBaseURL,
},
{
name: "oauth legacy official API remains on official media API",
name: "oauth legacy official API is pinned to CLI proxy",
account: Account{
Type: AccountTypeOAuth,
Platform: PlatformGrok,
@@ -353,10 +353,10 @@ func TestGetGrokMediaBaseURLSeparatesOAuthMediaFromCLIProxy(t *testing.T) {
"base_url": xai.DefaultBaseURL,
},
},
expected: xai.DefaultBaseURL,
expected: xai.DefaultCLIBaseURL,
},
{
name: "oauth untrusted custom base_url is pinned to official media API",
name: "oauth untrusted custom base_url is pinned to CLI proxy",
account: Account{
Type: AccountTypeOAuth,
Platform: PlatformGrok,
@@ -364,7 +364,7 @@ func TestGetGrokMediaBaseURLSeparatesOAuthMediaFromCLIProxy(t *testing.T) {
"base_url": "https://custom.example.com/v1",
},
},
expected: xai.DefaultBaseURL,
expected: xai.DefaultCLIBaseURL,
},
{
name: "API key retains its configured media API",
@@ -395,7 +395,7 @@ func TestGetGrokMediaBaseURLSeparatesOAuthMediaFromCLIProxy(t *testing.T) {
}
}
func TestGetGrokMediaBaseURLAllowsExplicitOAuthOverrideWhenUnsafeOverridesEnabled(t *testing.T) {
func TestGetGrokMediaBaseURLPinsOAuthWhenUnsafeOverridesEnabled(t *testing.T) {
t.Setenv(xai.EnvAllowUnsafeURLOverrides, "true")
account := Account{
Type: AccountTypeOAuth,
@@ -405,5 +405,5 @@ func TestGetGrokMediaBaseURLAllowsExplicitOAuthOverrideWhenUnsafeOverridesEnable
},
}
require.Equal(t, "https://custom.example.com/v1", account.GetGrokMediaBaseURL())
require.Equal(t, xai.DefaultCLIBaseURL, account.GetGrokMediaBaseURL())
}
@@ -4,7 +4,7 @@ package service
// dto 层做响应脱敏、service 层做更新合并都引用此清单——新增凭证类型时务必同步。
var SensitiveCredentialKeys = []string{
// OAuth
"access_token", "refresh_token", "id_token",
"access_token", "refresh_token", "id_token", "agent_private_key",
// API Key 类
"api_key", "session_key", "cookie",
// 云服务凭据
+42 -1
View File
@@ -18,6 +18,35 @@ var (
const AccountListGroupUngrouped int64 = -1
const AccountPrivacyModeUnsetFilter = "__unset__"
// OAuthRefreshPageOptions describes one bounded, cursor-stable scan of OAuth
// accounts. Candidate platforms are supplied by TokenRefreshService's refresher
// registry so repository eligibility cannot drift from registered providers.
type OAuthRefreshPageOptions struct {
Platforms []string
AfterID int64
Limit int
ActiveOnly bool
IncludeSetupToken bool
RequireRefreshToken bool
ExcludeRetryCooldown bool
}
// OAuthRefreshCandidatePage keeps cursor metadata from the raw SQL ID page.
// Hydration may legitimately lose a concurrently deleted row, but callers can
// still advance past the raw page without truncating or duplicating the scan.
type OAuthRefreshCandidatePage struct {
Accounts []Account
NextAfterID int64
HasMore bool
}
// OAuthRefreshCandidatePager is intentionally narrower than AccountRepository.
// Production refresh cycles fail closed when the repository does not implement
// this bounded contract instead of silently falling back to an unpaged scan.
type OAuthRefreshCandidatePager interface {
ListOAuthRefreshCandidatePage(ctx context.Context, options OAuthRefreshPageOptions) (*OAuthRefreshCandidatePage, error)
}
type AccountRepository interface {
Create(ctx context.Context, account *Account) error
GetByID(ctx context.Context, id int64) (*Account, error)
@@ -44,7 +73,6 @@ type AccountRepository interface {
ListAllWithFilters(ctx context.Context, platform, accountType, status, search string, groupID int64, privacyMode string) ([]Account, error)
ListByGroup(ctx context.Context, groupID int64) ([]Account, error)
ListActive(ctx context.Context) ([]Account, error)
ListOAuthRefreshCandidates(ctx context.Context) ([]Account, error)
ListByPlatform(ctx context.Context, platform string) ([]Account, error)
UpdateLastUsed(ctx context.Context, id int64) error
@@ -90,6 +118,19 @@ type AccountRepository interface {
ListShadowsByParent(ctx context.Context, parentID int64) ([]*Account, error)
}
type AccountDuplicateRepository interface {
// CreateWithAccountGroups atomically persists an account, its exact group priorities,
// and the scheduler outbox event for the new routing snapshot.
CreateWithAccountGroups(ctx context.Context, account *Account, groups []AccountGroup) error
}
// AdminAccountRepository makes the account-duplication write capability an explicit
// construction dependency without forcing read-only gateway test doubles to implement it.
type AdminAccountRepository interface {
AccountRepository
AccountDuplicateRepository
}
// AccountBulkUpdate describes the fields that can be updated in a bulk operation.
// Nil pointers mean "do not change".
type AccountBulkUpdate struct {
@@ -65,6 +65,13 @@ func tryModelFilePricing(billingService *BillingService, model string, tokens Us
if err != nil || pricing == nil {
return nil
}
if billingService.shouldApplySessionLongContextPricing(tokens, pricing) {
breakdown, err := billingService.CalculateCost(model, tokens, 1)
if err != nil || breakdown == nil || breakdown.TotalCost <= 0 {
return nil
}
return &breakdown.TotalCost
}
cost := float64(tokens.InputTokens)*pricing.InputPricePerToken +
float64(tokens.OutputTokens)*pricing.OutputPricePerToken +
float64(tokens.CacheCreationTokens)*pricing.CacheCreationPricePerToken +
@@ -459,6 +459,26 @@ func TestTryModelFilePricing_Success(t *testing.T) {
require.InDelta(t, 0.2, *result, 1e-12)
}
func TestTryModelFilePricing_AppliesLongContextPricing(t *testing.T) {
bs := newTestBillingServiceWithPrices(map[string]*ModelPricing{
"gpt-5.6-sol": {
InputPricePerToken: 0.001,
OutputPricePerToken: 0.002,
CacheReadPricePerToken: 0.0001,
LongContextInputThreshold: 100,
LongContextInputMultiplier: 2,
LongContextOutputMultiplier: 1.5,
},
})
tokens := UsageTokens{InputTokens: 101, OutputTokens: 10, CacheReadTokens: 5}
result := tryModelFilePricing(bs, "gpt-5.6-sol", tokens)
require.NotNil(t, result)
// Input and cache-read use the 2x input tier; output uses the 1.5x tier.
require.InDelta(t, 0.233, *result, 1e-12)
}
func TestTryModelFilePricing_PricingNotFound(t *testing.T) {
// "nonexistent-model" does not match any fallback pattern
bs := newTestBillingServiceWithPrices(map[string]*ModelPricing{})
+116 -21
View File
@@ -15,6 +15,7 @@ import (
"net/http/httptest"
"regexp"
"strings"
"sync"
"time"
"github.com/Wei-Shaw/sub2api/internal/config"
@@ -72,6 +73,8 @@ type AccountTestService struct {
httpUpstream HTTPUpstream
cfg *config.Config
tlsFPProfileService *TLSFingerprintProfileService
agentIdentityTaskMu sync.Mutex
agentIdentityWS agentIdentityWSConnectionInvalidator
}
// NewAccountTestService creates a new AccountTestService
@@ -544,9 +547,11 @@ func (s *AccountTestService) testOpenAIAccountConnection(c *gin.Context, account
if credentialAccount.IsOAuth() {
isOAuth = true
// OAuth - use Bearer token with ChatGPT internal API
authToken = credentialAccount.GetOpenAIAccessToken()
if authToken == "" {
// Agent Identity signs each request and does not retain the OAuth token.
if !credentialAccount.IsOpenAIAgentIdentity() {
authToken = credentialAccount.GetOpenAIAccessToken()
}
if authToken == "" && !credentialAccount.IsOpenAIAgentIdentity() {
return s.sendErrorAndEnd(c, "No access token available")
}
@@ -591,8 +596,11 @@ func (s *AccountTestService) testOpenAIAccountConnection(c *gin.Context, account
payload := createOpenAITestPayload(upstreamTestModelID, isOAuth)
payloadBytes, _ := json.Marshal(payload)
// Send test_start event
s.sendEvent(c, TestEvent{Type: "test_start", Model: testModelID})
// Send test_start event once. A task-invalid Agent Identity response may
// restart this probe after registering a replacement task.
if !agentIdentityTaskRecoveryWasTried(ctx) {
s.sendEvent(c, TestEvent{Type: "test_start", Model: testModelID})
}
req, err := http.NewRequestWithContext(ctx, "POST", apiURL, bytes.NewReader(payloadBytes))
if err != nil {
@@ -602,7 +610,19 @@ func (s *AccountTestService) testOpenAIAccountConnection(c *gin.Context, account
// Set common headers
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+authToken)
if credentialAccount.IsOpenAIAgentIdentity() {
authHeaders, authErr := buildAgentIdentityAuthenticationHeaders(ctx, s.accountRepo, s.agentIdentityWS, &s.agentIdentityTaskMu, credentialAccount)
if authErr != nil {
return s.sendErrorAndEnd(c, "Failed to build Agent Identity authentication")
}
for key, values := range authHeaders {
for _, value := range values {
req.Header.Add(key, value)
}
}
} else {
req.Header.Set("Authorization", "Bearer "+authToken)
}
// Set OAuth-specific headers for ChatGPT internal API
if isOAuth {
@@ -644,6 +664,15 @@ func (s *AccountTestService) testOpenAIAccountConnection(c *gin.Context, account
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
body = redactAgentIdentitySensitiveBodyForAccount(ctx, s.accountRepo, credentialAccount, body)
if !agentIdentityTaskRecoveryWasTried(ctx) && credentialAccount.IsOpenAIAgentIdentity() && isAgentIdentityTaskInvalidHTTPResponse(resp.StatusCode, body) {
expectedTaskID := credentialAccount.GetCredential("task_id")
if err := ensureAgentIdentityTaskForAccount(ctx, s.accountRepo, s.agentIdentityWS, &s.agentIdentityTaskMu, credentialAccount, expectedTaskID); err != nil {
return s.sendErrorAndEnd(c, fmt.Sprintf("Agent Identity task recovery failed: %s", err.Error()))
}
c.Request = c.Request.WithContext(markAgentIdentityTaskRecoveryTried(ctx))
return s.testOpenAIAccountConnection(c, account, modelID, prompt, mode)
}
if resp.StatusCode == http.StatusTooManyRequests {
s.reconcileOpenAI429State(ctx, account, resp.Header, body)
}
@@ -695,7 +724,7 @@ func (s *AccountTestService) testGrokAccountConnection(c *gin.Context, account *
return s.sendErrorAndEnd(c, fmt.Sprintf("Unsupported Grok account type: %s", account.Type))
}
apiURL, err := xai.BuildResponsesURL(account.GetGrokBaseURL())
apiURL, err := buildGrokResponsesURL(account, s.cfg)
if err != nil {
return s.sendErrorAndEnd(c, fmt.Sprintf("Invalid Grok base URL: %s", err.Error()))
}
@@ -715,7 +744,9 @@ func (s *AccountTestService) testGrokAccountConnection(c *gin.Context, account *
return s.sendErrorAndEnd(c, "Failed to create Grok test payload")
}
s.sendEvent(c, TestEvent{Type: "test_start", Model: testModelID})
if !agentIdentityTaskRecoveryWasTried(ctx) {
s.sendEvent(c, TestEvent{Type: "test_start", Model: testModelID})
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, apiURL, bytes.NewReader(payloadBytes))
if err != nil {
@@ -724,7 +755,9 @@ func (s *AccountTestService) testGrokAccountConnection(c *gin.Context, account *
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json, text/event-stream")
req.Header.Set("Authorization", "Bearer "+authToken)
applyGrokCLIHeaders(req.Header)
if account.IsGrokOAuth() {
applyGrokCLIHeaders(req.Header)
}
proxyURL := ""
if account.ProxyID != nil && account.Proxy != nil {
@@ -740,7 +773,7 @@ func (s *AccountTestService) testGrokAccountConnection(c *gin.Context, account *
now := time.Now()
snapshot := parseGrokQuotaSnapshot(resp.Header, resp.StatusCode, now)
if snapshot != nil && s.accountRepo != nil {
resetAt, limited := grokRateLimitResetAt(snapshot, now)
resetAt, limited := grokRateLimitResetAtForAccount(account, snapshot, now)
if limited {
normalizeGrokExhaustedWindowResets(snapshot, resetAt, now)
}
@@ -749,7 +782,11 @@ func (s *AccountTestService) testGrokAccountConnection(c *gin.Context, account *
})
if limited {
persistGrokRateLimit(ctx, s.accountRepo, account, resetAt)
} else if isSuccessfulGrokRateLimitRecovery(account, snapshot) {
clearGrokRateLimitAfterRecovery(ctx, s.accountRepo, account)
}
} else if s.accountRepo != nil && isSuccessfulGrokRateLimitRecovery(account, &xai.QuotaSnapshot{StatusCode: resp.StatusCode}) {
clearGrokRateLimitAfterRecovery(ctx, s.accountRepo, account)
}
if resp.StatusCode != http.StatusOK {
@@ -827,16 +864,26 @@ func (s *AccountTestService) testOpenAIChatCompletionsConnection(
// resulting capability state on the account.
func (s *AccountTestService) testOpenAICompactConnection(c *gin.Context, account *Account, testModelID string) error {
ctx := c.Request.Context()
credentialAccount := account
if account.IsShadow() {
resolved, err := resolveCredentialAccount(ctx, s.accountRepo, account)
if err != nil {
return s.sendErrorAndEnd(c, "Failed to resolve account credentials")
}
credentialAccount = resolved
}
authToken := ""
apiURL := ""
isOAuth := false
switch {
case account.IsOAuth():
case credentialAccount.IsOAuth():
isOAuth = true
authToken = account.GetOpenAIAccessToken()
if authToken == "" {
if !credentialAccount.IsOpenAIAgentIdentity() {
authToken = credentialAccount.GetOpenAIAccessToken()
}
if authToken == "" && !credentialAccount.IsOpenAIAgentIdentity() {
return s.sendErrorAndEnd(c, "No access token available")
}
apiURL = chatgptCodexAPIURL + "/compact"
@@ -865,7 +912,9 @@ func (s *AccountTestService) testOpenAICompactConnection(c *gin.Context, account
c.Writer.Flush()
payloadBytes, _ := json.Marshal(createOpenAICompactProbePayload(testModelID))
s.sendEvent(c, TestEvent{Type: "test_start", Model: testModelID})
if !agentIdentityTaskRecoveryWasTried(ctx) {
s.sendEvent(c, TestEvent{Type: "test_start", Model: testModelID})
}
req, err := http.NewRequestWithContext(ctx, "POST", apiURL, bytes.NewReader(payloadBytes))
if err != nil {
@@ -875,7 +924,19 @@ func (s *AccountTestService) testOpenAICompactConnection(c *gin.Context, account
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
req.Header.Set("Authorization", "Bearer "+authToken)
if credentialAccount.IsOpenAIAgentIdentity() {
authHeaders, authErr := buildAgentIdentityAuthenticationHeaders(ctx, s.accountRepo, s.agentIdentityWS, &s.agentIdentityTaskMu, credentialAccount)
if authErr != nil {
return s.sendErrorAndEnd(c, "Failed to build Agent Identity authentication")
}
for key, values := range authHeaders {
for _, value := range values {
req.Header.Add(key, value)
}
}
} else {
req.Header.Set("Authorization", "Bearer "+authToken)
}
req.Header.Set("OpenAI-Beta", "responses=experimental")
req.Header.Set("Originator", "codex_cli_rs")
req.Header.Set("User-Agent", codexCLIUserAgent)
@@ -886,7 +947,7 @@ func (s *AccountTestService) testOpenAICompactConnection(c *gin.Context, account
if isOAuth {
req.Host = "chatgpt.com"
setOpenAIChatGPTAccountHeaders(req.Header, account)
setOpenAIChatGPTAccountHeaders(req.Header, credentialAccount)
}
// 账号级请求头覆写:测试请求与真实转发保持一致的最终头
@@ -909,6 +970,15 @@ func (s *AccountTestService) testOpenAICompactConnection(c *gin.Context, account
defer func() { _ = resp.Body.Close() }()
body, _ := io.ReadAll(io.LimitReader(resp.Body, 2<<20))
body = redactAgentIdentitySensitiveBodyForAccount(ctx, s.accountRepo, credentialAccount, body)
if !agentIdentityTaskRecoveryWasTried(ctx) && credentialAccount.IsOpenAIAgentIdentity() && isAgentIdentityTaskInvalidHTTPResponse(resp.StatusCode, body) {
expectedTaskID := credentialAccount.GetCredential("task_id")
if err := ensureAgentIdentityTaskForAccount(ctx, s.accountRepo, s.agentIdentityWS, &s.agentIdentityTaskMu, credentialAccount, expectedTaskID); err != nil {
return s.sendErrorAndEnd(c, fmt.Sprintf("Agent Identity task recovery failed: %s", err.Error()))
}
c.Request = c.Request.WithContext(markAgentIdentityTaskRecoveryTried(ctx))
return s.testOpenAICompactConnection(c, account, testModelID)
}
if s.accountRepo != nil {
updates := buildOpenAICompactProbeExtraUpdates(resp, body, nil, time.Now())
@@ -1700,8 +1770,19 @@ func (s *AccountTestService) testOpenAIImageAPIKey(c *gin.Context, ctx context.C
// testOpenAIImageOAuth tests OpenAI image generation using an OAuth account via Codex /responses API.
func (s *AccountTestService) testOpenAIImageOAuth(c *gin.Context, ctx context.Context, account *Account, modelID, prompt string) error {
authToken := account.GetOpenAIAccessToken()
if authToken == "" {
credentialAccount := account
if account.IsShadow() {
resolved, err := resolveCredentialAccount(ctx, s.accountRepo, account)
if err != nil {
return s.sendErrorAndEnd(c, "Failed to resolve account credentials")
}
credentialAccount = resolved
}
authToken := ""
if !credentialAccount.IsOpenAIAgentIdentity() {
authToken = credentialAccount.GetOpenAIAccessToken()
}
if authToken == "" && !credentialAccount.IsOpenAIAgentIdentity() {
return s.sendErrorAndEnd(c, "No access token available")
}
@@ -1733,17 +1814,29 @@ func (s *AccountTestService) testOpenAIImageOAuth(c *gin.Context, ctx context.Co
}
req = req.WithContext(WithHTTPUpstreamProfile(req.Context(), HTTPUpstreamProfileOpenAI))
req.Host = "chatgpt.com"
req.Header.Set("Authorization", "Bearer "+authToken)
if credentialAccount.IsOpenAIAgentIdentity() {
authHeaders, authErr := buildAgentIdentityAuthenticationHeaders(ctx, s.accountRepo, s.agentIdentityWS, &s.agentIdentityTaskMu, credentialAccount)
if authErr != nil {
return s.sendErrorAndEnd(c, "Failed to build Agent Identity authentication")
}
for key, values := range authHeaders {
for _, value := range values {
req.Header.Add(key, value)
}
}
} else {
req.Header.Set("Authorization", "Bearer "+authToken)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "text/event-stream")
req.Header.Set("OpenAI-Beta", "responses=experimental")
req.Header.Set("originator", "codex_cli_rs")
if customUA := strings.TrimSpace(account.GetOpenAIUserAgent()); customUA != "" {
if customUA := strings.TrimSpace(credentialAccount.GetOpenAIUserAgent()); customUA != "" {
req.Header.Set("User-Agent", customUA)
} else {
req.Header.Set("User-Agent", codexCLIUserAgent)
}
setOpenAIChatGPTAccountHeaders(req.Header, account)
setOpenAIChatGPTAccountHeaders(req.Header, credentialAccount)
// 与真实转发一致:originator 与最终 User-Agent 首段配套(原 opencode 与 Codex UA 错配会 404,issue #3901)。
enforceCodexIdentityHeaders(req.Header)
@@ -1762,6 +1855,7 @@ func (s *AccountTestService) testOpenAIImageOAuth(c *gin.Context, ctx context.Co
}()
if resp.StatusCode >= 400 {
body, _ := io.ReadAll(io.LimitReader(resp.Body, 2<<20))
body = redactAgentIdentitySensitiveBodyForAccount(ctx, s.accountRepo, credentialAccount, body)
message := strings.TrimSpace(extractUpstreamErrorMessage(body))
if message == "" {
message = fmt.Sprintf("Responses API returned %d", resp.StatusCode)
@@ -1773,6 +1867,7 @@ func (s *AccountTestService) testOpenAIImageOAuth(c *gin.Context, ctx context.Co
if err != nil {
return s.sendErrorAndEnd(c, fmt.Sprintf("Failed to read image response: %s", err.Error()))
}
body = redactAgentIdentitySensitiveBodyForAccount(ctx, s.accountRepo, credentialAccount, body)
results, _, _, _, _, err := collectOpenAIImagesFromResponsesBody(body)
if err != nil {
@@ -40,8 +40,9 @@ func TestAccountTestService_TestAccountConnection_GrokUsesXAIResponses(t *testin
Schedulable: true,
Concurrency: 1,
Credentials: map[string]any{
"access_token": "grok-access-token",
"expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339),
"access_token": "grok-access-token",
"refresh_token": "grok-refresh-token",
"expires_at": time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339),
"model_mapping": map[string]any{
"grok": "grok-4.3",
},
@@ -92,8 +93,9 @@ func TestAccountTestService_TestAccountConnection_GrokDefaultsEmptyModelTo45(t *
Schedulable: true,
Concurrency: 1,
Credentials: map[string]any{
"access_token": "grok-access-token",
"expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339),
"access_token": "grok-access-token",
"refresh_token": "grok-refresh-token",
"expires_at": time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339),
},
}
repo := &mockAccountRepoForGemini{accountsByID: map[int64]*Account{account.ID: account}}
@@ -133,8 +135,9 @@ func TestAccountTestService_Grok429PersistsRateLimitReset(t *testing.T) {
Schedulable: true,
Concurrency: 1,
Credentials: map[string]any{
"access_token": "grok-access-token",
"expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339),
"access_token": "grok-access-token",
"refresh_token": "grok-refresh-token",
"expires_at": time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339),
},
}
baseRepo := &mockAccountRepoForGemini{accountsByID: map[int64]*Account{account.ID: account}}
@@ -166,8 +169,9 @@ func TestAccountTestService_Grok429WithoutQuotaHeadersUsesFallback(t *testing.T)
ID: 15, Name: "grok-oauth-limited-no-headers", Platform: PlatformGrok,
Type: AccountTypeOAuth, Status: StatusActive, Schedulable: true, Concurrency: 1,
Credentials: map[string]any{
"access_token": "grok-access-token",
"expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339),
"access_token": "grok-access-token",
"refresh_token": "grok-refresh-token",
"expires_at": time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339),
},
}
baseRepo := &mockAccountRepoForGemini{accountsByID: map[int64]*Account{account.ID: account}}
@@ -299,6 +299,8 @@ type AccountUsageService struct {
cache *UsageCache
identityCache IdentityCache
tlsFPProfileService *TLSFingerprintProfileService
agentIdentityTaskMu sync.Mutex
agentIdentityWS agentIdentityWSConnectionInvalidator
}
// NewAccountUsageService 创建AccountUsageService实例
@@ -692,8 +694,11 @@ func (s *AccountUsageService) probeOpenAICodexSnapshot(ctx context.Context, acco
if account == nil || !account.IsOAuth() {
return nil, nil
}
accessToken := account.GetOpenAIAccessToken()
if accessToken == "" {
accessToken := ""
if !account.IsOpenAIAgentIdentity() {
accessToken = account.GetOpenAIAccessToken()
}
if accessToken == "" && !account.IsOpenAIAgentIdentity() {
return nil, fmt.Errorf("no access token available")
}
modelID := openaipkg.DefaultTestModel
@@ -711,7 +716,19 @@ func (s *AccountUsageService) probeOpenAICodexSnapshot(ctx context.Context, acco
}
req.Host = "chatgpt.com"
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+accessToken)
if account.IsOpenAIAgentIdentity() {
authHeaders, authErr := buildAgentIdentityAuthenticationHeaders(ctx, s.accountRepo, s.agentIdentityWS, &s.agentIdentityTaskMu, account)
if authErr != nil {
return nil, fmt.Errorf("build Agent Identity authentication: %w", authErr)
}
for key, values := range authHeaders {
for _, value := range values {
req.Header.Add(key, value)
}
}
} else {
req.Header.Set("Authorization", "Bearer "+accessToken)
}
req.Header.Set("Accept", "text/event-stream")
req.Header.Set("OpenAI-Beta", "responses=experimental")
req.Header.Set("Originator", "codex_cli_rs")
+313 -34
View File
@@ -2,6 +2,8 @@ package service
import (
"context"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"log/slog"
@@ -60,6 +62,275 @@ func (s *adminServiceImpl) GetAccountsByIDs(ctx context.Context, ids []int64) ([
return accounts, nil
}
const maxAccountNameRunes = 100
const duplicateAccountOperationIDExtraKey = "duplicate_operation_id"
func duplicateAccountName(sourceName string) string {
const suffix = " (Copy)"
nameRunes := []rune(strings.TrimSpace(sourceName))
maxBaseRunes := maxAccountNameRunes - len([]rune(suffix))
if len(nameRunes) > maxBaseRunes {
nameRunes = nameRunes[:maxBaseRunes]
}
return string(nameRunes) + suffix
}
func cloneAccountJSONMap(value map[string]any) (map[string]any, error) {
if value == nil {
return nil, nil
}
payload, err := json.Marshal(value)
if err != nil {
return nil, err
}
cloned := make(map[string]any, len(value))
if err := json.Unmarshal(payload, &cloned); err != nil {
return nil, err
}
return cloned, nil
}
var duplicateAccountDiscardedExtraKeys = map[string]struct{}{
// A retry identity belongs to the operation that created one copy, not to later copies.
duplicateAccountOperationIDExtraKey: {},
// External sync identity belongs to one local account only.
"crs_account_id": {},
"crs_kind": {},
"crs_synced_at": {},
// Local quota usage and derived window timestamps must start fresh.
"quota_used": {},
"quota_daily_used": {},
"quota_weekly_used": {},
"quota_daily_start": {},
"quota_weekly_start": {},
"quota_daily_reset_at": {},
"quota_weekly_reset_at": {},
// Provider observations, capability probes, and transient scheduling state.
"model_rate_limits": {},
"session_window_utilization": {},
"passive_usage_7d_utilization": {},
"passive_usage_7d_reset": {},
"passive_usage_7d_oi_utilization": {},
"passive_usage_7d_oi_reset": {},
"passive_usage_sampled_at": {},
"grok_usage_snapshot": {},
"grok_billing_snapshot": {},
"openai_responses_supported": {},
"openai_compact_supported": {},
"openai_compact_checked_at": {},
"openai_compact_last_status": {},
"openai_compact_last_error": {},
"antigravity_credits_overages": {},
"antigravity_force_token_refresh": {},
"antigravity_force_token_refresh_at": {},
"antigravity_force_token_refresh_reason": {},
"drive_storage_limit": {},
"drive_storage_usage": {},
"drive_tier_updated_at": {},
"codex_primary_used_percent": {},
"codex_primary_reset_after_seconds": {},
"codex_primary_window_minutes": {},
"codex_secondary_used_percent": {},
"codex_secondary_reset_after_seconds": {},
"codex_secondary_window_minutes": {},
"codex_primary_over_secondary_percent": {},
"codex_usage_updated_at": {},
"codex_5h_used_percent": {},
"codex_5h_reset_after_seconds": {},
"codex_5h_window_minutes": {},
"codex_5h_reset_at": {},
"codex_7d_used_percent": {},
"codex_7d_reset_after_seconds": {},
"codex_7d_window_minutes": {},
"codex_7d_reset_at": {},
}
func duplicateAccountExtra(value map[string]any) (map[string]any, error) {
cloned, err := cloneAccountJSONMap(value)
if err != nil {
return nil, err
}
for key := range duplicateAccountDiscardedExtraKeys {
delete(cloned, key)
}
return cloned, nil
}
func canDuplicateAccountType(accountType string) bool {
switch accountType {
case AccountTypeAPIKey, AccountTypeUpstream, AccountTypeBedrock, AccountTypeServiceAccount:
return true
default:
return false
}
}
func duplicateAccountGroups(source *Account) ([]AccountGroup, []int64) {
if len(source.AccountGroups) > 0 {
groups := make([]AccountGroup, 0, len(source.AccountGroups))
groupIDs := make([]int64, 0, len(source.AccountGroups))
for _, sourceGroup := range source.AccountGroups {
groups = append(groups, AccountGroup{GroupID: sourceGroup.GroupID, Priority: sourceGroup.Priority})
groupIDs = append(groupIDs, sourceGroup.GroupID)
}
return groups, groupIDs
}
groups := make([]AccountGroup, 0, len(source.GroupIDs))
groupIDs := append([]int64(nil), source.GroupIDs...)
for i, groupID := range groupIDs {
groups = append(groups, AccountGroup{GroupID: groupID, Priority: i + 1})
}
return groups, groupIDs
}
func duplicateAccountOperationID(sourceID int64, actorScope, operationKey string) string {
operationKey = strings.TrimSpace(operationKey)
if operationKey == "" {
return ""
}
actorScope = strings.TrimSpace(actorScope)
if actorScope == "" {
actorScope = "admin:0"
}
payload := "admin.accounts.duplicate\x00" + actorScope + "\x00" + strconv.FormatInt(sourceID, 10) + "\x00" + operationKey
digest := sha256.Sum256([]byte(payload))
return fmt.Sprintf("%x", digest)
}
func (s *adminServiceImpl) findDuplicateByOperationID(ctx context.Context, operationID string) (*Account, error) {
if operationID == "" {
return nil, nil
}
accounts, err := s.accountRepo.FindByExtraField(ctx, duplicateAccountOperationIDExtraKey, operationID)
if err != nil {
return nil, fmt.Errorf("find duplicate account operation: %w", err)
}
if len(accounts) == 0 {
return nil, nil
}
account := accounts[0]
return &account, nil
}
// RecoverDuplicateAccount performs a read-only lookup for an already committed duplicate.
// It is used when the idempotency coordinator cannot confirm whether response persistence
// succeeded, and deliberately never repeats the create side effect.
func (s *adminServiceImpl) RecoverDuplicateAccount(ctx context.Context, id int64, actorScope, operationKey string) (*Account, error) {
return s.findDuplicateByOperationID(ctx, duplicateAccountOperationID(id, actorScope, operationKey))
}
func cloneAccountValuePointer[T any](value *T) *T {
if value == nil {
return nil
}
cloned := *value
return &cloned
}
// DuplicateAccount creates a paused account from source configuration without carrying first-class
// runtime state. Credentials and extra configuration are deep-copied so normalization of the new
// account cannot mutate the in-memory source. Linked credential shadows are excluded because they
// intentionally do not own credentials and must be created through CreateShadow.
func (s *adminServiceImpl) DuplicateAccount(ctx context.Context, id int64, actorScope, operationKey string) (*Account, error) {
operationID := duplicateAccountOperationID(id, actorScope, operationKey)
existing, err := s.RecoverDuplicateAccount(ctx, id, actorScope, operationKey)
if err != nil {
return nil, err
}
if existing != nil {
return existing, nil
}
source, err := s.accountRepo.GetByID(ctx, id)
if err != nil {
return nil, err
}
if source.IsCredentialShadow() {
return nil, infraerrors.BadRequest(
"ACCOUNT_DUPLICATE_SHADOW_UNSUPPORTED",
"linked credential shadow accounts cannot be duplicated; duplicate the parent account instead",
)
}
if !canDuplicateAccountType(source.Type) {
return nil, infraerrors.BadRequest(
"ACCOUNT_DUPLICATE_CREDENTIAL_TYPE_UNSUPPORTED",
"accounts with rotating or unsupported credential types cannot be duplicated",
)
}
credentials, err := cloneAccountJSONMap(source.Credentials)
if err != nil {
return nil, fmt.Errorf("clone account credentials: %w", err)
}
extra, err := duplicateAccountExtra(source.Extra)
if err != nil {
return nil, fmt.Errorf("clone account extra configuration: %w", err)
}
if operationID != "" {
if extra == nil {
extra = make(map[string]any, 1)
}
extra[duplicateAccountOperationIDExtraKey] = operationID
}
var expiresAt *int64
if source.ExpiresAt != nil {
unix := source.ExpiresAt.Unix()
expiresAt = &unix
}
autoPauseOnExpired := source.AutoPauseOnExpired
groups, groupIDs := duplicateAccountGroups(source)
proxyID := source.ProxyID
if source.ProxyFallbackOriginID != nil {
// Proxy fallback is transient runtime state; duplicate the configured origin.
proxyID = source.ProxyFallbackOriginID
}
input := &CreateAccountInput{
Name: duplicateAccountName(source.Name),
Notes: cloneAccountValuePointer(source.Notes),
Platform: source.Platform,
Type: source.Type,
Credentials: credentials,
Extra: extra,
ProxyID: cloneAccountValuePointer(proxyID),
Concurrency: source.Concurrency,
Priority: source.Priority,
RateMultiplier: cloneAccountValuePointer(source.RateMultiplier),
LoadFactor: cloneAccountValuePointer(source.LoadFactor),
GroupIDs: groupIDs,
ExpiresAt: expiresAt,
AutoPauseOnExpired: &autoPauseOnExpired,
SkipDefaultGroupBind: true,
SkipMixedChannelCheck: true,
}
accountExtra, err := normalizeOpenAILongContextBillingExtra(input.Platform, input.Extra)
if err != nil {
return nil, fmt.Errorf("normalize duplicate account extra: %w", err)
}
if err := NormalizeHeaderOverrideCredentials(input.Credentials); err != nil {
return nil, err
}
duplicate, err := buildAccountForCreate(input, accountExtra)
if err != nil {
return nil, err
}
// A copied credential must be reviewed before it can share live traffic with its source.
duplicate.Schedulable = false
if s.accountDuplicateRepo == nil {
return nil, errors.New("account duplicate repository is not configured")
}
if err := s.accountDuplicateRepo.CreateWithAccountGroups(ctx, duplicate, groups); err != nil {
return nil, fmt.Errorf("create duplicate account: %w", err)
}
for i := range groups {
groups[i].AccountID = duplicate.ID
}
duplicate.AccountGroups = groups
duplicate.GroupIDs = groupIDs
return duplicate, nil
}
func normalizeAccountConcurrency(platform, accountType string, concurrency int) int {
if platform == PlatformGrok && accountType == AccountTypeOAuth {
if concurrency <= 0 {
@@ -122,40 +393,7 @@ func normalizeOpenAILongContextBillingUpdateExtra(account *Account, input *Updat
return normalized, nil
}
func (s *adminServiceImpl) CreateAccount(ctx context.Context, input *CreateAccountInput) (*Account, error) {
accountExtra, err := normalizeOpenAILongContextBillingExtra(input.Platform, input.Extra)
if err != nil {
return nil, err
}
// 绑定分组
groupIDs := input.GroupIDs
// 如果没有指定分组,自动绑定对应平台的默认分组
if len(groupIDs) == 0 && !input.SkipDefaultGroupBind {
defaultGroupName := input.Platform + "-default"
groups, err := s.groupRepo.ListActiveByPlatform(ctx, input.Platform)
if err == nil {
for _, g := range groups {
if g.Name == defaultGroupName {
groupIDs = []int64{g.ID}
break
}
}
}
}
// 检查混合渠道风险(除非用户已确认)
if len(groupIDs) > 0 && !input.SkipMixedChannelCheck {
if err := s.checkMixedChannelRisk(ctx, 0, input.Platform, groupIDs); err != nil {
return nil, err
}
}
// 校验并规范化请求头覆写配置(header 名小写化、格式检查)
if err := NormalizeHeaderOverrideCredentials(input.Credentials); err != nil {
return nil, err
}
func buildAccountForCreate(input *CreateAccountInput, accountExtra map[string]any) (*Account, error) {
account := &Account{
Name: input.Name,
Notes: normalizeAccountNotes(input.Notes),
@@ -198,6 +436,47 @@ func (s *adminServiceImpl) CreateAccount(ctx context.Context, input *CreateAccou
}
account.LoadFactor = input.LoadFactor
}
return account, nil
}
func (s *adminServiceImpl) CreateAccount(ctx context.Context, input *CreateAccountInput) (*Account, error) {
accountExtra, err := normalizeOpenAILongContextBillingExtra(input.Platform, input.Extra)
if err != nil {
return nil, err
}
// 绑定分组
groupIDs := input.GroupIDs
// 如果没有指定分组,自动绑定对应平台的默认分组
if len(groupIDs) == 0 && !input.SkipDefaultGroupBind {
defaultGroupName := input.Platform + "-default"
groups, err := s.groupRepo.ListActiveByPlatform(ctx, input.Platform)
if err == nil {
for _, g := range groups {
if g.Name == defaultGroupName {
groupIDs = []int64{g.ID}
break
}
}
}
}
// 检查混合渠道风险(除非用户已确认)
if len(groupIDs) > 0 && !input.SkipMixedChannelCheck {
if err := s.checkMixedChannelRisk(ctx, 0, input.Platform, groupIDs); err != nil {
return nil, err
}
}
// 校验并规范化请求头覆写配置(header 名小写化、格式检查)
if err := NormalizeHeaderOverrideCredentials(input.Credentials); err != nil {
return nil, err
}
account, err := buildAccountForCreate(input, accountExtra)
if err != nil {
return nil, err
}
if err := s.accountRepo.Create(ctx, account); err != nil {
return nil, err
}
+9 -1
View File
@@ -67,6 +67,12 @@ type AdminService interface {
GetAccount(ctx context.Context, id int64) (*Account, error)
GetAccountsByIDs(ctx context.Context, ids []int64) ([]*Account, error)
CreateAccount(ctx context.Context, input *CreateAccountInput) (*Account, error)
// DuplicateAccount creates an independent account from an existing account's configuration.
// First-class runtime columns are intentionally reset by the normal account creation path.
DuplicateAccount(ctx context.Context, id int64, actorScope, operationKey string) (*Account, error)
// RecoverDuplicateAccount returns a previously committed duplicate for an ambiguous retry.
// It never creates an account.
RecoverDuplicateAccount(ctx context.Context, id int64, actorScope, operationKey string) (*Account, error)
UpdateAccount(ctx context.Context, id int64, input *UpdateAccountInput) (*Account, error)
// UpdateAccountExtra 仅对 Extra 做 JSONB 增量合并(key 级覆盖),不会影响其它字段或运行态键。
// 用于刷新流程持久化 account_uuid / org_uuid 等少量键,避免被全量快照覆盖。
@@ -577,6 +583,7 @@ type adminServiceImpl struct {
userRepo UserRepository
groupRepo GroupRepository
accountRepo AccountRepository
accountDuplicateRepo AccountDuplicateRepository
proxyRepo ProxyRepository
apiKeyRepo APIKeyRepository
redeemCodeRepo RedeemCodeRepository
@@ -602,7 +609,7 @@ type userGroupRateBatchReader interface {
func NewAdminService(
userRepo UserRepository,
groupRepo GroupRepository,
accountRepo AccountRepository,
accountRepo AdminAccountRepository,
proxyRepo ProxyRepository,
apiKeyRepo APIKeyRepository,
redeemCodeRepo RedeemCodeRepository,
@@ -623,6 +630,7 @@ func NewAdminService(
userRepo: userRepo,
groupRepo: groupRepo,
accountRepo: accountRepo,
accountDuplicateRepo: accountRepo,
proxyRepo: proxyRepo,
apiKeyRepo: apiKeyRepo,
redeemCodeRepo: redeemCodeRepo,
@@ -0,0 +1,322 @@
//go:build unit
package service
import (
"context"
"errors"
"net/http"
"strings"
"testing"
"time"
"unicode/utf8"
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
"github.com/stretchr/testify/require"
)
type duplicateAccountRepoStub struct {
*sparkShadowRepoStub
atomicCreateErr error
accountGroupsOf map[int64][]AccountGroup
}
func newDuplicateAccountRepoStub() *duplicateAccountRepoStub {
return &duplicateAccountRepoStub{
sparkShadowRepoStub: newSparkShadowRepoStub(),
accountGroupsOf: make(map[int64][]AccountGroup),
}
}
func (s *duplicateAccountRepoStub) CreateWithAccountGroups(ctx context.Context, account *Account, groups []AccountGroup) error {
if s.atomicCreateErr != nil {
return s.atomicCreateErr
}
groupIDs := make([]int64, 0, len(groups))
for _, group := range groups {
groupIDs = append(groupIDs, group.GroupID)
}
account.GroupIDs = groupIDs
if err := s.Create(ctx, account); err != nil {
return err
}
clonedGroups := make([]AccountGroup, len(groups))
copy(clonedGroups, groups)
for i := range clonedGroups {
clonedGroups[i].AccountID = account.ID
}
account.AccountGroups = clonedGroups
s.accountGroupsOf[account.ID] = clonedGroups
if len(groupIDs) > 0 {
s.groupsOf[account.ID] = append([]int64(nil), groupIDs...)
}
stored := *account
s.accounts[account.ID] = &stored
s.mockAccountRepoForGemini.accountsByID[account.ID] = &stored
return nil
}
func (s *duplicateAccountRepoStub) FindByExtraField(_ context.Context, key string, value any) ([]Account, error) {
wanted, ok := value.(string)
if !ok {
return nil, nil
}
var matches []Account
for _, account := range s.accounts {
if actual, ok := account.Extra[key].(string); ok && actual == wanted {
matches = append(matches, *account)
}
}
return matches, nil
}
func TestDuplicateAccountCopiesConfigurationAndResetsRuntimeState(t *testing.T) {
ctx := context.Background()
repo := newDuplicateAccountRepoStub()
svc := &adminServiceImpl{accountRepo: repo, accountDuplicateRepo: repo}
notes := "keep this note"
proxyID := int64(17)
originalProxyID := int64(11)
rateMultiplier := 1.25
loadFactor := 9
expiresAt := time.Date(2027, time.March, 4, 5, 6, 7, 0, time.UTC)
rateLimitedAt := time.Now().Add(-time.Minute)
rateLimitResetAt := time.Now().Add(time.Hour)
overloadUntil := time.Now().Add(2 * time.Hour)
tempUnschedulableUntil := time.Now().Add(3 * time.Hour)
sessionWindowStart := time.Now().Add(-2 * time.Hour)
sessionWindowEnd := time.Now().Add(2 * time.Hour)
source := &Account{
Name: "primary",
Notes: &notes,
Platform: PlatformAnthropic,
Type: AccountTypeAPIKey,
ProxyID: &proxyID,
ProxyFallbackOriginID: &originalProxyID,
Concurrency: 6,
Priority: 40,
RateMultiplier: &rateMultiplier,
LoadFactor: &loadFactor,
Status: StatusError,
Schedulable: true,
ErrorMessage: "upstream unavailable",
ExpiresAt: &expiresAt,
AutoPauseOnExpired: false,
Credentials: map[string]any{
"api_key": "secret",
"nested": map[string]any{"token": "source-token"},
},
Extra: map[string]any{
"config": map[string]any{"region": "us-east-1"},
"items": []any{map[string]any{"enabled": true}},
"quota_limit": 1000,
"quota_used": 450,
"quota_daily_used": 25,
"quota_daily_start": "2026-07-15T00:00:00Z",
"model_rate_limits": map[string]any{"gpt-5": "2099-01-01T00:00:00Z"},
"codex_5h_used_percent": 80,
"codex_cli_only": true,
"grok_usage_snapshot": map[string]any{"status_code": 429},
"openai_responses_supported": false,
"openai_compact_checked_at": "2026-07-15T00:00:00Z",
"session_window_utilization": 0.8,
"passive_usage_sampled_at": "2026-07-15T00:00:00Z",
"antigravity_force_token_refresh": true,
"antigravity_credits_overages": map[string]any{"enabled": true},
"crs_account_id": "remote-42",
"crs_kind": "openai-api-key",
"crs_synced_at": "2026-07-15T00:00:00Z",
},
GroupIDs: []int64{7, 3},
AccountGroups: []AccountGroup{{GroupID: 7, Priority: 50}, {GroupID: 3, Priority: 7}},
RateLimitedAt: &rateLimitedAt,
RateLimitResetAt: &rateLimitResetAt,
OverloadUntil: &overloadUntil,
TempUnschedulableUntil: &tempUnschedulableUntil,
TempUnschedulableReason: "maintenance",
SessionWindowStart: &sessionWindowStart,
SessionWindowEnd: &sessionWindowEnd,
SessionWindowStatus: "active",
}
require.NoError(t, repo.Create(ctx, source))
duplicate, err := svc.DuplicateAccount(ctx, source.ID, "admin:1", "")
require.NoError(t, err)
require.NotEqual(t, source.ID, duplicate.ID)
require.Equal(t, "primary (Copy)", duplicate.Name)
require.Equal(t, source.Platform, duplicate.Platform)
require.Equal(t, source.Type, duplicate.Type)
require.Equal(t, source.Concurrency, duplicate.Concurrency)
require.Equal(t, source.Priority, duplicate.Priority)
require.Equal(t, source.AutoPauseOnExpired, duplicate.AutoPauseOnExpired)
require.Equal(t, source.GroupIDs, duplicate.GroupIDs)
require.Equal(t, source.Credentials, duplicate.Credentials)
require.Equal(t, map[string]any{
"config": map[string]any{"region": "us-east-1"},
"items": []any{map[string]any{"enabled": true}},
"quota_limit": float64(1000),
"codex_cli_only": true,
}, duplicate.Extra)
require.NotNil(t, duplicate.ExpiresAt)
require.True(t, source.ExpiresAt.Equal(*duplicate.ExpiresAt))
require.Equal(t, source.Notes, duplicate.Notes)
require.Equal(t, source.ProxyFallbackOriginID, duplicate.ProxyID)
require.Equal(t, source.RateMultiplier, duplicate.RateMultiplier)
require.Equal(t, source.LoadFactor, duplicate.LoadFactor)
require.Equal(t, source.GroupIDs, repo.groupsOf[duplicate.ID])
require.Equal(t, []AccountGroup{
{AccountID: duplicate.ID, GroupID: 7, Priority: 50},
{AccountID: duplicate.ID, GroupID: 3, Priority: 7},
}, repo.accountGroupsOf[duplicate.ID])
require.Equal(t, StatusActive, duplicate.Status)
require.False(t, duplicate.Schedulable)
require.Empty(t, duplicate.ErrorMessage)
require.Nil(t, duplicate.LastUsedAt)
require.Nil(t, duplicate.RateLimitedAt)
require.Nil(t, duplicate.RateLimitResetAt)
require.Nil(t, duplicate.OverloadUntil)
require.Nil(t, duplicate.TempUnschedulableUntil)
require.Empty(t, duplicate.TempUnschedulableReason)
require.Nil(t, duplicate.SessionWindowStart)
require.Nil(t, duplicate.SessionWindowEnd)
require.Empty(t, duplicate.SessionWindowStatus)
duplicate.Credentials["nested"].(map[string]any)["token"] = "changed"
duplicate.Extra["config"].(map[string]any)["region"] = "changed"
duplicate.Extra["items"].([]any)[0].(map[string]any)["enabled"] = false
storedSource, getErr := repo.GetByID(ctx, source.ID)
require.NoError(t, getErr)
require.Equal(t, "source-token", storedSource.Credentials["nested"].(map[string]any)["token"])
require.Equal(t, "us-east-1", storedSource.Extra["config"].(map[string]any)["region"])
require.Equal(t, true, storedSource.Extra["items"].([]any)[0].(map[string]any)["enabled"])
require.Equal(t, "remote-42", storedSource.Extra["crs_account_id"])
}
func TestDuplicateAccountRejectsCredentialShadow(t *testing.T) {
ctx := context.Background()
repo := newDuplicateAccountRepoStub()
svc := &adminServiceImpl{accountRepo: repo, accountDuplicateRepo: repo}
parentID := int64(99)
shadow := &Account{
Name: "shadow",
Platform: PlatformOpenAI,
Type: AccountTypeOAuth,
ParentAccountID: &parentID,
QuotaDimension: QuotaDimensionSpark,
}
require.NoError(t, repo.Create(ctx, shadow))
_, err := svc.DuplicateAccount(ctx, shadow.ID, "admin:1", "")
require.Error(t, err)
require.Equal(t, http.StatusBadRequest, infraerrors.Code(err))
require.Equal(t, "ACCOUNT_DUPLICATE_SHADOW_UNSUPPORTED", infraerrors.Reason(err))
require.Len(t, repo.accounts, 1)
}
func TestDuplicateAccountRejectsRotatingOrUnknownCredentialTypes(t *testing.T) {
for _, accountType := range []string{AccountTypeOAuth, AccountTypeSetupToken, "legacy-cookie"} {
t.Run(accountType, func(t *testing.T) {
ctx := context.Background()
repo := newDuplicateAccountRepoStub()
svc := &adminServiceImpl{accountRepo: repo, accountDuplicateRepo: repo}
source := &Account{
Name: "rotating-credential-account",
Platform: PlatformOpenAI,
Type: accountType,
Credentials: map[string]any{"refresh_token": "shared-token"},
}
require.NoError(t, repo.Create(ctx, source))
_, err := svc.DuplicateAccount(ctx, source.ID, "admin:1", "")
require.Error(t, err)
require.Equal(t, http.StatusBadRequest, infraerrors.Code(err))
require.Equal(t, "ACCOUNT_DUPLICATE_CREDENTIAL_TYPE_UNSUPPORTED", infraerrors.Reason(err))
require.Len(t, repo.accounts, 1)
})
}
}
func TestDuplicateAccountPreservesUngroupedState(t *testing.T) {
ctx := context.Background()
repo := newDuplicateAccountRepoStub()
svc := &adminServiceImpl{accountRepo: repo, accountDuplicateRepo: repo}
source := &Account{
Name: "ungrouped",
Platform: PlatformAnthropic,
Type: AccountTypeAPIKey,
Credentials: map[string]any{"api_key": "secret"},
GroupIDs: nil,
}
require.NoError(t, repo.Create(ctx, source))
duplicate, err := svc.DuplicateAccount(ctx, source.ID, "admin:1", "")
require.NoError(t, err)
require.Empty(t, duplicate.GroupIDs)
require.NotContains(t, repo.groupsOf, duplicate.ID)
}
func TestDuplicateAccountAtomicCreateFailureLeavesNoOrphan(t *testing.T) {
ctx := context.Background()
repo := newDuplicateAccountRepoStub()
svc := &adminServiceImpl{accountRepo: repo, accountDuplicateRepo: repo}
source := &Account{
Name: "source",
Platform: PlatformAnthropic,
Type: AccountTypeAPIKey,
Credentials: map[string]any{"api_key": "secret"},
GroupIDs: []int64{7},
AccountGroups: []AccountGroup{{GroupID: 7, Priority: 25}},
}
require.NoError(t, repo.Create(ctx, source))
repo.atomicCreateErr = errors.New("group binding failed")
_, err := svc.DuplicateAccount(ctx, source.ID, "admin:1", "")
require.ErrorContains(t, err, "group binding failed")
require.Len(t, repo.accounts, 1)
}
func TestDuplicateAccountNamePreservesSuffixWithinSchemaLimit(t *testing.T) {
name := duplicateAccountName(strings.Repeat("界", 100))
require.Equal(t, 100, utf8.RuneCountInString(name))
require.True(t, strings.HasSuffix(name, " (Copy)"))
}
func TestDuplicateAccountReturnsExistingCopyForSameOperationKey(t *testing.T) {
ctx := context.Background()
repo := newDuplicateAccountRepoStub()
svc := &adminServiceImpl{accountRepo: repo, accountDuplicateRepo: repo}
source := &Account{
Name: "source",
Platform: PlatformAnthropic,
Type: AccountTypeAPIKey,
Credentials: map[string]any{"api_key": "secret"},
}
require.NoError(t, repo.Create(ctx, source))
first, err := svc.DuplicateAccount(ctx, source.ID, "admin:7", "stable-operation-key")
require.NoError(t, err)
second, err := svc.DuplicateAccount(ctx, source.ID, "admin:7", "stable-operation-key")
require.NoError(t, err)
recovered, err := svc.RecoverDuplicateAccount(ctx, source.ID, "admin:7", "stable-operation-key")
require.NoError(t, err)
otherAdminRecovery, err := svc.RecoverDuplicateAccount(ctx, source.ID, "admin:8", "stable-operation-key")
require.NoError(t, err)
otherAdminCopy, err := svc.DuplicateAccount(ctx, source.ID, "admin:8", "stable-operation-key")
require.NoError(t, err)
require.Equal(t, first.ID, second.ID)
require.Equal(t, first.ID, recovered.ID)
require.Nil(t, otherAdminRecovery, "durable recovery identity must remain scoped to the initiating admin")
require.NotEqual(t, first.ID, otherAdminCopy.ID)
require.Len(t, repo.accounts, 3)
require.NotEmpty(t, first.Extra[duplicateAccountOperationIDExtraKey])
}
+168 -16
View File
@@ -92,6 +92,9 @@ const (
contentModerationCleanupInterval = 24 * time.Hour
contentModerationCleanupTimeout = 30 * time.Minute
contentModerationCleanupDelay = 5 * time.Minute
contentModerationRuntimeCacheTTL = time.Second
contentModerationRuntimeRefreshTimeout = 5 * time.Second
)
var contentModerationCategoryOrder = []string{
@@ -512,10 +515,22 @@ type ContentModerationService struct {
lastCleanupUnix atomic.Int64
lastCleanupDeletedHit atomic.Int64
lastCleanupDeletedNonHit atomic.Int64
runtimeSnapshot atomic.Pointer[contentModerationRuntimeSnapshot]
runtimeRefreshMu sync.Mutex
runtimeCacheTTL time.Duration
runtimeRefreshRetryAt atomic.Int64
keyHealthMu sync.Mutex
keyHealth map[string]*contentModerationKeyHealth
}
type contentModerationRuntimeSnapshot struct {
riskControlEnabled bool
config *ContentModerationConfig
keywordMatcher *contentModerationKeywordMatcher
configDigest [sha256.Size]byte
loadedAt time.Time
}
type contentModerationTask struct {
input ContentModerationCheckInput
content ContentModerationInput
@@ -700,6 +715,7 @@ func (s *ContentModerationService) UpdateConfig(ctx context.Context, input Updat
if err := s.settingRepo.Set(ctx, SettingKeyContentModerationConfig, string(raw)); err != nil {
return nil, fmt.Errorf("save content moderation config: %w", err)
}
s.replaceRuntimeConfig(cfg, raw)
return s.configView(cfg), nil
}
@@ -776,16 +792,7 @@ func (s *ContentModerationService) Check(ctx context.Context, input ContentModer
"protocol", input.Protocol)
return allow, nil
}
if !s.isRiskControlEnabled(ctx) {
slog.Info("content_moderation.skip_feature_disabled",
"user_id", input.UserID,
"api_key_id", input.APIKeyID,
"group_id", contentModerationLogGroupID(input.GroupID),
"endpoint", input.Endpoint,
"protocol", input.Protocol)
return allow, nil
}
cfg, err := s.loadConfig(ctx)
runtimeSnapshot, err := s.loadRuntimeSnapshot(ctx)
if err != nil {
slog.Warn("content_moderation.skip_config_load_failed",
"user_id", input.UserID,
@@ -796,6 +803,16 @@ func (s *ContentModerationService) Check(ctx context.Context, input ContentModer
"error", err)
return allow, nil
}
if !runtimeSnapshot.riskControlEnabled {
slog.Info("content_moderation.skip_feature_disabled",
"user_id", input.UserID,
"api_key_id", input.APIKeyID,
"group_id", contentModerationLogGroupID(input.GroupID),
"endpoint", input.Endpoint,
"protocol", input.Protocol)
return allow, nil
}
cfg := runtimeSnapshot.config
inGroupScope := cfg.includesGroup(input.GroupID)
inModelScope := cfg.includesModel(input.Model)
slog.Info("content_moderation.config_loaded",
@@ -885,7 +902,7 @@ func (s *ContentModerationService) Check(ctx context.Context, input ContentModer
hashText := content.Hash()
if cfg.Mode == ContentModerationModePreBlock {
if cfg.KeywordBlockingMode != ContentModerationKeywordModeAPIOnly && len(cfg.BlockedKeywords) > 0 {
if keyword, hit := matchBlockedKeyword(content.Text, cfg.BlockedKeywords); hit {
if keyword, hit := runtimeSnapshot.matchBlockedKeyword(content.Text); hit {
s.recordPreBlockSyncMetric(0, ContentModerationActionKeywordBlock)
slog.Info("content_moderation.keyword_block",
"user_id", input.UserID,
@@ -1178,12 +1195,13 @@ func (s *ContentModerationService) enqueueRecord(input ContentModerationCheckInp
func (s *ContentModerationService) worker(id int) {
for {
ctx, cancel := context.WithTimeout(context.Background(), maxContentModerationTimeoutMS*time.Millisecond+10*time.Second)
cfg, err := s.loadConfig(ctx)
if err != nil || id >= cfg.WorkerCount {
runtimeSnapshot, err := s.loadRuntimeSnapshot(ctx)
if err != nil || runtimeSnapshot == nil || runtimeSnapshot.config == nil || id >= runtimeSnapshot.config.WorkerCount {
cancel()
time.Sleep(time.Second)
continue
}
cfg := runtimeSnapshot.config
task, ok := s.dequeueAsyncTask(ctx, time.Second)
if !ok {
cancel()
@@ -1438,15 +1456,18 @@ func (s *ContentModerationService) runCleanupOnce() {
}
func (s *ContentModerationService) loadConfig(ctx context.Context) (*ContentModerationConfig, error) {
cfg := defaultContentModerationConfig()
raw, err := s.settingRepo.GetValue(ctx, SettingKeyContentModerationConfig)
if err != nil {
if errors.Is(err, ErrSettingNotFound) {
cfg.normalize()
return cfg, nil
return parseContentModerationConfig("")
}
return nil, fmt.Errorf("get content moderation config: %w", err)
}
return parseContentModerationConfig(raw)
}
func parseContentModerationConfig(raw string) (*ContentModerationConfig, error) {
cfg := defaultContentModerationConfig()
if strings.TrimSpace(raw) == "" {
cfg.normalize()
return cfg, nil
@@ -1458,6 +1479,137 @@ func (s *ContentModerationService) loadConfig(ctx context.Context) (*ContentMode
return cfg, nil
}
func (s *ContentModerationService) loadRuntimeSnapshot(ctx context.Context) (*contentModerationRuntimeSnapshot, error) {
if s == nil || s.settingRepo == nil {
return nil, errors.New("content moderation setting repository unavailable")
}
now := time.Now()
if snapshot := s.runtimeSnapshot.Load(); snapshot != nil {
if now.Sub(snapshot.loadedAt) < s.runtimeSnapshotTTL() {
return snapshot, nil
}
s.triggerRuntimeSnapshotRefresh()
return snapshot, nil
}
s.runtimeRefreshMu.Lock()
defer s.runtimeRefreshMu.Unlock()
if snapshot := s.runtimeSnapshot.Load(); snapshot != nil {
return snapshot, nil
}
return s.refreshRuntimeSnapshot(ctx)
}
func (s *ContentModerationService) runtimeSnapshotTTL() time.Duration {
if s != nil && s.runtimeCacheTTL > 0 {
return s.runtimeCacheTTL
}
return contentModerationRuntimeCacheTTL
}
func (s *ContentModerationService) triggerRuntimeSnapshotRefresh() {
if s == nil || s.runtimeRefreshDeferred() || !s.runtimeRefreshMu.TryLock() {
return
}
if s.runtimeRefreshDeferred() {
s.runtimeRefreshMu.Unlock()
return
}
go func() {
defer s.runtimeRefreshMu.Unlock()
ctx, cancel := context.WithTimeout(context.Background(), contentModerationRuntimeRefreshTimeout)
defer cancel()
if _, err := s.refreshRuntimeSnapshot(ctx); err != nil {
s.runtimeRefreshRetryAt.Store(time.Now().Add(s.runtimeSnapshotTTL()).UnixNano())
slog.Warn("content_moderation.runtime_snapshot_refresh_failed", "error", err)
}
}()
}
func (s *ContentModerationService) runtimeRefreshDeferred() bool {
if s == nil {
return false
}
return time.Now().UnixNano() < s.runtimeRefreshRetryAt.Load()
}
func (s *ContentModerationService) refreshRuntimeSnapshot(ctx context.Context) (*contentModerationRuntimeSnapshot, error) {
values, err := s.settingRepo.GetMultiple(ctx, []string{
SettingKeyRiskControlEnabled,
SettingKeyContentModerationConfig,
})
if err != nil {
return nil, fmt.Errorf("get content moderation runtime settings: %w", err)
}
rawConfig := values[SettingKeyContentModerationConfig]
configDigest := sha256.Sum256([]byte(rawConfig))
if current := s.runtimeSnapshot.Load(); current != nil && current.configDigest == configDigest {
snapshot := &contentModerationRuntimeSnapshot{
riskControlEnabled: values[SettingKeyRiskControlEnabled] == "true",
config: current.config,
keywordMatcher: current.keywordMatcher,
configDigest: configDigest,
loadedAt: time.Now(),
}
s.runtimeSnapshot.Store(snapshot)
s.runtimeRefreshRetryAt.Store(0)
return snapshot, nil
}
cfg, err := parseContentModerationConfig(rawConfig)
if err != nil {
return nil, err
}
snapshot := &contentModerationRuntimeSnapshot{
riskControlEnabled: values[SettingKeyRiskControlEnabled] == "true",
config: cfg,
keywordMatcher: newContentModerationKeywordMatcher(cfg.BlockedKeywords),
configDigest: configDigest,
loadedAt: time.Now(),
}
s.runtimeSnapshot.Store(snapshot)
s.runtimeRefreshRetryAt.Store(0)
return snapshot, nil
}
func (s *ContentModerationService) replaceRuntimeConfig(cfg *ContentModerationConfig, raw []byte) {
if s == nil || cfg == nil {
return
}
s.runtimeRefreshMu.Lock()
hasSnapshot := s.runtimeSnapshot.Load() != nil
s.runtimeRefreshMu.Unlock()
if !hasSnapshot {
return
}
config := cloneContentModerationConfig(cfg)
keywordMatcher := newContentModerationKeywordMatcher(cfg.BlockedKeywords)
configDigest := sha256.Sum256(raw)
s.runtimeRefreshMu.Lock()
defer s.runtimeRefreshMu.Unlock()
current := s.runtimeSnapshot.Load()
if current == nil {
return
}
s.runtimeSnapshot.Store(&contentModerationRuntimeSnapshot{
riskControlEnabled: current.riskControlEnabled,
config: config,
keywordMatcher: keywordMatcher,
configDigest: configDigest,
loadedAt: time.Now(),
})
}
func (s *contentModerationRuntimeSnapshot) matchBlockedKeyword(text string) (string, bool) {
if s == nil || s.config == nil {
return "", false
}
if s.keywordMatcher != nil {
return s.keywordMatcher.Match(text)
}
return matchBlockedKeyword(text, s.config.BlockedKeywords)
}
func (s *ContentModerationService) isRiskControlEnabled(ctx context.Context) bool {
raw, err := s.settingRepo.GetValue(ctx, SettingKeyRiskControlEnabled)
if err != nil {
@@ -0,0 +1,222 @@
package service
import (
"strings"
)
type contentModerationKeywordMatcher struct {
nodes []contentModerationKeywordNode
edges []contentModerationKeywordEdge
rootTransitions [256]int32
keywords []string
}
type contentModerationKeywordNode struct {
failure int32
bestKeyword int32
edgeStart uint32
edgeCount uint16
}
type contentModerationKeywordEdge struct {
target int32
label byte
}
type contentModerationKeywordBuildEdge struct {
target int32
nextSibling int32
label byte
}
func newContentModerationKeywordMatcher(keywords []string) *contentModerationKeywordMatcher {
if len(keywords) == 0 {
return nil
}
buildNodes := []contentModerationKeywordNode{newContentModerationKeywordNode()}
buildEdges := make([]contentModerationKeywordBuildEdge, 0)
originalKeywords := append([]string(nil), keywords...)
for keywordIndex, keyword := range keywords {
if keyword == "" {
continue
}
state := int32(0)
for _, label := range []byte(strings.ToLower(keyword)) {
next := contentModerationKeywordBuildTransition(buildNodes, buildEdges, state, label)
if next < 0 {
next = int32(len(buildNodes))
buildNodes = append(buildNodes, newContentModerationKeywordNode())
buildEdges = append(buildEdges, contentModerationKeywordBuildEdge{
target: next,
nextSibling: contentModerationKeywordBuildFirstEdge(buildNodes[state]),
label: label,
})
buildNodes[state].edgeStart = uint32(len(buildEdges))
}
state = next
}
if current := buildNodes[state].bestKeyword; current < 0 || int32(keywordIndex) < current {
buildNodes[state].bestKeyword = int32(keywordIndex)
}
}
if len(buildNodes) == 1 {
return nil
}
queue := make([]int32, 0, len(buildNodes)-1)
var rootTransitions [256]int32
for edgeIndex := contentModerationKeywordBuildFirstEdge(buildNodes[0]); edgeIndex >= 0; edgeIndex = buildEdges[edgeIndex].nextSibling {
edge := buildEdges[edgeIndex]
rootTransitions[edge.label] = edge.target
queue = append(queue, edge.target)
}
for queueIndex := 0; queueIndex < len(queue); queueIndex++ {
state := queue[queueIndex]
for edgeIndex := contentModerationKeywordBuildFirstEdge(buildNodes[state]); edgeIndex >= 0; edgeIndex = buildEdges[edgeIndex].nextSibling {
edge := buildEdges[edgeIndex]
failure := buildNodes[state].failure
fallback := contentModerationKeywordBuildTransition(buildNodes, buildEdges, failure, edge.label)
for fallback < 0 && failure != 0 {
failure = buildNodes[failure].failure
fallback = contentModerationKeywordBuildTransition(buildNodes, buildEdges, failure, edge.label)
}
if fallback >= 0 {
buildNodes[edge.target].failure = fallback
}
buildNodes[edge.target].bestKeyword = minKeywordIndex(
buildNodes[edge.target].bestKeyword,
buildNodes[buildNodes[edge.target].failure].bestKeyword,
)
queue = append(queue, edge.target)
}
}
edges := make([]contentModerationKeywordEdge, 0, len(buildEdges))
var outgoing [256]contentModerationKeywordEdge
for nodeIndex := range buildNodes {
count := 0
for edgeIndex := contentModerationKeywordBuildFirstEdge(buildNodes[nodeIndex]); edgeIndex >= 0; edgeIndex = buildEdges[edgeIndex].nextSibling {
edge := buildEdges[edgeIndex]
outgoing[count] = contentModerationKeywordEdge{target: edge.target, label: edge.label}
count++
}
for index := 1; index < count; index++ {
current := outgoing[index]
insertAt := index
for insertAt > 0 && current.label < outgoing[insertAt-1].label {
outgoing[insertAt] = outgoing[insertAt-1]
insertAt--
}
outgoing[insertAt] = current
}
buildNodes[nodeIndex].edgeStart = uint32(len(edges))
buildNodes[nodeIndex].edgeCount = uint16(count)
edges = append(edges, outgoing[:count]...)
}
return &contentModerationKeywordMatcher{
nodes: buildNodes,
edges: edges,
rootTransitions: rootTransitions,
keywords: originalKeywords,
}
}
func newContentModerationKeywordNode() contentModerationKeywordNode {
return contentModerationKeywordNode{bestKeyword: -1}
}
func contentModerationKeywordBuildFirstEdge(node contentModerationKeywordNode) int32 {
if node.edgeStart == 0 {
return -1
}
return int32(node.edgeStart - 1)
}
func contentModerationKeywordBuildTransition(
nodes []contentModerationKeywordNode,
edges []contentModerationKeywordBuildEdge,
state int32,
label byte,
) int32 {
if state < 0 || int(state) >= len(nodes) {
return -1
}
for edgeIndex := contentModerationKeywordBuildFirstEdge(nodes[state]); edgeIndex >= 0; edgeIndex = edges[edgeIndex].nextSibling {
if edges[edgeIndex].label == label {
return edges[edgeIndex].target
}
}
return -1
}
func minKeywordIndex(left, right int32) int32 {
if left < 0 {
return right
}
if right < 0 || left < right {
return left
}
return right
}
func (m *contentModerationKeywordMatcher) Match(text string) (string, bool) {
if m == nil || text == "" || len(m.nodes) == 0 || len(m.keywords) == 0 {
return "", false
}
lower := strings.ToLower(text)
state := int32(0)
bestKeyword := int32(-1)
for index := 0; index < len(lower); index++ {
label := lower[index]
for {
next := m.next(state, label)
if next != 0 {
state = next
break
}
if state == 0 {
break
}
state = m.nodes[state].failure
}
bestKeyword = minKeywordIndex(bestKeyword, m.nodes[state].bestKeyword)
if bestKeyword == 0 {
return m.keywords[0], true
}
}
if bestKeyword < 0 || int(bestKeyword) >= len(m.keywords) {
return "", false
}
return m.keywords[bestKeyword], true
}
func (m *contentModerationKeywordMatcher) next(state int32, label byte) int32 {
if state == 0 {
return m.rootTransitions[label]
}
if state < 0 || int(state) >= len(m.nodes) {
return 0
}
node := m.nodes[state]
left := int(node.edgeStart)
right := left + int(node.edgeCount)
for left < right {
middle := left + (right-left)/2
edge := m.edges[middle]
if edge.label < label {
left = middle + 1
continue
}
right = middle
}
end := int(node.edgeStart) + int(node.edgeCount)
if left < end && m.edges[left].label == label {
return m.edges[left].target
}
return 0
}
@@ -0,0 +1,59 @@
package service
import (
"math/rand"
"strings"
"testing"
"github.com/stretchr/testify/require"
)
func TestContentModerationKeywordMatcherMatchesLegacyBehavior(t *testing.T) {
tests := []struct {
name string
text string
keywords []string
}{
{name: "miss", text: "clean prompt", keywords: []string{"blocked", "secret"}},
{name: "case insensitive", text: "contains SECRET value", keywords: []string{"secret"}},
{name: "configured order wins", text: "early appears before later", keywords: []string{"later", "early"}},
{name: "overlap uses configured order", text: "abc", keywords: []string{"bc", "abc"}},
{name: "unicode", text: "这里包含敏感词和世界", keywords: []string{"世界", "敏感词"}},
{name: "duplicates", text: "duplicate", keywords: []string{"duplicate", "DUPLICATE"}},
{name: "empty entries", text: "blocked", keywords: []string{"", "blocked"}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
wantKeyword, wantHit := matchBlockedKeyword(tt.text, tt.keywords)
gotKeyword, gotHit := newContentModerationKeywordMatcher(tt.keywords).Match(tt.text)
require.Equal(t, wantHit, gotHit)
require.Equal(t, wantKeyword, gotKeyword)
})
}
}
func TestContentModerationKeywordMatcherRandomizedParity(t *testing.T) {
rng := rand.New(rand.NewSource(20260714))
const alphabet = "abcXYZ"
for iteration := 0; iteration < 1000; iteration++ {
keywords := make([]string, 1+rng.Intn(30))
for index := range keywords {
length := 1 + rng.Intn(8)
var value strings.Builder
for range length {
_ = value.WriteByte(alphabet[rng.Intn(len(alphabet))])
}
keywords[index] = value.String()
}
var text strings.Builder
for range 20 + rng.Intn(100) {
_ = text.WriteByte(alphabet[rng.Intn(len(alphabet))])
}
wantKeyword, wantHit := matchBlockedKeyword(text.String(), keywords)
gotKeyword, gotHit := newContentModerationKeywordMatcher(keywords).Match(text.String())
require.Equal(t, wantHit, gotHit, "iteration %d", iteration)
require.Equal(t, wantKeyword, gotKeyword, "iteration %d", iteration)
}
}
@@ -0,0 +1,451 @@
package service
import (
"context"
"encoding/json"
"errors"
"sync"
"testing"
"time"
"github.com/stretchr/testify/require"
)
type contentModerationRuntimeSettingRepo struct {
mu sync.Mutex
values map[string]string
getValueCalls int
getMultipleCalls int
getMultipleErr error
getMultipleStart chan<- struct{}
getMultipleWait <-chan struct{}
}
func (r *contentModerationRuntimeSettingRepo) Get(_ context.Context, key string) (*Setting, error) {
r.mu.Lock()
defer r.mu.Unlock()
value, ok := r.values[key]
if !ok {
return nil, ErrSettingNotFound
}
return &Setting{Key: key, Value: value}, nil
}
func (r *contentModerationRuntimeSettingRepo) GetValue(_ context.Context, key string) (string, error) {
r.mu.Lock()
defer r.mu.Unlock()
r.getValueCalls++
value, ok := r.values[key]
if !ok {
return "", ErrSettingNotFound
}
return value, nil
}
func (r *contentModerationRuntimeSettingRepo) Set(_ context.Context, key, value string) error {
r.mu.Lock()
defer r.mu.Unlock()
if r.values == nil {
r.values = make(map[string]string)
}
r.values[key] = value
return nil
}
func (r *contentModerationRuntimeSettingRepo) GetMultiple(_ context.Context, keys []string) (map[string]string, error) {
r.mu.Lock()
r.getMultipleCalls++
if err := r.getMultipleErr; err != nil {
r.mu.Unlock()
return nil, err
}
out := make(map[string]string, len(keys))
for _, key := range keys {
if value, ok := r.values[key]; ok {
out[key] = value
}
}
start := r.getMultipleStart
wait := r.getMultipleWait
r.getMultipleStart = nil
r.getMultipleWait = nil
r.mu.Unlock()
if start != nil {
start <- struct{}{}
}
if wait != nil {
<-wait
}
return out, nil
}
func (r *contentModerationRuntimeSettingRepo) SetMultiple(_ context.Context, values map[string]string) error {
r.mu.Lock()
defer r.mu.Unlock()
if r.values == nil {
r.values = make(map[string]string)
}
for key, value := range values {
r.values[key] = value
}
return nil
}
func (r *contentModerationRuntimeSettingRepo) GetAll(_ context.Context) (map[string]string, error) {
r.mu.Lock()
defer r.mu.Unlock()
out := make(map[string]string, len(r.values))
for key, value := range r.values {
out[key] = value
}
return out, nil
}
func (r *contentModerationRuntimeSettingRepo) Delete(_ context.Context, key string) error {
r.mu.Lock()
defer r.mu.Unlock()
delete(r.values, key)
return nil
}
func (r *contentModerationRuntimeSettingRepo) calls() (getValue, getMultiple int) {
r.mu.Lock()
defer r.mu.Unlock()
return r.getValueCalls, r.getMultipleCalls
}
func (r *contentModerationRuntimeSettingRepo) failMultiple(err error) {
r.mu.Lock()
defer r.mu.Unlock()
r.getMultipleErr = err
}
func (r *contentModerationRuntimeSettingRepo) blockNextMultiple(start chan<- struct{}, wait <-chan struct{}) {
r.mu.Lock()
defer r.mu.Unlock()
r.getMultipleStart = start
r.getMultipleWait = wait
}
func runtimeCacheTestConfig(t *testing.T, keywords ...string) string {
t.Helper()
cfg := defaultContentModerationConfig()
cfg.Enabled = true
cfg.Mode = ContentModerationModePreBlock
cfg.KeywordBlockingMode = ContentModerationKeywordModeKeywordOnly
cfg.BlockedKeywords = keywords
raw, err := json.Marshal(cfg)
require.NoError(t, err)
return string(raw)
}
func runtimeCacheTestService(repo *contentModerationRuntimeSettingRepo, ttl time.Duration) *ContentModerationService {
return &ContentModerationService{
settingRepo: repo,
repo: &contentModerationTestRepo{},
runtimeCacheTTL: ttl,
}
}
func runtimeCacheTestInput(text string) ContentModerationCheckInput {
return ContentModerationCheckInput{
Protocol: ContentModerationProtocolOpenAIChat,
Model: "risk-cache-test",
Body: []byte(`{"messages":[{"role":"user","content":"` + text + `"}]}`),
}
}
func TestContentModerationRuntimeSnapshotCachesSettings(t *testing.T) {
repo := &contentModerationRuntimeSettingRepo{values: map[string]string{
SettingKeyRiskControlEnabled: "true",
SettingKeyContentModerationConfig: runtimeCacheTestConfig(t, "blocked"),
}}
svc := runtimeCacheTestService(repo, time.Hour)
for range 20 {
decision, err := svc.Check(context.Background(), runtimeCacheTestInput("clean prompt"))
require.NoError(t, err)
require.True(t, decision.Allowed)
}
getValue, getMultiple := repo.calls()
require.Zero(t, getValue)
require.Equal(t, 1, getMultiple)
}
func TestContentModerationRuntimeSnapshotUpdateConfigIsImmediate(t *testing.T) {
repo := &contentModerationRuntimeSettingRepo{values: map[string]string{
SettingKeyRiskControlEnabled: "true",
SettingKeyContentModerationConfig: runtimeCacheTestConfig(t, "old-keyword"),
}}
svc := runtimeCacheTestService(repo, time.Hour)
decision, err := svc.Check(context.Background(), runtimeCacheTestInput("new-keyword"))
require.NoError(t, err)
require.True(t, decision.Allowed)
keywords := []string{"new-keyword"}
_, err = svc.UpdateConfig(context.Background(), UpdateContentModerationConfigInput{
BlockedKeywords: &keywords,
})
require.NoError(t, err)
decision, err = svc.Check(context.Background(), runtimeCacheTestInput("new-keyword"))
require.NoError(t, err)
require.True(t, decision.Blocked)
_, getMultiple := repo.calls()
require.Equal(t, 1, getMultiple)
}
func TestContentModerationRuntimeSnapshotUpdateWinsOverInitialLoad(t *testing.T) {
repo := &contentModerationRuntimeSettingRepo{values: map[string]string{
SettingKeyRiskControlEnabled: "true",
SettingKeyContentModerationConfig: runtimeCacheTestConfig(t, "old-keyword"),
}}
svc := runtimeCacheTestService(repo, time.Hour)
refreshStarted := make(chan struct{}, 1)
releaseRefresh := make(chan struct{})
released := false
defer func() {
if !released {
close(releaseRefresh)
}
}()
repo.blockNextMultiple(refreshStarted, releaseRefresh)
initialCheckDone := make(chan error, 1)
go func() {
decision, err := svc.Check(context.Background(), runtimeCacheTestInput("clean prompt"))
if err == nil && (decision == nil || !decision.Allowed) {
err = errors.New("unexpected initial moderation decision")
}
initialCheckDone <- err
}()
require.Eventually(t, func() bool {
select {
case <-refreshStarted:
return true
default:
return false
}
}, time.Second, time.Millisecond)
updateDone := make(chan error, 1)
go func() {
keywords := []string{"new-keyword"}
_, updateErr := svc.UpdateConfig(context.Background(), UpdateContentModerationConfigInput{
BlockedKeywords: &keywords,
})
updateDone <- updateErr
}()
select {
case updateErr := <-updateDone:
require.NoError(t, updateErr)
t.Fatal("configuration update completed before the initial load released its lock")
case <-time.After(10 * time.Millisecond):
}
close(releaseRefresh)
released = true
require.NoError(t, <-initialCheckDone)
require.NoError(t, <-updateDone)
decision, err := svc.Check(context.Background(), runtimeCacheTestInput("new-keyword"))
require.NoError(t, err)
require.True(t, decision.Blocked)
decision, err = svc.Check(context.Background(), runtimeCacheTestInput("old-keyword"))
require.NoError(t, err)
require.True(t, decision.Allowed)
}
func TestContentModerationRuntimeSnapshotRefreshFailureKeepsStaleConfig(t *testing.T) {
repo := &contentModerationRuntimeSettingRepo{values: map[string]string{
SettingKeyRiskControlEnabled: "true",
SettingKeyContentModerationConfig: runtimeCacheTestConfig(t, "blocked"),
}}
svc := runtimeCacheTestService(repo, time.Nanosecond)
input := runtimeCacheTestInput("blocked")
decision, err := svc.Check(context.Background(), input)
require.NoError(t, err)
require.True(t, decision.Blocked)
repo.failMultiple(errors.New("database unavailable"))
decision, err = svc.Check(context.Background(), input)
require.NoError(t, err)
require.True(t, decision.Blocked)
require.Eventually(t, func() bool {
_, calls := repo.calls()
return calls >= 2
}, time.Second, time.Millisecond)
}
func TestContentModerationRuntimeSnapshotRefreshFailureBacksOff(t *testing.T) {
repo := &contentModerationRuntimeSettingRepo{values: map[string]string{
SettingKeyRiskControlEnabled: "true",
SettingKeyContentModerationConfig: runtimeCacheTestConfig(t, "blocked"),
}}
svc := runtimeCacheTestService(repo, time.Minute)
input := runtimeCacheTestInput("blocked")
decision, err := svc.Check(context.Background(), input)
require.NoError(t, err)
require.True(t, decision.Blocked)
current := svc.runtimeSnapshot.Load()
require.NotNil(t, current)
expired := *current
expired.loadedAt = time.Now().Add(-2 * time.Minute)
svc.runtimeSnapshot.Store(&expired)
repo.failMultiple(errors.New("database unavailable"))
decision, err = svc.Check(context.Background(), input)
require.NoError(t, err)
require.True(t, decision.Blocked)
require.Eventually(t, func() bool {
_, calls := repo.calls()
return calls == 2
}, time.Second, time.Millisecond)
for range 100 {
decision, err = svc.Check(context.Background(), input)
require.NoError(t, err)
require.True(t, decision.Blocked)
}
_, calls := repo.calls()
require.Equal(t, 2, calls)
}
func TestContentModerationRuntimeSnapshotRefreshReusesUnchangedMatcher(t *testing.T) {
repo := &contentModerationRuntimeSettingRepo{values: map[string]string{
SettingKeyRiskControlEnabled: "true",
SettingKeyContentModerationConfig: runtimeCacheTestConfig(t, "blocked"),
}}
svc := runtimeCacheTestService(repo, time.Minute)
input := runtimeCacheTestInput("blocked")
decision, err := svc.Check(context.Background(), input)
require.NoError(t, err)
require.True(t, decision.Blocked)
current := svc.runtimeSnapshot.Load()
require.NotNil(t, current)
expired := *current
expired.loadedAt = time.Now().Add(-2 * time.Minute)
svc.runtimeSnapshot.Store(&expired)
decision, err = svc.Check(context.Background(), input)
require.NoError(t, err)
require.True(t, decision.Blocked)
require.Eventually(t, func() bool {
refreshed := svc.runtimeSnapshot.Load()
return refreshed != nil && refreshed.loadedAt.After(expired.loadedAt)
}, time.Second, time.Millisecond)
refreshed := svc.runtimeSnapshot.Load()
require.Same(t, current.config, refreshed.config)
require.Same(t, current.keywordMatcher, refreshed.keywordMatcher)
_, calls := repo.calls()
require.Equal(t, 2, calls)
}
func TestContentModerationRuntimeSnapshotUpdateWinsOverInFlightRefresh(t *testing.T) {
repo := &contentModerationRuntimeSettingRepo{values: map[string]string{
SettingKeyRiskControlEnabled: "true",
SettingKeyContentModerationConfig: runtimeCacheTestConfig(t, "old-keyword"),
}}
svc := runtimeCacheTestService(repo, time.Minute)
decision, err := svc.Check(context.Background(), runtimeCacheTestInput("old-keyword"))
require.NoError(t, err)
require.True(t, decision.Blocked)
current := svc.runtimeSnapshot.Load()
require.NotNil(t, current)
expired := *current
expired.loadedAt = time.Now().Add(-2 * time.Minute)
svc.runtimeSnapshot.Store(&expired)
refreshStarted := make(chan struct{}, 1)
releaseRefresh := make(chan struct{})
repo.blockNextMultiple(refreshStarted, releaseRefresh)
decision, err = svc.Check(context.Background(), runtimeCacheTestInput("clean prompt"))
require.NoError(t, err)
require.True(t, decision.Allowed)
require.Eventually(t, func() bool {
select {
case <-refreshStarted:
return true
default:
return false
}
}, time.Second, time.Millisecond)
updateDone := make(chan error, 1)
go func() {
keywords := []string{"new-keyword"}
_, updateErr := svc.UpdateConfig(context.Background(), UpdateContentModerationConfigInput{
BlockedKeywords: &keywords,
})
updateDone <- updateErr
}()
select {
case updateErr := <-updateDone:
require.NoError(t, updateErr)
t.Fatal("configuration update completed before the in-flight refresh released its lock")
case <-time.After(10 * time.Millisecond):
}
close(releaseRefresh)
require.NoError(t, <-updateDone)
decision, err = svc.Check(context.Background(), runtimeCacheTestInput("new-keyword"))
require.NoError(t, err)
require.True(t, decision.Blocked)
decision, err = svc.Check(context.Background(), runtimeCacheTestInput("old-keyword"))
require.NoError(t, err)
require.True(t, decision.Allowed)
}
func TestContentModerationRuntimeSnapshotConcurrentReadAndReplace(t *testing.T) {
repo := &contentModerationRuntimeSettingRepo{values: map[string]string{
SettingKeyRiskControlEnabled: "true",
SettingKeyContentModerationConfig: runtimeCacheTestConfig(t, "blocked-0"),
}}
svc := runtimeCacheTestService(repo, time.Hour)
_, err := svc.Check(context.Background(), runtimeCacheTestInput("clean prompt"))
require.NoError(t, err)
var wg sync.WaitGroup
errs := make(chan error, 8)
for range 8 {
wg.Add(1)
go func() {
defer wg.Done()
for range 100 {
decision, checkErr := svc.Check(context.Background(), runtimeCacheTestInput("clean prompt"))
if checkErr != nil {
errs <- checkErr
return
}
if decision == nil || !decision.Allowed {
errs <- errors.New("unexpected moderation decision")
return
}
}
}()
}
for i := 1; i <= 20; i++ {
keywords := []string{"blocked-" + time.Duration(i).String()}
_, err := svc.UpdateConfig(context.Background(), UpdateContentModerationConfigInput{
BlockedKeywords: &keywords,
})
require.NoError(t, err)
}
wg.Wait()
close(errs)
for err := range errs {
require.NoError(t, err)
}
}
+67 -6
View File
@@ -558,19 +558,80 @@ type ForwardResult struct {
ImageSizeBreakdown map[string]int
}
// UpstreamFailoverError indicates an upstream error that should trigger account failover.
// GatewayFailureStage identifies which request stage failed. The zero value is
// intentionally treated as inference so existing UpstreamFailoverError callers
// retain their current behavior.
type GatewayFailureStage string
const (
GatewayFailureStageInference GatewayFailureStage = "inference"
GatewayFailureStageAccountAuth GatewayFailureStage = "account_auth"
)
// GatewayFailureScope identifies whether selecting another account can help.
type GatewayFailureScope string
const (
GatewayFailureScopeAccount GatewayFailureScope = "account"
GatewayFailureScopeProvider GatewayFailureScope = "provider"
GatewayFailureScopeRequest GatewayFailureScope = "request"
)
// NextAccountAction is tri-state for backwards compatibility. The zero value
// means legacy retry behavior; only NextAccountStop explicitly short-circuits.
type NextAccountAction uint8
const (
NextAccountLegacyRetry NextAccountAction = iota
NextAccountRetry
NextAccountStop
)
type GatewayFailureReason string
// UpstreamFailoverError indicates an upstream or credential error that may
// trigger account failover. Additive metadata keeps existing composite literals
// source-compatible and preserves their legacy retry-next-account behavior.
type UpstreamFailoverError struct {
StatusCode int
ResponseBody []byte // 上游响应体,用于错误透传规则匹配
ResponseHeaders http.Header // 上游响应头,用于透传 cf-ray/cf-mitigated/content-type 等诊断信息
ForceCacheBilling bool // Antigravity 粘性会话切换时设为 true
RetryableOnSameAccount bool // 临时性错误(如 Google 间歇性 400、空响应),应在同一账号上重试 N 次再切换
StatusCode int
ResponseBody []byte // 上游响应体,用于错误透传规则匹配
ResponseHeaders http.Header // 上游响应头,用于透传 cf-ray/cf-mitigated/content-type 等诊断信息
ForceCacheBilling bool // Antigravity 粘性会话切换时设为 true
RetryableOnSameAccount bool // 临时性错误(如 Google 间歇性 400、空响应),应在同一账号上重试 N 次再切换
SafeToFailoverAfterWrite bool // 仅写出 SSE 注释等非语义字节时,仍可在同一客户端流中切换账号
Stage GatewayFailureStage
Scope GatewayFailureScope
Reason GatewayFailureReason
NextAccountAction NextAccountAction
ClientStatusCode int
ClientMessage string
}
func (e *UpstreamFailoverError) Error() string {
if e != nil && e.Stage == GatewayFailureStageAccountAuth {
return fmt.Sprintf("credential failure: %s (failover)", e.Reason)
}
return fmt.Sprintf("upstream error: %d (failover)", e.StatusCode)
}
func (e *UpstreamFailoverError) ShouldRetryNextAccount() bool {
return e != nil && e.NextAccountAction != NextAccountStop
}
func (e *UpstreamFailoverError) IsCredentialFailure() bool {
return e != nil && e.Stage == GatewayFailureStageAccountAuth
}
// ShouldReportAccountScheduleFailure prevents provider- and request-scoped
// credential failures from being misattributed to the selected account. Legacy
// and inference failures retain their existing scheduler-health behavior.
func (e *UpstreamFailoverError) ShouldReportAccountScheduleFailure() bool {
if e == nil {
return false
}
return !e.IsCredentialFailure() || e.Scope == GatewayFailureScopeAccount
}
// sseStreamErrorEventError 表示上游 SSE 流体内出现 event:error 帧。
// RawData 是该事件 data: 行的原始 JSON 字符串
// (Anthropic 标准结构 {"type":"error","error":{"type":"...","message":"..."}})。
@@ -0,0 +1,661 @@
package service
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"net/http"
"strings"
"time"
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
"github.com/gin-gonic/gin"
)
const (
grokCredentialFailoverDeadlineKey = "grok_credential_failover_deadline"
grokCredentialFailoverBudget = 15 * time.Second
grokCredentialMutationTimeout = 5 * time.Second
grokCredentialMutationConfirmWait = 250 * time.Millisecond
grokCredentialCacheCleanupTimeout = 500 * time.Millisecond
GrokCredentialUnavailableClientMessage = "No healthy Grok OAuth account is currently available"
GrokCredentialReasonRevoked GatewayFailureReason = "grok_oauth_credential_revoked"
GrokCredentialReasonMissing GatewayFailureReason = "grok_oauth_credentials_missing"
GrokCredentialReasonEntitlement GatewayFailureReason = "grok_oauth_entitlement_action_required"
GrokCredentialReasonProxyInvalid GatewayFailureReason = "grok_oauth_proxy_invalid"
GrokCredentialReasonRefreshTransient GatewayFailureReason = "grok_oauth_refresh_transient"
GrokCredentialReasonProviderConfig GatewayFailureReason = "grok_oauth_provider_config"
GrokCredentialReasonProviderDown GatewayFailureReason = "grok_oauth_provider_unavailable"
GrokCredentialReasonAccountChanged GatewayFailureReason = "grok_oauth_account_state_changed"
GrokCredentialReasonStateUpdate GatewayFailureReason = "grok_oauth_account_state_update_failed"
GrokCredentialReasonFailoverTimeout GatewayFailureReason = "grok_oauth_failover_timeout"
)
var errGrokCredentialStateUpdateFailed = errors.New("grok oauth account state update failed")
type grokCredentialFailureClass struct {
scope GatewayFailureScope
reason GatewayFailureReason
action NextAccountAction
permanent bool
transient bool
message string
snapshot *GrokCredentialMutationSnapshot
}
// GrokCredentialMutationSnapshot is the credential identity observed when the
// request selected an account. Repository mutations compare all fields before
// quarantining that account so a concurrent refresh cannot be overwritten.
type GrokCredentialMutationSnapshot struct {
CredentialsJSON string
AccessToken string
RefreshToken string
TokenVersion int64
ProxyID *int64
}
type grokCredentialFailureSnapshotError struct {
cause error
snapshot GrokCredentialMutationSnapshot
}
func (e *grokCredentialFailureSnapshotError) Error() string { return e.cause.Error() }
func (e *grokCredentialFailureSnapshotError) Unwrap() error { return e.cause }
func withGrokCredentialFailureSnapshot(err error, account *Account) error {
if err == nil || account == nil || !account.IsGrokOAuth() {
return err
}
var existing *grokCredentialFailureSnapshotError
if errors.As(err, &existing) {
return err
}
return &grokCredentialFailureSnapshotError{cause: err, snapshot: grokCredentialMutationSnapshot(account)}
}
func grokCredentialFailureSnapshot(err error) (GrokCredentialMutationSnapshot, bool) {
var snapshotErr *grokCredentialFailureSnapshotError
if !errors.As(err, &snapshotErr) || snapshotErr == nil {
return GrokCredentialMutationSnapshot{}, false
}
return snapshotErr.snapshot, true
}
type grokCredentialConditionalStateRepository interface {
SetGrokCredentialErrorIfMatch(context.Context, int64, GrokCredentialMutationSnapshot, string) (bool, error)
SetGrokCredentialTempUnschedulableIfMatch(context.Context, int64, GrokCredentialMutationSnapshot, time.Time, string) (bool, error)
}
// GetRequestCredential applies the request-path credential and failover contract
// before any upstream transport is opened.
func (s *OpenAIGatewayService) GetRequestCredential(ctx context.Context, c *gin.Context, account *Account) (string, string, error) {
return s.getRequestCredential(ctx, c, account)
}
func (s *OpenAIGatewayService) getRequestCredential(ctx context.Context, c *gin.Context, account *Account) (string, string, error) {
if ctx == nil {
ctx = context.Background()
}
if account == nil {
return "", "", errors.New("account is nil")
}
if !account.IsGrokOAuth() {
return s.GetAccessToken(ctx, account)
}
if err := ctx.Err(); err != nil {
return "", "", err
}
if s == nil || s.grokTokenProvider == nil {
return "", "", s.newGrokCredentialFailover(c, account, grokCredentialFailureClass{
scope: GatewayFailureScopeProvider,
reason: GrokCredentialReasonProviderConfig,
action: NextAccountStop,
message: "Grok OAuth credential provider is unavailable",
})
}
if s.isOpenAIAccountRuntimeBlocked(account) {
return "", "", s.newGrokCredentialFailover(c, account, grokCredentialFailureClass{
scope: GatewayFailureScopeAccount,
reason: GrokCredentialReasonAccountChanged,
action: NextAccountRetry,
message: "Grok OAuth account is not currently schedulable",
})
}
credentialCtx, cancel, budgetExpired := grokCredentialAcquisitionContext(ctx, c)
if cancel != nil {
defer cancel()
}
if budgetExpired {
return "", "", s.newGrokCredentialFailover(c, account, grokCredentialFailureClass{
scope: GatewayFailureScopeRequest,
reason: GrokCredentialReasonFailoverTimeout,
action: NextAccountStop,
message: "Grok OAuth credential failover budget exhausted",
})
}
token, kind, err := s.GetAccessToken(credentialCtx, account)
if err == nil {
if s.isOpenAIAccountRuntimeBlocked(account) {
return "", "", s.newGrokCredentialFailover(c, account, grokCredentialFailureClass{
scope: GatewayFailureScopeAccount,
reason: GrokCredentialReasonAccountChanged,
action: NextAccountRetry,
message: "Grok OAuth account is not currently schedulable",
})
}
return token, kind, nil
}
if parentErr := ctx.Err(); parentErr != nil {
return "", "", parentErr
}
if credentialCtx.Err() != nil {
return "", "", s.newGrokCredentialFailover(c, account, grokCredentialFailureClass{
scope: GatewayFailureScopeRequest,
reason: GrokCredentialReasonFailoverTimeout,
action: NextAccountStop,
message: "Grok OAuth credential failover budget exhausted",
})
}
class := classifyGrokCredentialFailure(account, err)
if snapshot, ok := grokCredentialFailureSnapshot(err); ok {
class.snapshot = &snapshot
}
if ctx.Err() != nil {
return "", "", ctx.Err()
}
if class.permanent || class.transient {
freshToken, mutationErr := s.applyGrokCredentialAccountFailure(credentialCtx, account, class)
if freshToken != "" {
return freshToken, "oauth", nil
}
if mutationErr != nil {
if ctx.Err() != nil {
return "", "", ctx.Err()
}
if credentialCtx.Err() != nil {
return "", "", s.newGrokCredentialFailover(c, account, grokCredentialFailureClass{
scope: GatewayFailureScopeRequest,
reason: GrokCredentialReasonFailoverTimeout,
action: NextAccountStop,
message: "Grok OAuth credential failover budget exhausted",
})
}
if errors.Is(mutationErr, errOAuthRefreshAccountStateChanged) {
class = grokCredentialFailureClass{
scope: GatewayFailureScopeAccount,
reason: GrokCredentialReasonAccountChanged,
action: NextAccountRetry,
message: "Grok OAuth account eligibility changed",
}
} else if errors.Is(mutationErr, errOAuthRefreshAccountRereadFailed) {
class = grokCredentialFailureClass{
scope: GatewayFailureScopeProvider,
reason: GrokCredentialReasonProviderDown,
action: NextAccountStop,
message: "Grok OAuth account state is temporarily unavailable",
}
} else {
class = grokCredentialFailureClass{
scope: GatewayFailureScopeProvider,
reason: GrokCredentialReasonStateUpdate,
action: NextAccountStop,
message: "Grok OAuth account state could not be updated safely",
}
}
}
}
return "", "", s.newGrokCredentialFailover(c, account, class)
}
func grokCredentialAcquisitionContext(ctx context.Context, c *gin.Context) (context.Context, context.CancelFunc, bool) {
if c == nil {
return ctx, nil, false
}
deadline := time.Time{}
if raw, ok := c.Get(grokCredentialFailoverDeadlineKey); ok {
deadline, _ = raw.(time.Time)
}
if deadline.IsZero() {
deadline = time.Now().Add(grokCredentialFailoverBudget)
c.Set(grokCredentialFailoverDeadlineKey, deadline)
}
if !time.Now().Before(deadline) {
return ctx, nil, true
}
acquireCtx, cancel := context.WithDeadline(ctx, deadline)
return acquireCtx, cancel, false
}
func classifyGrokCredentialFailure(account *Account, err error) grokCredentialFailureClass {
stableReason := strings.ToLower(strings.TrimSpace(infraerrors.Reason(err)))
message := ""
if err != nil {
message = strings.ToLower(err.Error())
}
contains := func(values ...string) bool {
for _, value := range values {
if strings.Contains(stableReason, value) || strings.Contains(message, value) {
return true
}
}
return false
}
var providerConfigErr *providerConfigurationRefreshError
var containmentErr *providerCycleContainmentRefreshError
switch {
case errors.Is(err, errGrokOAuthRefreshTokenMissing), errors.Is(err, errGrokOAuthAccessTokenMissing), errors.Is(err, errGrokOAuthAccessTokenExpired):
return grokCredentialFailureClass{scope: GatewayFailureScopeAccount, reason: GrokCredentialReasonMissing, action: NextAccountRetry, permanent: true, message: "Grok OAuth credentials are missing or expired"}
case contains("invalid_grant", "invalid_refresh_token", "token_expired", "refresh_token_reused", "refresh_token_invalidated", "app_session_terminated"):
return grokCredentialFailureClass{scope: GatewayFailureScopeAccount, reason: GrokCredentialReasonRevoked, action: NextAccountRetry, permanent: true, message: "Grok OAuth credentials require account action"}
case contains("grok_oauth_entitlement_denied", "entitlement_denied", "access_denied", "subscription required", "no active grok subscription"):
return grokCredentialFailureClass{scope: GatewayFailureScopeAccount, reason: GrokCredentialReasonEntitlement, action: NextAccountRetry, permanent: true, message: "Grok OAuth entitlement requires account action"}
case errors.Is(err, errGrokOAuthConfiguredProxyMiss), contains("grok_oauth_proxy_not_found"):
return grokCredentialFailureClass{scope: GatewayFailureScopeAccount, reason: GrokCredentialReasonProxyInvalid, action: NextAccountRetry, permanent: true, message: "Grok OAuth account proxy configuration is invalid"}
case errors.Is(err, errOAuthRefreshAccountRereadFailed):
return grokCredentialFailureClass{scope: GatewayFailureScopeProvider, reason: GrokCredentialReasonProviderDown, action: NextAccountStop, message: "Grok OAuth account state is temporarily unavailable"}
case errors.Is(err, errOAuthRefreshCredentialPersist):
return grokCredentialFailureClass{scope: GatewayFailureScopeProvider, reason: GrokCredentialReasonProviderDown, action: NextAccountStop, message: "Grok OAuth shared credential state is temporarily unavailable"}
case errors.As(err, &containmentErr):
return grokCredentialFailureClass{scope: GatewayFailureScopeProvider, reason: GrokCredentialReasonProviderDown, action: NextAccountStop, message: "Grok OAuth provider state is temporarily unavailable"}
case errors.Is(err, errOAuthRefreshAccountStateChanged):
return grokCredentialFailureClass{scope: GatewayFailureScopeAccount, reason: GrokCredentialReasonAccountChanged, action: NextAccountRetry, message: "Grok OAuth account eligibility changed"}
case errors.As(err, &providerConfigErr):
return grokCredentialFailureClass{scope: GatewayFailureScopeProvider, reason: GrokCredentialReasonProviderConfig, action: NextAccountStop, message: "Grok OAuth provider configuration is unavailable"}
case errors.Is(err, errGrokOAuthRefreshNotConfigured), contains("invalid_client", "unauthorized_client", "invalid_scope", "unknown scope", "grok oauth service is not configured", "grok_oauth_proxy_not_available"):
return grokCredentialFailureClass{scope: GatewayFailureScopeProvider, reason: GrokCredentialReasonProviderConfig, action: NextAccountStop, message: "Grok OAuth provider configuration is unavailable"}
case contains("grok_oauth_proxy_lookup_failed"),
contains("grok_oauth_token_refresh_failed") && contains("status 403") && (account == nil || account.ProxyID == nil):
return grokCredentialFailureClass{scope: GatewayFailureScopeProvider, reason: GrokCredentialReasonProviderDown, action: NextAccountStop, message: "Grok OAuth provider is temporarily unavailable"}
case contains("grok_oauth_client_init_failed") && (account == nil || account.ProxyID == nil):
return grokCredentialFailureClass{scope: GatewayFailureScopeProvider, reason: GrokCredentialReasonProviderConfig, action: NextAccountStop, message: "Grok OAuth provider configuration is unavailable"}
case contains("grok_oauth_request_failed") && (account == nil || account.ProxyID == nil):
return grokCredentialFailureClass{scope: GatewayFailureScopeProvider, reason: GrokCredentialReasonProviderDown, action: NextAccountStop, message: "Grok OAuth provider is temporarily unavailable"}
case contains("status 429", "status 500", "status 502", "status 503", "status 504") && (account == nil || account.ProxyID == nil):
return grokCredentialFailureClass{scope: GatewayFailureScopeProvider, reason: GrokCredentialReasonProviderDown, action: NextAccountStop, message: "Grok OAuth provider is temporarily unavailable"}
default:
return grokCredentialFailureClass{scope: GatewayFailureScopeAccount, reason: GrokCredentialReasonRefreshTransient, action: NextAccountRetry, transient: true, message: "Grok OAuth credential refresh is temporarily unavailable"}
}
}
func (s *OpenAIGatewayService) applyGrokCredentialAccountFailure(ctx context.Context, account *Account, class grokCredentialFailureClass) (string, error) {
if s == nil || account == nil || ctx == nil || ctx.Err() != nil {
if ctx != nil {
return "", ctx.Err()
}
return "", context.Canceled
}
mutationMu := s.grokCredentialMutationLock(account.ID)
if err := mutationMu.Lock(ctx); err != nil {
return "", err
}
defer mutationMu.Unlock()
stateRepo, hasConditionalStateRepo := s.accountRepo.(grokCredentialConditionalStateRepository)
snapshot := grokCredentialMutationSnapshot(account)
if class.snapshot != nil {
snapshot = *class.snapshot
}
if token, err := s.validateCurrentGrokCredentialFailure(ctx, account.ID, snapshot, class); err != nil || token != "" {
return token, err
}
if class.permanent {
if token, ok := s.grokCredentialConcurrentlyRefreshedToken(ctx, account.ID, snapshot); ok {
return token, nil
}
if ctx.Err() != nil {
return "", ctx.Err()
}
rollbackRuntime := s.blockGrokCredentialRuntime(account, time.Time{}, string(class.reason))
keepRuntimeBlock := false
runtimeRollbackDone := false
defer func() {
if !keepRuntimeBlock && !runtimeRollbackDone {
rollbackRuntime()
}
}()
if s.accountRepo == nil {
keepRuntimeBlock = true
return "", fmt.Errorf("%w: account repository is not configured", errGrokCredentialStateUpdateFailed)
}
if !hasConditionalStateRepo {
keepRuntimeBlock = true
return "", fmt.Errorf("%w: conditional account repository is not configured", errGrokCredentialStateUpdateFailed)
}
stateCtx, cancel := context.WithTimeout(ctx, grokCredentialMutationTimeout)
if err := ctx.Err(); err != nil {
cancel()
return "", err
}
updated, err := stateRepo.SetGrokCredentialErrorIfMatch(stateCtx, account.ID, snapshot, string(class.reason))
requestErr := ctx.Err()
cancel()
if err != nil {
slog.Warn("grok_credential_failure.set_error_failed", "account_id", account.ID, "reason", class.reason, "error", err)
if requestErr != nil || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
if s.grokCredentialMutationCommitted(account.ID, class, time.Time{}) {
updated = true
} else if requestErr != nil {
return "", requestErr
} else {
keepRuntimeBlock = true
return "", fmt.Errorf("%w: permanent state commit could not be confirmed: %v", errGrokCredentialStateUpdateFailed, err)
}
} else {
keepRuntimeBlock = true
return "", fmt.Errorf("%w: persist permanent state: %v", errGrokCredentialStateUpdateFailed, err)
}
}
if !updated {
rollbackRuntime()
runtimeRollbackDone = true
return s.resolveGrokCredentialCASMiss(ctx, account.ID, snapshot)
}
// SetError is the linearization point: the durable quarantine is now
// committed and this node's runtime block must not be rolled back.
keepRuntimeBlock = true
if s.grokTokenProvider == nil {
if ctx.Err() != nil {
return "", ctx.Err()
}
return "", fmt.Errorf("%w: token provider is not configured", errGrokCredentialStateUpdateFailed)
}
invalidateCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), grokCredentialCacheCleanupTimeout)
err = s.grokTokenProvider.InvalidateToken(invalidateCtx, account)
cancel()
if err != nil {
slog.Warn("grok_credential_failure.invalidate_token_failed", "account_id", account.ID, "reason", class.reason, "error", err)
if ctx.Err() != nil {
return "", ctx.Err()
}
return "", fmt.Errorf("%w: invalidate cached credential: %v", errGrokCredentialStateUpdateFailed, err)
}
if ctx.Err() != nil {
return "", ctx.Err()
}
return "", nil
}
if class.transient {
until := time.Now().Add(tokenRefreshTempUnschedDuration)
if ctx.Err() != nil {
return "", ctx.Err()
}
rollbackRuntime := s.blockGrokCredentialRuntime(account, until, string(class.reason))
keepRuntimeBlock := false
runtimeRollbackDone := false
defer func() {
if !keepRuntimeBlock && !runtimeRollbackDone {
rollbackRuntime()
}
}()
stateCtx, cancel := context.WithTimeout(ctx, grokCredentialMutationTimeout)
if s.accountRepo == nil {
cancel()
keepRuntimeBlock = true
return "", fmt.Errorf("%w: account repository is not configured", errGrokCredentialStateUpdateFailed)
}
if !hasConditionalStateRepo {
cancel()
keepRuntimeBlock = true
return "", fmt.Errorf("%w: conditional account repository is not configured", errGrokCredentialStateUpdateFailed)
}
if err := ctx.Err(); err != nil {
cancel()
return "", err
}
updated, err := stateRepo.SetGrokCredentialTempUnschedulableIfMatch(stateCtx, account.ID, snapshot, until, string(class.reason))
requestErr := ctx.Err()
cancel()
if err != nil {
slog.Warn("grok_credential_failure.set_temp_unschedulable_failed", "account_id", account.ID, "reason", class.reason, "error", err)
if requestErr != nil || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
if s.grokCredentialMutationCommitted(account.ID, class, until) {
updated = true
} else if requestErr != nil {
return "", requestErr
} else {
keepRuntimeBlock = true
return "", fmt.Errorf("%w: transient state commit could not be confirmed: %v", errGrokCredentialStateUpdateFailed, err)
}
} else {
keepRuntimeBlock = true
return "", fmt.Errorf("%w: persist transient state: %v", errGrokCredentialStateUpdateFailed, err)
}
}
if !updated {
rollbackRuntime()
runtimeRollbackDone = true
return s.resolveGrokCredentialCASMiss(ctx, account.ID, snapshot)
}
// The temporary quarantine is durable after SetTempUnschedulable succeeds.
keepRuntimeBlock = true
if ctx.Err() != nil {
return "", ctx.Err()
}
return "", nil
}
return "", nil
}
func (s *OpenAIGatewayService) validateCurrentGrokCredentialFailure(
ctx context.Context,
accountID int64,
snapshot GrokCredentialMutationSnapshot,
class grokCredentialFailureClass,
) (string, error) {
if s == nil || s.accountRepo == nil || accountID <= 0 || ctx == nil || ctx.Err() != nil {
if ctx != nil {
return "", ctx.Err()
}
return "", context.Canceled
}
checkCtx, cancel := context.WithTimeout(ctx, time.Second)
defer cancel()
latest, err := s.accountRepo.GetByID(checkCtx, accountID)
if err != nil {
if errors.Is(err, ErrAccountNotFound) {
return "", errOAuthRefreshAccountStateChanged
}
return "", fmt.Errorf("%w: %v", errOAuthRefreshAccountRereadFailed, err)
}
if latest == nil || !latest.IsGrokOAuth() || !latest.IsSchedulable() || s.isOpenAIAccountRuntimeBlocked(latest) {
return "", errOAuthRefreshAccountStateChanged
}
latestSnapshot := grokCredentialMutationSnapshot(latest)
if latestSnapshot.CredentialsJSON != snapshot.CredentialsJSON ||
!grokCredentialProxyIDsEqual(latestSnapshot.ProxyID, snapshot.ProxyID) {
if token, ok := s.grokCredentialConcurrentlyRefreshedToken(ctx, accountID, snapshot); ok {
return token, nil
}
return "", errOAuthRefreshAccountStateChanged
}
// A configured proxy is external to the account-row CAS identity. Recheck
// the hydrated proxy object so restoring a deleted row under the same ID
// wins over a stale proxy-invalid failure.
if class.reason == GrokCredentialReasonProxyInvalid {
if latest.ProxyID == nil || latest.Proxy != nil {
return "", errOAuthRefreshAccountStateChanged
}
} else if latest.ProxyID != nil && latest.Proxy == nil {
return "", errOAuthRefreshAccountStateChanged
}
if class.reason == GrokCredentialReasonMissing {
expiresAt := latest.GetCredentialAsTime("expires_at")
credentialsStillMissing := strings.TrimSpace(latest.GetGrokAccessToken()) == "" ||
strings.TrimSpace(latest.GetGrokRefreshToken()) == "" || expiresAt == nil || !time.Now().Before(*expiresAt)
if !credentialsStillMissing {
return "", errOAuthRefreshAccountStateChanged
}
}
return "", nil
}
func (s *OpenAIGatewayService) grokCredentialMutationLock(accountID int64) *oauthRefreshLocalLock {
actual, _ := s.grokCredentialMutationLocks.LoadOrStore(accountID, newOAuthRefreshLocalLock())
mu, ok := actual.(*oauthRefreshLocalLock)
if !ok {
mu = newOAuthRefreshLocalLock()
s.grokCredentialMutationLocks.Store(accountID, mu)
}
return mu
}
func (s *OpenAIGatewayService) grokCredentialMutationCommitted(accountID int64, class grokCredentialFailureClass, until time.Time) bool {
if s == nil || s.accountRepo == nil || accountID <= 0 {
return false
}
confirmCtx, cancel := context.WithTimeout(context.Background(), grokCredentialMutationConfirmWait)
defer cancel()
latest, err := s.accountRepo.GetByID(confirmCtx, accountID)
if err != nil || latest == nil {
return false
}
if class.permanent {
return latest.Status == StatusError && !latest.Schedulable && latest.ErrorMessage == string(class.reason)
}
if class.transient {
return latest.TempUnschedulableUntil != nil && !latest.TempUnschedulableUntil.Before(until) &&
latest.TempUnschedulableReason == string(class.reason)
}
return false
}
func grokCredentialMutationSnapshot(account *Account) GrokCredentialMutationSnapshot {
if account == nil {
return GrokCredentialMutationSnapshot{}
}
credentialsJSON := "null"
if encoded, err := json.Marshal(account.Credentials); err == nil {
credentialsJSON = string(encoded)
}
snapshot := GrokCredentialMutationSnapshot{
CredentialsJSON: credentialsJSON,
AccessToken: strings.TrimSpace(account.GetGrokAccessToken()),
RefreshToken: strings.TrimSpace(account.GetGrokRefreshToken()),
TokenVersion: account.GetCredentialAsInt64("_token_version"),
}
if account.ProxyID != nil {
proxyID := *account.ProxyID
snapshot.ProxyID = &proxyID
}
return snapshot
}
func (s *OpenAIGatewayService) resolveGrokCredentialCASMiss(ctx context.Context, accountID int64, snapshot GrokCredentialMutationSnapshot) (string, error) {
if ctx.Err() != nil {
return "", ctx.Err()
}
if token, ok := s.grokCredentialConcurrentlyRefreshedToken(ctx, accountID, snapshot); ok {
return token, nil
}
return "", errOAuthRefreshAccountStateChanged
}
func (s *OpenAIGatewayService) blockGrokCredentialRuntime(account *Account, until time.Time, reason string) func() {
if s == nil || account == nil {
return func() {}
}
mu := s.openAIAccountRuntimeBlockLock(account.ID)
mu.Lock()
before, hadBefore := s.openaiAccountRuntimeBlockUntil.Load(account.ID)
installedGeneration, changed := s.blockAccountSchedulingLocked(account, until, reason)
installed, installedOK := s.openaiAccountRuntimeBlockUntil.Load(account.ID)
installedUntil, isTime := installed.(time.Time)
mu.Unlock()
if !changed || !installedOK || !isTime {
return func() {}
}
if hadBefore {
if beforeUntil, ok := before.(time.Time); ok && beforeUntil.Equal(installedUntil) {
return func() {}
}
}
return func() {
mu.Lock()
defer mu.Unlock()
generation, ok := s.openaiAccountRuntimeBlockGeneration.Load(account.ID)
if !ok || generation != installedGeneration {
return
}
current, ok := s.openaiAccountRuntimeBlockUntil.Load(account.ID)
currentUntil, isTime := current.(time.Time)
if !ok || !isTime || !currentUntil.Equal(installedUntil) {
return
}
if hadBefore {
s.openaiAccountRuntimeBlockUntil.Store(account.ID, before)
s.openaiAccountRuntimeBlockGeneration.Store(account.ID, s.openaiAccountRuntimeBlockSequence.Add(1))
return
}
s.openaiAccountRuntimeBlockUntil.Delete(account.ID)
s.openaiAccountRuntimeBlockGeneration.Store(account.ID, s.openaiAccountRuntimeBlockSequence.Add(1))
}
}
func (s *OpenAIGatewayService) grokCredentialConcurrentlyRefreshedToken(ctx context.Context, accountID int64, baseline GrokCredentialMutationSnapshot) (string, bool) {
if s == nil || s.accountRepo == nil || accountID <= 0 || ctx == nil || ctx.Err() != nil {
return "", false
}
checkCtx, cancel := context.WithTimeout(ctx, time.Second)
defer cancel()
latest, err := s.accountRepo.GetByID(checkCtx, accountID)
if err != nil || latest == nil {
return "", false
}
latestSnapshot := grokCredentialMutationSnapshot(latest)
if !grokCredentialProxyIDsEqual(latestSnapshot.ProxyID, baseline.ProxyID) ||
latestSnapshot.CredentialsJSON == baseline.CredentialsJSON || !latest.IsSchedulable() ||
(latest.ProxyID != nil && latest.Proxy == nil) || s.isOpenAIAccountRuntimeBlocked(latest) {
return "", false
}
latestToken := strings.TrimSpace(latest.GetGrokAccessToken())
if latestToken == "" || strings.TrimSpace(latest.GetGrokRefreshToken()) == "" {
return "", false
}
expiresAt := latest.GetCredentialAsTime("expires_at")
if expiresAt == nil || !time.Now().Before(*expiresAt) {
return "", false
}
return latestToken, true
}
func grokCredentialProxyIDsEqual(left, right *int64) bool {
if left == nil || right == nil {
return left == nil && right == nil
}
return *left == *right
}
func (s *OpenAIGatewayService) newGrokCredentialFailover(c *gin.Context, account *Account, class grokCredentialFailureClass) error {
if strings.TrimSpace(class.message) == "" {
class.message = "Grok OAuth credentials are unavailable"
}
appendOpsUpstreamError(c, OpsUpstreamErrorEvent{
Platform: PlatformGrok,
AccountID: account.ID,
Stage: string(GatewayFailureStageAccountAuth),
Scope: string(class.scope),
Reason: string(class.reason),
Kind: "credential_failover",
Message: class.message,
})
return &UpstreamFailoverError{
Stage: GatewayFailureStageAccountAuth,
Scope: class.scope,
Reason: class.reason,
NextAccountAction: class.action,
ClientStatusCode: http.StatusServiceUnavailable,
ClientMessage: GrokCredentialUnavailableClientMessage,
}
}
File diff suppressed because it is too large. Load diff
+7 -24
View File
@@ -13,7 +13,6 @@ import (
"strings"
"time"
"github.com/Wei-Shaw/sub2api/internal/pkg/xai"
"github.com/Wei-Shaw/sub2api/internal/util/responseheaders"
"github.com/gin-gonic/gin"
"github.com/tidwall/gjson"
@@ -268,25 +267,6 @@ func (s *OpenAIGatewayService) BindGrokMediaVideoRequestAccount(ctx context.Cont
return s.BindStickySession(ctx, groupID, GrokMediaVideoRequestSessionHash(requestID), accountID)
}
func (e GrokMediaEndpoint) upstreamURL(baseURL, requestID string) (string, error) {
switch e {
case GrokMediaEndpointImagesGenerations:
return xai.BuildImagesGenerationsURL(baseURL)
case GrokMediaEndpointImagesEdits:
return xai.BuildImagesEditsURL(baseURL)
case GrokMediaEndpointVideosGenerations:
return xai.BuildVideosGenerationsURL(baseURL)
case GrokMediaEndpointVideosEdits:
return xai.BuildVideosEditsURL(baseURL)
case GrokMediaEndpointVideosExtensions:
return xai.BuildVideosExtensionsURL(baseURL)
case GrokMediaEndpointVideoStatus:
return xai.BuildVideoURL(baseURL, requestID)
default:
return "", fmt.Errorf("unsupported grok media endpoint: %s", e)
}
}
func (s *OpenAIGatewayService) ForwardGrokMedia(
ctx context.Context,
c *gin.Context,
@@ -304,11 +284,11 @@ func (s *OpenAIGatewayService) ForwardGrokMedia(
return nil, fmt.Errorf("account platform %s is not supported for grok media", account.Platform)
}
token, _, err := s.GetAccessToken(ctx, account)
token, _, err := s.getRequestCredential(ctx, c, account)
if err != nil {
return nil, err
}
targetURL, err := endpoint.upstreamURL(account.GetGrokMediaBaseURL(), requestID)
targetURL, err := buildGrokMediaURL(account, s.cfg, endpoint, requestID)
if err != nil {
return nil, err
}
@@ -339,7 +319,9 @@ func (s *OpenAIGatewayService) ForwardGrokMedia(
}
upstreamReq.Header.Set("Authorization", "Bearer "+token)
upstreamReq.Header.Set("Accept", "application/json")
applyGrokCLIHeaders(upstreamReq.Header)
if account.IsGrokOAuth() {
applyGrokCLIHeaders(upstreamReq.Header)
}
if endpoint.RequiresRequestBody() {
contentType = strings.TrimSpace(contentType)
if contentType == "" {
@@ -366,7 +348,7 @@ func (s *OpenAIGatewayService) ForwardGrokMedia(
return s.handleGrokMediaErrorResponse(ctx, resp, c, account, requestIDHeader, requestModel)
}
s.updateGrokUsageSnapshot(ctx, account, xai.ParseQuotaHeaders(resp.Header, resp.StatusCode))
s.updateGrokUsageFromResponse(ctx, account, resp.Header, resp.StatusCode)
respBody, err := ReadUpstreamResponseBody(resp.Body, s.cfg, c, openAITooLargeError)
if err != nil {
return nil, err
@@ -635,6 +617,7 @@ func (s *OpenAIGatewayService) handleGrokMediaErrorResponse(
return nil, &UpstreamFailoverError{
StatusCode: resp.StatusCode,
ResponseBody: body,
ResponseHeaders: resp.Header.Clone(),
RetryableOnSameAccount: account.IsPoolMode() && account.IsPoolModeRetryableStatus(resp.StatusCode),
}
}
@@ -0,0 +1,345 @@
package service
import (
"context"
"errors"
"fmt"
"strings"
"time"
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
)
const (
defaultGrokOAuthReconcilePageSize = 50
maxGrokOAuthReconcilePageSize = 500
maxGrokOAuthReconcileWindow = 24 * time.Hour
GrokOAuthReconcileReasonMissingRefreshToken = "missing_refresh_token"
GrokOAuthReconcileReasonMissingAccessToken = "missing_access_token"
GrokOAuthReconcileReasonMissingExpiry = "missing_expiry"
GrokOAuthReconcileReasonInvalidExpiry = "invalid_expiry"
GrokOAuthReconcileReasonNearExpiry = "near_expiry"
GrokOAuthReconcileReasonCredentialRejected = "credential_rejected"
GrokOAuthReconcileActionBlock = "block_account"
GrokOAuthReconcileActionRefresh = "refresh_credentials"
GrokOAuthReconcileOutcomePlanned = "planned"
GrokOAuthReconcileOutcomeApplied = "applied"
GrokOAuthReconcileOutcomeSkipped = "skipped"
GrokOAuthReconcileOutcomeFailed = "failed"
GrokOAuthReconcileOutcomePartial = "partial"
)
var (
ErrGrokOAuthReconcileMode = infraerrors.BadRequest(
"GROK_OAUTH_RECONCILE_MODE_INVALID",
"apply requires dry_run=false and apply=true",
)
ErrGrokOAuthReconcileCursor = infraerrors.BadRequest(
"GROK_OAUTH_RECONCILE_CURSOR_INVALID",
"after_id must be non-negative",
)
ErrGrokOAuthReconcileLimit = infraerrors.BadRequest(
"GROK_OAUTH_RECONCILE_LIMIT_INVALID",
"limit is outside the allowed reconciliation page range",
)
ErrGrokOAuthReconcileWindow = infraerrors.BadRequest(
"GROK_OAUTH_RECONCILE_WINDOW_INVALID",
"refresh_window_seconds is outside the allowed range",
)
)
// GrokOAuthReconciler is the narrow admin-facing reconciliation port.
type GrokOAuthReconciler interface {
ReconcileGrokOAuth(ctx context.Context, input GrokOAuthReconcileInput) (*GrokOAuthReconcileResult, error)
}
// GrokOAuthConditionalErrorRepository is the narrow compare-and-set mutation
// used by reconciliation. The repository must only transition an active Grok
// OAuth account when its credential document still exactly matches the state
// observed immediately before the mutation.
type GrokOAuthConditionalErrorRepository interface {
SetGrokOAuthErrorIfCredentialsUnchanged(ctx context.Context, id int64, expectedCredentials map[string]any, errorMsg string) (bool, error)
}
type GrokOAuthReconcileInput struct {
DryRun bool
Apply bool
AfterID int64
Limit int
RefreshWindow time.Duration
}
// GrokOAuthReconcileItem is deliberately metadata-only. Credentials, account
// identity fields, provider response bodies, and raw errors never cross this API.
type GrokOAuthReconcileItem struct {
AccountID int64 `json:"account_id"`
Reason string `json:"reason"`
Action string `json:"action"`
Outcome string `json:"outcome"`
}
type GrokOAuthReconcileResult struct {
DryRun bool `json:"dry_run"`
Scanned int `json:"scanned"`
Actionable int `json:"actionable"`
WouldBlock int `json:"would_block"`
WouldRefresh int `json:"would_refresh"`
Blocked int `json:"blocked"`
Refreshed int `json:"refreshed"`
Skipped int `json:"skipped"`
Failed int `json:"failed"`
Partial int `json:"partial"`
Items []GrokOAuthReconcileItem `json:"items"`
NextAfterID int64 `json:"next_after_id"`
HasMore bool `json:"has_more"`
}
func (s *TokenRefreshService) ReconcileGrokOAuth(ctx context.Context, input GrokOAuthReconcileInput) (*GrokOAuthReconcileResult, error) {
if ctx == nil {
ctx = context.Background()
}
if input.Apply && input.DryRun {
return nil, ErrGrokOAuthReconcileMode
}
if input.AfterID < 0 {
return nil, ErrGrokOAuthReconcileCursor
}
limit := input.Limit
maxPageSize := s.grokOAuthReconcileMaxPageSize()
if limit == 0 {
limit = min(defaultGrokOAuthReconcilePageSize, maxPageSize)
}
if limit < 1 || limit > maxPageSize {
return nil, ErrGrokOAuthReconcileLimit
}
refreshWindow := input.RefreshWindow
if refreshWindow == 0 {
refreshWindow = grokTokenRefreshSkew
}
if refreshWindow < 0 || refreshWindow > maxGrokOAuthReconcileWindow {
return nil, ErrGrokOAuthReconcileWindow
}
if refreshWindow < grokTokenRefreshSkew {
refreshWindow = grokTokenRefreshSkew
}
dryRun := !input.Apply
pager := s.candidatePager
if pager == nil {
pager, _ = s.accountRepo.(OAuthRefreshCandidatePager)
}
if pager == nil {
return nil, errors.New("OAuth refresh candidate pager is not configured")
}
page, err := pager.ListOAuthRefreshCandidatePage(ctx, OAuthRefreshPageOptions{
Platforms: []string{PlatformGrok},
AfterID: input.AfterID,
Limit: limit,
ActiveOnly: true,
// Reconciliation scans OAuth only and intentionally does not require a
// refresh token so structurally invalid rows remain discoverable.
IncludeSetupToken: false,
RequireRefreshToken: false,
})
if err != nil {
return nil, err
}
if page == nil {
return nil, errors.New("OAuth reconciliation repository returned a nil cursor page")
}
accounts := page.Accounts
if !isStrictlyIncreasingAccountPage(accounts, input.AfterID) {
return nil, errors.New("OAuth reconciliation repository returned an invalid cursor page")
}
result := &GrokOAuthReconcileResult{
DryRun: dryRun,
Scanned: len(accounts),
Items: make([]GrokOAuthReconcileItem, 0, len(accounts)),
HasMore: page.HasMore,
}
if result.HasMore {
if page.NextAfterID <= input.AfterID {
return nil, errors.New("OAuth reconciliation repository returned invalid cursor metadata")
}
result.NextAfterID = page.NextAfterID
}
registration, ok := s.grokRegistration()
if !ok {
return nil, errors.New("grok OAuth refresher is not registered")
}
conditionalErrorRepo, supportsConditionalError := s.accountRepo.(GrokOAuthConditionalErrorRepository)
if input.Apply && !supportsConditionalError {
return nil, errors.New("grok OAuth conditional error mutation is not configured")
}
providerState := &tokenRefreshProviderState{
service: s,
registration: registration,
rateGate: s.providerRateGate(PlatformGrok),
poolGate: s.providerConcurrencyGate(PlatformGrok),
}
for i := range accounts {
if err := ctx.Err(); err != nil {
return nil, err
}
account := &accounts[i]
reason, action, actionable := classifyGrokOAuthReconcileAccount(account, refreshWindow)
if !actionable {
result.Skipped++
continue
}
result.Actionable++
item := GrokOAuthReconcileItem{
AccountID: account.ID,
Reason: reason,
Action: action,
Outcome: GrokOAuthReconcileOutcomePlanned,
}
if action == GrokOAuthReconcileActionBlock {
result.WouldBlock++
} else {
result.WouldRefresh++
}
if dryRun {
result.Items = append(result.Items, item)
continue
}
switch action {
case GrokOAuthReconcileActionBlock:
latest, err := s.accountRepo.GetByID(ctx, account.ID)
if err != nil || latest == nil {
item.Outcome = GrokOAuthReconcileOutcomeFailed
result.Failed++
break
}
latestReason, latestAction, stillActionable := classifyGrokOAuthReconcileAccount(latest, refreshWindow)
if !stillActionable || latestAction != GrokOAuthReconcileActionBlock {
// The account changed after page hydration (for example, an admin
// reauthorized it). Never apply a stale destructive action; the next
// resumable scan can plan the fresh state.
item.Outcome = GrokOAuthReconcileOutcomeSkipped
result.Skipped++
break
}
account = latest
item.Reason = latestReason
applied, err := conditionalErrorRepo.SetGrokOAuthErrorIfCredentialsUnchanged(
ctx,
account.ID,
account.Credentials,
"Grok OAuth credential reconciliation: missing refresh token",
)
if err != nil {
item.Outcome = GrokOAuthReconcileOutcomeFailed
result.Failed++
break
}
if !applied {
// Reauthorization won the compare-and-set race after the final
// reread. The runtime fast path is installed only after the CAS
// succeeds, so the fresh active account remains untouched.
item.Outcome = GrokOAuthReconcileOutcomeSkipped
result.Skipped++
break
}
s.notifyAccountSchedulingBlocked(account, time.Time{}, "grok_oauth_reconcile_invalid")
account.Status = StatusError
account.Schedulable = false
cacheInvalidationFailed := s.cacheInvalidator == nil
if s.cacheInvalidator != nil {
if err := s.cacheInvalidator.InvalidateToken(ctx, account); err != nil {
cacheInvalidationFailed = true
}
}
result.Blocked++
if cacheInvalidationFailed {
item.Outcome = GrokOAuthReconcileOutcomePartial
result.Partial++
} else {
item.Outcome = GrokOAuthReconcileOutcomeApplied
}
case GrokOAuthReconcileActionRefresh:
if providerState.isTripped() {
item.Outcome = GrokOAuthReconcileOutcomeSkipped
result.Skipped++
break
}
if providerState.isTripped() {
item.Outcome = GrokOAuthReconcileOutcomeSkipped
result.Skipped++
break
}
refreshErr := s.refreshWithRetryWithRateGate(ctx, account, registration.refresher, registration.executor, refreshWindow, providerState)
providerState.recordResult(refreshErr)
var permanentErr *accountPermanentRefreshError
switch {
case refreshErr == nil:
item.Outcome = GrokOAuthReconcileOutcomeApplied
result.Refreshed++
case errors.Is(refreshErr, errRefreshSkipped):
item.Outcome = GrokOAuthReconcileOutcomeSkipped
result.Skipped++
case errors.As(refreshErr, &permanentErr) && permanentErr.persistentlyBlocked:
item.Reason = GrokOAuthReconcileReasonCredentialRejected
item.Action = GrokOAuthReconcileActionBlock
result.Blocked++
if permanentErr.cacheInvalidationFailed {
item.Outcome = GrokOAuthReconcileOutcomePartial
result.Partial++
} else {
item.Outcome = GrokOAuthReconcileOutcomeApplied
}
default:
item.Outcome = GrokOAuthReconcileOutcomeFailed
result.Failed++
}
default:
return nil, fmt.Errorf("unsupported Grok OAuth reconciliation action")
}
result.Items = append(result.Items, item)
}
return result, nil
}
func (s *TokenRefreshService) grokOAuthReconcileMaxPageSize() int {
return maxGrokOAuthReconcilePageSize
}
func (s *TokenRefreshService) grokRegistration() (tokenRefreshRegistration, bool) {
for _, registration := range s.registrations {
if registration.platform == PlatformGrok && registration.refresher != nil {
return registration, true
}
}
return tokenRefreshRegistration{}, false
}
func classifyGrokOAuthReconcileAccount(account *Account, refreshWindow time.Duration) (reason, action string, actionable bool) {
if account == nil || !account.IsGrokOAuth() || account.Status != StatusActive {
return "", "", false
}
if strings.TrimSpace(account.GetGrokRefreshToken()) == "" {
return GrokOAuthReconcileReasonMissingRefreshToken, GrokOAuthReconcileActionBlock, true
}
if strings.TrimSpace(account.GetGrokAccessToken()) == "" {
return GrokOAuthReconcileReasonMissingAccessToken, GrokOAuthReconcileActionRefresh, true
}
rawExpiry := strings.TrimSpace(account.GetCredential("expires_at"))
if rawExpiry == "" {
return GrokOAuthReconcileReasonMissingExpiry, GrokOAuthReconcileActionRefresh, true
}
expiresAt := account.GetCredentialAsTime("expires_at")
if expiresAt == nil {
return GrokOAuthReconcileReasonInvalidExpiry, GrokOAuthReconcileActionRefresh, true
}
if time.Until(*expiresAt) <= refreshWindow {
return GrokOAuthReconcileReasonNearExpiry, GrokOAuthReconcileActionRefresh, true
}
return "", "", false
}
Loaded 100 of 243 files, more files were not shown because too many files have changed in this diff. Show more