From a95770bc90a83a21bdd88c7f0f6ac8b2cecd3868 Mon Sep 17 00:00:00 2001 From: Lollipopdamn <2516731482@qq.com> Date: Sat, 28 Nov 2026 15:54:55 +0800 Subject: [PATCH] fix: sync fork v2.4.5 runtime safeguards --- .github/workflows/backend-ci.yml | 3 + LOCAL_FORK.md | 6 + backend/cmd/server/VERSION | 2 +- backend/internal/config/config.go | 28 +- backend/internal/config/redis_pool_test.go | 48 + .../internal/handler/admin/ops_ws_handler.go | 41 +- .../handler/admin/ops_ws_origin_test.go | 52 + .../internal/handler/auth_linuxdo_oauth.go | 6 +- .../handler/auth_linuxdo_oauth_test.go | 3 + .../handler/content_moderation_helper.go | 2 +- backend/internal/handler/gateway_handler.go | 9 +- .../gateway_handler_chat_completions.go | 3 +- .../handler/gateway_handler_responses.go | 3 +- backend/internal/handler/gateway_systemone.go | 1 + .../internal/handler/gemini_v1beta_handler.go | 1 + backend/internal/handler/grok_audio.go | 4 +- .../internal/handler/openai_alpha_search.go | 8 +- .../handler/openai_chat_completions.go | 5 +- .../internal/handler/openai_deepseek_tools.go | 1 + backend/internal/handler/openai_embeddings.go | 5 +- .../handler/openai_gateway_handler.go | 17 +- .../openai_gateway_usage_context_test.go | 26 + backend/internal/handler/openai_images.go | 3 +- .../usage_record_gin_context_reuse_test.go | 263 + backend/internal/pkg/ip/request_host.go | 107 + .../repository/channel_monitor_v2_repo.go | 35 +- .../channel_monitor_v2_repo_test.go | 14 + backend/internal/repository/redis.go | 64 +- .../repository/redis_pool_behavior_test.go | 205 + backend/internal/repository/redis_test.go | 25 +- .../service/openai_gateway_request_body.go | 12 +- .../internal/service/request_string_detach.go | 65 + .../service/request_string_detach_test.go | 127 + .../service/update_source_baselines.go | 4 +- deploy/config.example.yaml | 15 +- docs/release-notes/v2.1.76.md | 17 + .../components/auth/DingTalkOAuthSection.vue | 3 +- .../src/components/auth/EmailOAuthButtons.vue | 3 +- .../components/auth/LinuxDoOAuthSection.vue | 3 +- .../src/components/auth/OidcOAuthSection.vue | 3 +- .../components/auth/WechatOAuthSection.vue | 3 +- .../auth/__tests__/OAuthLoginSections.spec.ts | 11 + .../__tests__/monitorFormat.spec.ts | 4 + .../channel-monitor-v2/monitorFormat.ts | 3 +- frontend/src/utils/__tests__/url.spec.ts | 37 + frontend/src/utils/url.ts | 57 +- .../src/views/auth/DingTalkCallbackView.vue | 9 +- .../auth/DingTalkEmailCompletionView.vue | 9 +- .../src/views/auth/LinuxDoCallbackView.vue | 9 +- frontend/src/views/auth/LoginView.vue | 13 +- frontend/src/views/auth/OAuthCallbackView.vue | 9 +- frontend/src/views/auth/OidcCallbackView.vue | 9 +- .../src/views/auth/WechatCallbackView.vue | 9 +- .../fork-selection-ledger-20261128-v245.json | 11619 ++++++++++++++++ .../notes/upstream-sync-20261128-v245.md | 41 + maintenance/upstream.lock.json | 53 +- 56 files changed, 12986 insertions(+), 151 deletions(-) create mode 100644 backend/internal/config/redis_pool_test.go create mode 100644 backend/internal/handler/admin/ops_ws_origin_test.go create mode 100644 backend/internal/handler/usage_record_gin_context_reuse_test.go create mode 100644 backend/internal/pkg/ip/request_host.go create mode 100644 backend/internal/repository/redis_pool_behavior_test.go create mode 100644 backend/internal/service/request_string_detach.go create mode 100644 backend/internal/service/request_string_detach_test.go create mode 100644 docs/release-notes/v2.1.76.md create mode 100644 frontend/src/utils/__tests__/url.spec.ts create mode 100644 maintenance/notes/fork-selection-ledger-20261128-v245.json create mode 100644 maintenance/notes/upstream-sync-20261128-v245.md diff --git a/.github/workflows/backend-ci.yml b/.github/workflows/backend-ci.yml index bdc1a8d7..469bc9ec 100644 --- a/.github/workflows/backend-ci.yml +++ b/.github/workflows/backend-ci.yml @@ -101,6 +101,9 @@ jobs: - name: Fork v2.3.175 protocol and cache regression working-directory: backend run: go test -race -p 1 -parallel 1 -tags=unit ./internal/service ./internal/repository -run '^Test(FilterThinkingBlocks|SanitizeAnthropicBodyForBetaTokens_ContextManagementCompactBeta|NormalizeOpenAIResponsesLitePayload_NullBodyDoesNotPanic|SanitizeOpenAIResponsesInputItemIDsMatchesLegacy|SanitizeOpenAIResponsesInputItemIDsTruncatedBodiesMatchLegacy|SanitizeOpenAIResponsesInputItemIDsLeadingWhitespaceKeepsOffsets|StripGrokAPIKeyOpenAICompatFieldsMatchesLegacy|ReasoningContent|DeepSeekNativeReasoningReplayTreatsUndecodableCacheValueAsMiss|ChannelMonitorV2RefreshesEarlierDurableCursor|ClientErrorPrivacy.*PublicLink|SilentRefusalDetector)' -count=1 + - name: Fork v2.4.5 request isolation and security regression + working-directory: backend + run: go test -race -p 1 -parallel 1 -tags=unit ./internal/config ./internal/service ./internal/repository ./internal/handler ./internal/handler/admin ./internal/pkg/ip -run '^Test(QueuedUsage|UsageRecords|DetachRequestStrings|OpenAIRequestViewStringsDoNotPinTheBody|BuildRedis|ProvideReasoningRedis|RedisPool|LoadRedisPool|ChannelMonitorV2HistogramOverflow|OpsWS|SanitizeFrontendRedirectPath)' -count=1 - name: Session revocation, atomic codes and gateway admission regression working-directory: backend run: go test -race -p 1 -parallel 1 -tags=unit ./internal/pkg/httputil ./internal/repository ./internal/service ./internal/handler ./internal/server/middleware ./internal/server/routes -run 'Test(AuthUserTokenCutoff|EmailCode|JWTRevocation|AuthHandlerRevokeAllSessions|OAuthBindCookieRejects|GroupModelAllowlist|GatewayRoutesGroupModelAllowlist|NormalizeLenientJSONRequestBody|DeepSeek|NativeAnthropicPassthrough|PatchGrokResponsesBody|NormalizeGrokChatReasoningEffort|ReleaseAccountSession|CleanupStaleProcessSlots)' -count=1 diff --git a/LOCAL_FORK.md b/LOCAL_FORK.md index 883140c9..2e5c79e2 100644 --- a/LOCAL_FORK.md +++ b/LOCAL_FORK.md @@ -30,6 +30,12 @@ 原生支付模块已退役,充值使用链动小铺及兑换码。服务器部署继续使用备份和校验后的受控发布流程。 +## 二改 v2.4.5 选择性同步(2026-11-28) + +固定正式 v2.4.5 来源,盘点 v2.3.175 后 47 个提交、1,152 个变化路径,适配 Redis 连接池回收与等待超时、异步计费请求上下文/字符串脱离、监控直方图溢出显示,以及 Ops WebSocket Origin 和登录/OAuth 站内跳转校验。原版正式版本仍为 v0.2.25,未发布 main 仅记录观察值。 + +保留生图分组、Images API、批量生图、Key、价格/倍率、原生厂商路由和个人主题;无限画布继续移除。新账本、配额预占、计费 schema、完整 MFA/Key seal、支付及全请求体索引等成组模块延期。用户随后授权提交 GitHub 并更新部署,个人发布版本推进至 v2.1.76;按 PR/CI、自有 Release/GHCR、备份实际恢复及受控切换流程发布,最终生产验收另存证据。具体采用与延期项见[同步记录](maintenance/notes/upstream-sync-20261128-v245.md)及[完整取舍清单](maintenance/notes/fork-selection-ledger-20261128-v245.json)。 + ## 二改 v2.3.155 选择性同步(2026-11-24) 审阅正式 v2.3.153 至 v2.3.155 的 43 个提交、336 个变化路径,适配网关 Base URL 路径兼容及最终防护、Passkey 会话/错误反馈和 WebSocket/otel 依赖修复。智能路由富分组下拉已有覆盖;保留本地主题、原生厂商路由、计费与 TOTP 登录规则。Nuxt UI 改版、全套多因子/Key seal 验证、5xx 告警迁移及退役支付不整组导入。原版检查点仍为 v0.2.24。用户随后授权提交 GitHub 并部署,个人发布版本推进至 v2.1.72,沿用 PR/CI、自有 Release/GHCR、备份实际恢复及受控切换流程;最终发布与线上验收另存证据。来源、逐项取舍与验证边界见[同步记录](maintenance/notes/upstream-sync-20261124-v23155.md)。 diff --git a/backend/cmd/server/VERSION b/backend/cmd/server/VERSION index d7c51dbf..8b0d8fd4 100644 --- a/backend/cmd/server/VERSION +++ b/backend/cmd/server/VERSION @@ -1 +1 @@ -2.1.75 +2.1.76 diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go index 23683cd7..2011feab 100644 --- a/backend/internal/config/config.go +++ b/backend/internal/config/config.go @@ -1700,7 +1700,12 @@ type RedisConfig struct { // PoolSize: 连接池大小,控制最大并发连接数 PoolSize int `mapstructure:"pool_size"` // MinIdleConns: 最小空闲连接数,保持热连接减少冷启动延迟 - MinIdleConns int `mapstructure:"min_idle_conns"` + MinIdleConns int `mapstructure:"min_idle_conns"` + MaxIdleConns int `mapstructure:"max_idle_conns"` + PoolFIFO bool `mapstructure:"pool_fifo"` + PoolTimeoutMS int `mapstructure:"pool_timeout_ms"` + ConnMaxIdleTimeSeconds int `mapstructure:"conn_max_idle_time_seconds"` + ConnMaxLifetimeSeconds int `mapstructure:"conn_max_lifetime_seconds"` // EnableTLS: 是否启用 TLS/SSL 连接 EnableTLS bool `mapstructure:"enable_tls"` } @@ -2355,8 +2360,13 @@ func setDefaults() { viper.SetDefault("redis.dial_timeout_seconds", 5) viper.SetDefault("redis.read_timeout_seconds", 3) viper.SetDefault("redis.write_timeout_seconds", 3) - viper.SetDefault("redis.pool_size", 1024) - viper.SetDefault("redis.min_idle_conns", 128) + viper.SetDefault("redis.pool_size", 512) + viper.SetDefault("redis.min_idle_conns", 8) + viper.SetDefault("redis.max_idle_conns", 64) + viper.SetDefault("redis.pool_fifo", true) + viper.SetDefault("redis.pool_timeout_ms", 1000) + viper.SetDefault("redis.conn_max_idle_time_seconds", 300) + viper.SetDefault("redis.conn_max_lifetime_seconds", 1800) viper.SetDefault("redis.enable_tls", false) // Batch Image queue @@ -3310,6 +3320,18 @@ func (c *Config) Validate() error { if c.Redis.MinIdleConns > c.Redis.PoolSize { return fmt.Errorf("redis.min_idle_conns cannot exceed redis.pool_size") } + if c.Redis.MaxIdleConns < 0 { + return fmt.Errorf("redis.max_idle_conns must be non-negative") + } + if c.Redis.PoolTimeoutMS <= 0 { + return fmt.Errorf("redis.pool_timeout_ms must be positive") + } + if c.Redis.ConnMaxIdleTimeSeconds < 0 { + return fmt.Errorf("redis.conn_max_idle_time_seconds must be non-negative") + } + if c.Redis.ConnMaxLifetimeSeconds < 0 { + return fmt.Errorf("redis.conn_max_lifetime_seconds must be non-negative") + } if c.BatchImage.QueueEnabled { if strings.TrimSpace(c.BatchImage.QueueReadyKey) == "" { return fmt.Errorf("batch_image.queue_ready_key must not be empty") diff --git a/backend/internal/config/redis_pool_test.go b/backend/internal/config/redis_pool_test.go new file mode 100644 index 00000000..fd8d7546 --- /dev/null +++ b/backend/internal/config/redis_pool_test.go @@ -0,0 +1,48 @@ +package config + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestLoadRedisPoolDefaultsAndExplicitOverrides(t *testing.T) { + resetViperWithJWTSecret(t) + cfg, err := Load() + require.NoError(t, err) + require.Equal(t, 512, cfg.Redis.PoolSize) + require.Equal(t, 8, cfg.Redis.MinIdleConns) + require.Equal(t, 64, cfg.Redis.MaxIdleConns) + require.True(t, cfg.Redis.PoolFIFO) + require.Equal(t, 1000, cfg.Redis.PoolTimeoutMS) + require.Equal(t, 300, cfg.Redis.ConnMaxIdleTimeSeconds) + require.Equal(t, 1800, cfg.Redis.ConnMaxLifetimeSeconds) + + t.Setenv("REDIS_POOL_SIZE", "4096") + t.Setenv("REDIS_MIN_IDLE_CONNS", "256") + t.Setenv("REDIS_POOL_FIFO", "false") + t.Setenv("REDIS_MAX_IDLE_CONNS", "0") + t.Setenv("REDIS_POOL_TIMEOUT_MS", "250") + t.Setenv("REDIS_CONN_MAX_IDLE_TIME_SECONDS", "0") + t.Setenv("REDIS_CONN_MAX_LIFETIME_SECONDS", "0") + cfg, err = Load() + require.NoError(t, err) + require.Equal(t, 4096, cfg.Redis.PoolSize) + require.Equal(t, 256, cfg.Redis.MinIdleConns) + require.Zero(t, cfg.Redis.MaxIdleConns) + require.False(t, cfg.Redis.PoolFIFO) + require.Equal(t, 250, cfg.Redis.PoolTimeoutMS) + require.Zero(t, cfg.Redis.ConnMaxIdleTimeSeconds) + require.Zero(t, cfg.Redis.ConnMaxLifetimeSeconds) +} + +func TestLoadRedisPoolRejectsInvalidSettings(t *testing.T) { + for _, key := range []string{"REDIS_MAX_IDLE_CONNS", "REDIS_POOL_TIMEOUT_MS", "REDIS_CONN_MAX_IDLE_TIME_SECONDS", "REDIS_CONN_MAX_LIFETIME_SECONDS"} { + t.Run(key, func(t *testing.T) { + resetViperWithJWTSecret(t) + t.Setenv(key, "-1") + _, err := Load() + require.Error(t, err) + }) + } +} diff --git a/backend/internal/handler/admin/ops_ws_handler.go b/backend/internal/handler/admin/ops_ws_handler.go index e4c42cc9..57de5cf6 100644 --- a/backend/internal/handler/admin/ops_ws_handler.go +++ b/backend/internal/handler/admin/ops_ws_handler.go @@ -15,6 +15,7 @@ import ( "sync/atomic" "time" + "github.com/Wei-Shaw/sub2api/internal/pkg/ip" "github.com/Wei-Shaw/sub2api/internal/pkg/logger" servermiddleware "github.com/Wei-Shaw/sub2api/internal/server/middleware" "github.com/Wei-Shaw/sub2api/internal/service" @@ -552,27 +553,22 @@ func isAllowedOpsWSOrigin(r *http.Request) bool { } } parsed, err := url.Parse(origin) - if err != nil || parsed.Hostname() == "" { + if err != nil || !parsed.IsAbs() || parsed.Opaque != "" || parsed.User != nil || + parsed.Path != "" || strings.ContainsAny(origin, "?#") || + (parsed.Scheme != "http" && parsed.Scheme != "https") { return false } - originHost := strings.ToLower(parsed.Hostname()) - - trustProxyHeaders := shouldTrustOpsWSProxyHeaders(r) - reqHost := hostWithoutPort(r.Host) - if trustProxyHeaders { - xfHost := strings.TrimSpace(r.Header.Get("X-Forwarded-Host")) - if xfHost != "" { - xfHost = strings.TrimSpace(strings.Split(xfHost, ",")[0]) - if xfHost != "" { - reqHost = hostWithoutPort(xfHost) - } - } + validOriginHost, ok := ip.ValidateRequestHost(parsed.Host) + if !ok { + return false } - reqHost = strings.ToLower(reqHost) - if reqHost == "" { + // Proxies may pass client-controlled X-Forwarded-Host through unchanged. + // Compare only the validated request Host, retaining the existing port policy. + validReqHost, ok := ip.ValidateRequestHost(r.Host) + if !ok { return false } - return originHost == reqHost + return strings.EqualFold(hostWithoutPort(validOriginHost), hostWithoutPort(validReqHost)) } func shouldTrustOpsWSProxyHeaders(r *http.Request) bool { @@ -639,6 +635,9 @@ func isAddrInTrustedProxies(addr netip.Addr, trusted []netip.Prefix) bool { return false } for _, p := range trusted { + if p.Bits() == 0 { + continue + } if p.Contains(addr) { return true } @@ -736,10 +735,18 @@ func parseTrustedProxyList(raw string) (prefixes []netip.Prefix, invalid []strin } } - if err != nil || !p.IsValid() { + if err != nil || !p.IsValid() || p.Bits() == 0 { invalid = append(invalid, item) continue } + if p.Addr().Is4In6() { + bits := p.Bits() - 96 + if bits <= 0 { + invalid = append(invalid, item) + continue + } + p = netip.PrefixFrom(p.Addr().Unmap(), bits) + } prefixes = append(prefixes, p.Masked()) } diff --git a/backend/internal/handler/admin/ops_ws_origin_test.go b/backend/internal/handler/admin/ops_ws_origin_test.go new file mode 100644 index 00000000..32998e57 --- /dev/null +++ b/backend/internal/handler/admin/ops_ws_origin_test.go @@ -0,0 +1,52 @@ +package admin + +import ( + "net/http/httptest" + "net/netip" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestOpsWSOriginUsesValidatedRequestHost(t *testing.T) { + previous := opsWSProxyConfig + opsWSProxyConfig = OpsWSProxyConfig{TrustProxy: true, TrustedProxies: defaultTrustedProxies(), OriginPolicy: OriginPolicyStrict} + t.Cleanup(func() { opsWSProxyConfig = previous }) + for _, tc := range []struct { + name, host, origin, forwarded string + want bool + }{ + {"same host", "example.com", "https://example.com", "", true}, + {"case and port policy", "EXAMPLE.com:8080", "https://example.com", "", true}, + {"IPv6", "[::1]:8080", "http://[::1]:8080", "", true}, + {"spoofed forwarded host", "example.com", "https://evil.example", "evil.example", false}, + {"forwarded host cannot override valid host", "example.com", "https://example.com", "evil.example", true}, + {"userinfo", "example.com", "https://evil@example.com", "", false}, + {"scheme", "example.com", "ftp://example.com", "", false}, + {"path", "example.com", "https://example.com/", "", false}, + {"query", "example.com", "https://example.com?", "", false}, + {"fragment", "example.com", "https://example.com#", "", false}, + {"invalid origin host", "example.com", "https://example.com:0", "", false}, + {"invalid request host", "example.com,evil.example", "https://example.com", "", false}, + {"invalid IPv6", "[not-an-ip]", "http://[not-an-ip]", "", false}, + {"strict missing", "example.com", "", "", false}, + } { + t.Run(tc.name, func(t *testing.T) { + r := httptest.NewRequest("GET", "http://example.com/ops/ws", nil) + r.Host, r.RemoteAddr = tc.host, "127.0.0.1:12345" + r.Header.Set("Origin", tc.origin) + r.Header.Set("X-Forwarded-Host", tc.forwarded) + require.Equal(t, tc.want, isAllowedOpsWSOrigin(r)) + }) + } + opsWSProxyConfig.OriginPolicy = OriginPolicyPermissive + require.True(t, isAllowedOpsWSOrigin(httptest.NewRequest("GET", "http://example.com", nil))) +} + +func TestOpsWSTrustRejectsWildcardAndNormalizesMappedIPv4(t *testing.T) { + prefixes, invalid := parseTrustedProxyList("0.0.0.0/0,::/0,::ffff:0.0.0.0/96,::ffff:10.0.0.0/104,127.0.0.1") + require.Len(t, invalid, 3) + require.Equal(t, []netip.Prefix{netip.MustParsePrefix("10.0.0.0/8"), netip.MustParsePrefix("127.0.0.1/32")}, prefixes) + require.True(t, isAddrInTrustedProxies(netip.MustParseAddr("10.1.2.3"), prefixes)) + require.False(t, isAddrInTrustedProxies(netip.MustParseAddr("8.8.8.8"), []netip.Prefix{netip.MustParsePrefix("0.0.0.0/0")})) +} diff --git a/backend/internal/handler/auth_linuxdo_oauth.go b/backend/internal/handler/auth_linuxdo_oauth.go index 54bb0223..40976e4c 100644 --- a/backend/internal/handler/auth_linuxdo_oauth.go +++ b/backend/internal/handler/auth_linuxdo_oauth.go @@ -1039,8 +1039,10 @@ func sanitizeFrontendRedirectPath(path string) string { if strings.Contains(path, "://") { return "" } - if strings.ContainsAny(path, "\r\n") { - return "" + for i := 0; i < len(path); i++ { + if path[i] < 0x20 || path[i] == 0x7f || path[i] == '\\' { + return "" + } } return path } diff --git a/backend/internal/handler/auth_linuxdo_oauth_test.go b/backend/internal/handler/auth_linuxdo_oauth_test.go index 6dcf30a0..26c29a1e 100644 --- a/backend/internal/handler/auth_linuxdo_oauth_test.go +++ b/backend/internal/handler/auth_linuxdo_oauth_test.go @@ -29,6 +29,9 @@ func TestSanitizeFrontendRedirectPath(t *testing.T) { require.Equal(t, "", sanitizeFrontendRedirectPath("//evil.com")) require.Equal(t, "", sanitizeFrontendRedirectPath("https://evil.com")) require.Equal(t, "", sanitizeFrontendRedirectPath("/\nfoo")) + for _, path := range []string{"/\\evil.example", "/\t/evil.example", "/bad\x00path", "/bad\x7fpath"} { + require.Empty(t, sanitizeFrontendRedirectPath(path), "unsafe redirect %q", path) + } long := "/" + strings.Repeat("a", linuxDoOAuthMaxRedirectLen) require.Equal(t, "", sanitizeFrontendRedirectPath(long)) diff --git a/backend/internal/handler/content_moderation_helper.go b/backend/internal/handler/content_moderation_helper.go index c7e7ff9b..35c9db3c 100644 --- a/backend/internal/handler/content_moderation_helper.go +++ b/backend/internal/handler/content_moderation_helper.go @@ -35,7 +35,7 @@ func clientRequestedModel(c *gin.Context, fallback string) string { } func clientRequestedUsageFields(c *gin.Context, mapping service.ChannelMappingResult, fallbackModel, upstreamModel string) service.ChannelUsageFields { - return mapping.ToUsageFields(clientRequestedModel(c, fallbackModel), upstreamModel) + return mapping.ToUsageFields(clientRequestedModel(c, fallbackModel), upstreamModel).Detached() } func runContentModeration(c *gin.Context, reqLog *zap.Logger, svc *service.ContentModerationService, apiKey *service.APIKey, subject middleware2.AuthSubject, protocol string, model string, body []byte) *service.ContentModerationDecision { diff --git a/backend/internal/handler/gateway_handler.go b/backend/internal/handler/gateway_handler.go index ad0b6ea3..697f6d84 100644 --- a/backend/internal/handler/gateway_handler.go +++ b/backend/internal/handler/gateway_handler.go @@ -198,7 +198,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) { } body = parsedReq.Body.Bytes() service.CaptureMessagesValidationFacts(c, body) - reqModel := parsedReq.Model + reqModel := strings.Clone(parsedReq.Model) reqStream := parsedReq.Stream if service.IsChatUnsupportedMediaModel(reqModel) { h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "This model is not supported on the Messages endpoint") @@ -219,7 +219,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) { return } body = parsedReq.Body.Bytes() - reqModel = parsedReq.Model + reqModel = strings.Clone(parsedReq.Model) reqStream = parsedReq.Stream } reqLog = reqLog.With(zap.String("model", reqModel), zap.Bool("stream", reqStream)) @@ -631,6 +631,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) { quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) sessionID := service.ExtractClientSessionID(c) channelUsageFields := clientRequestedUsageFields(c, channelMapping, reqModel, partial.UpstreamModel) + partial.DetachRequestStrings() h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) { if recordErr := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{ Result: partial, @@ -1072,6 +1073,8 @@ func (h *GatewayHandler) Messages(c *gin.Context) { forceCacheBilling := fs.ForceCacheBilling quotaPlatform := service.QuotaPlatform(c.Request.Context(), currentAPIKey) sessionID := service.ExtractClientSessionID(c) + result.DetachRequestStrings() + channelUsageFields := clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel) h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) { if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{ Result: result, @@ -1089,7 +1092,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) { RequestPayloadHash: requestPayloadHash, ForceCacheBilling: forceCacheBilling, APIKeyService: h.apiKeyService, - ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel), + ChannelUsageFields: channelUsageFields, }); err != nil { logger.L().With( zap.String("component", "handler.gateway.messages"), diff --git a/backend/internal/handler/gateway_handler_chat_completions.go b/backend/internal/handler/gateway_handler_chat_completions.go index 68bde791..0aea7da4 100644 --- a/backend/internal/handler/gateway_handler_chat_completions.go +++ b/backend/internal/handler/gateway_handler_chat_completions.go @@ -79,7 +79,7 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { h.chatCompletionsErrorResponse(c, http.StatusBadRequest, "invalid_request_error", "model is required") return } - reqModel := modelResult.String() + reqModel := strings.Clone(modelResult.String()) bindRequestedReasoningEffort(c, body, reqModel) ensureCompositeTargetPlatform(c, apiKey, reqModel) if rejectSystemOneOnlyPlatform(c, apiKey, h.chatCompletionsErrorResponse) { @@ -398,6 +398,7 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) sessionID := service.ExtractClientSessionID(c) channelUsageFields := clientRequestedUsageFields(c, channelMapping, reqModel, partial.UpstreamModel) + partial.DetachRequestStrings() h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) { if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{ Result: partial, diff --git a/backend/internal/handler/gateway_handler_responses.go b/backend/internal/handler/gateway_handler_responses.go index f4cd0e96..09b15b46 100644 --- a/backend/internal/handler/gateway_handler_responses.go +++ b/backend/internal/handler/gateway_handler_responses.go @@ -79,7 +79,7 @@ func (h *GatewayHandler) Responses(c *gin.Context) { h.responsesErrorResponse(c, http.StatusBadRequest, "invalid_request_error", "model is required") return } - reqModel := modelResult.String() + reqModel := strings.Clone(modelResult.String()) bindRequestedReasoningEffort(c, body, reqModel) ensureCompositeTargetPlatform(c, apiKey, reqModel) if rejectSystemOneOnlyPlatform(c, apiKey, h.responsesErrorResponse) { @@ -382,6 +382,7 @@ func (h *GatewayHandler) Responses(c *gin.Context) { quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) sessionID := service.ExtractClientSessionID(c) channelUsageFields := clientRequestedUsageFields(c, channelMapping, reqModel, partial.UpstreamModel) + partial.DetachRequestStrings() h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) { if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{ Result: partial, diff --git a/backend/internal/handler/gateway_systemone.go b/backend/internal/handler/gateway_systemone.go index 7638405a..579d90c0 100644 --- a/backend/internal/handler/gateway_systemone.go +++ b/backend/internal/handler/gateway_systemone.go @@ -287,6 +287,7 @@ func (h *GatewayHandler) recordSystemOneUsage(c *gin.Context, apiKey *service.AP sessionID := service.ExtractClientSessionID(c) requestPayloadHash := service.HashUsageRequestPayload(body) usageFields := clientRequestedUsageFields(c, mapping, model, result.UpstreamModel) + result.DetachRequestStrings() task := func(ctx context.Context) { if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{ diff --git a/backend/internal/handler/gemini_v1beta_handler.go b/backend/internal/handler/gemini_v1beta_handler.go index b1f8bb91..e11fa13b 100644 --- a/backend/internal/handler/gemini_v1beta_handler.go +++ b/backend/internal/handler/gemini_v1beta_handler.go @@ -905,6 +905,7 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) { accountReleaseFunc() } if result != nil { + result.DetachRequestStrings() usageInput := &service.RecordUsageInput{ Result: result, APIKey: apiKey, User: apiKey.User, Account: account, Subscription: subscription, PricingAt: pricingAt, diff --git a/backend/internal/handler/grok_audio.go b/backend/internal/handler/grok_audio.go index 56a269c5..19bc702a 100644 --- a/backend/internal/handler/grok_audio.go +++ b/backend/internal/handler/grok_audio.go @@ -371,6 +371,8 @@ func (h *OpenAIGatewayHandler) recordGrokVoiceUsage( model = endpoint } + result.DetachRequestStrings() + channelUsageFields := clientRequestedUsageFields(c, service.ChannelMappingResult{}, model, result.UpstreamModel) h.submitMandatoryUsageRecordTask(c.Request.Context(), func(ctx context.Context) { if err := h.gatewayService.RecordUsage(ctx, &service.OpenAIRecordUsageInput{ Result: result, @@ -386,7 +388,7 @@ func (h *OpenAIGatewayHandler) recordGrokVoiceUsage( APIKeyService: h.apiKeyService, QuotaPlatform: quotaPlatform, SessionID: sessionID, - ChannelUsageFields: clientRequestedUsageFields(c, service.ChannelMappingResult{}, model, result.UpstreamModel), + ChannelUsageFields: channelUsageFields, }); err != nil { logger.L().With( zap.String("component", "handler.openai_gateway.grok_voice"), diff --git a/backend/internal/handler/openai_alpha_search.go b/backend/internal/handler/openai_alpha_search.go index b051564b..fd2075a9 100644 --- a/backend/internal/handler/openai_alpha_search.go +++ b/backend/internal/handler/openai_alpha_search.go @@ -330,6 +330,10 @@ func (h *OpenAIGatewayHandler) recordAlphaSearchUsage( upstreamEndpoint := GetUpstreamEndpoint(c, account.Platform) quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) + pricingAt := service.OpenAIPricingAtFromContext(c.Request.Context()) + requestedModel = strings.Clone(requestedModel) + channelUsageFields := channelMapping.ToUsageFields(requestedModel, result.UpstreamModel).Detached() + result.DetachRequestStrings() h.submitMandatoryUsageRecordTask(c.Request.Context(), func(ctx context.Context) { if err := h.gatewayService.RecordUsage(ctx, &service.OpenAIRecordUsageInput{ Result: result, @@ -345,8 +349,8 @@ func (h *OpenAIGatewayHandler) recordAlphaSearchUsage( APIKeyService: h.apiKeyService, QuotaPlatform: quotaPlatform, SessionID: sessionID, - ChannelUsageFields: channelMapping.ToUsageFields(requestedModel, result.UpstreamModel), - PricingAt: service.OpenAIPricingAtFromContext(c.Request.Context()), + ChannelUsageFields: channelUsageFields, + PricingAt: pricingAt, }); err != nil { logger.L().With( zap.String("component", "handler.openai_gateway.alpha_search"), diff --git a/backend/internal/handler/openai_chat_completions.go b/backend/internal/handler/openai_chat_completions.go index f1dfab85..d494a0d0 100644 --- a/backend/internal/handler/openai_chat_completions.go +++ b/backend/internal/handler/openai_chat_completions.go @@ -83,7 +83,7 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) { h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "model is required") return } - reqModel := modelResult.String() + reqModel := strings.Clone(modelResult.String()) body = rewriteInboundDeepSeekCallIDs(apiKey, reqModel, body) ensureCompositeTargetPlatform(c, apiKey, reqModel) if rejectSystemOneOnlyPlatform(c, apiKey, h.errorResponse) { @@ -363,6 +363,7 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) { quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) sessionID := service.ExtractClientSessionID(c) cyberBlocked := service.GetOpsCyberPolicy(c) != nil + channelUsageFields := clientRequestedUsageFields(c, channelMapping, reqModel, res.UpstreamModel) h.submitOpenAIUsageRecordTask(c.Request.Context(), res, func(ctx context.Context) { if err := h.gatewayService.RecordUsage(ctx, &service.OpenAIRecordUsageInput{ Result: res, @@ -377,7 +378,7 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) { APIKeyService: h.apiKeyService, QuotaPlatform: quotaPlatform, SessionID: sessionID, - ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, res.UpstreamModel), + ChannelUsageFields: channelUsageFields, PricingAt: pricingAt, CyberBlocked: cyberBlocked, }); err != nil { diff --git a/backend/internal/handler/openai_deepseek_tools.go b/backend/internal/handler/openai_deepseek_tools.go index 47ca5211..43d8f8f0 100644 --- a/backend/internal/handler/openai_deepseek_tools.go +++ b/backend/internal/handler/openai_deepseek_tools.go @@ -296,6 +296,7 @@ func (h *OpenAIGatewayHandler) recordDeepSeekToolsUsage( upstreamEndpoint := result.UpstreamEndpoint quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) + result.DetachRequestStrings() h.submitMandatoryUsageRecordTask(c.Request.Context(), func(ctx context.Context) { if err := h.gatewayService.RecordUsage(ctx, &service.OpenAIRecordUsageInput{ Result: result, diff --git a/backend/internal/handler/openai_embeddings.go b/backend/internal/handler/openai_embeddings.go index a4421c6f..602a28d0 100644 --- a/backend/internal/handler/openai_embeddings.go +++ b/backend/internal/handler/openai_embeddings.go @@ -78,7 +78,7 @@ func (h *OpenAIGatewayHandler) Embeddings(c *gin.Context) { h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "model is required") return } - reqModel := modelResult.String() + reqModel := strings.Clone(modelResult.String()) ensureCompositeTargetPlatform(c, apiKey, reqModel) if !compositeTargetPlatformAllowed(c, apiKey, reqModel, service.PlatformOpenAI) { h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Model is not supported by this OpenAI-compatible endpoint for composite groups") @@ -344,6 +344,7 @@ func (h *OpenAIGatewayHandler) Embeddings(c *gin.Context) { quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) sessionID := service.ExtractClientSessionID(c) + channelUsageFields := clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel) h.submitOpenAIUsageRecordTask(c.Request.Context(), result, func(ctx context.Context) { if err := h.gatewayService.RecordUsage(ctx, &service.OpenAIRecordUsageInput{ Result: result, @@ -358,7 +359,7 @@ func (h *OpenAIGatewayHandler) Embeddings(c *gin.Context) { APIKeyService: h.apiKeyService, QuotaPlatform: quotaPlatform, SessionID: sessionID, - ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel), + ChannelUsageFields: channelUsageFields, PricingAt: pricingAt, }); err != nil { logger.L().With( diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 5bda67d1..7603ee71 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -278,12 +278,16 @@ func wrapUsageRecordTaskContext(parent context.Context, task service.UsageRecord return nil, func() {} } done := func() {} + var detached context.Context if parent != nil { done = service.InflightReservationFromContext(parent).Acquire() + // Copy only billing metadata before queuing; parent also holds the + // gin context and its complete request body. + detached = usageRecordContext(parent, context.Background()) } return func(ctx context.Context) { defer done() - task(usageRecordContext(parent, ctx)) + task(usageRecordContext(detached, ctx)) }, done } @@ -514,7 +518,7 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "model is required") return } - reqModel := modelResult.String() + reqModel := strings.Clone(modelResult.String()) body = rewriteInboundDeepSeekCallIDs(apiKey, reqModel, body) ensureCompositeTargetPlatform(c, apiKey, reqModel) if rejectSystemOneOnlyPlatform(c, apiKey, h.errorResponse) { @@ -956,6 +960,7 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) sessionID := service.ExtractClientSessionID(c) cyberBlocked := service.GetOpsCyberPolicy(c) != nil + channelUsageFields := clientRequestedUsageFields(c, channelMapping, reqModel, res.UpstreamModel) h.submitOpenAIUsageRecordTask(c.Request.Context(), res, func(ctx context.Context) { if err := h.gatewayService.RecordUsage(ctx, &service.OpenAIRecordUsageInput{ Result: res, @@ -971,7 +976,7 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { APIKeyService: h.apiKeyService, QuotaPlatform: quotaPlatform, SessionID: sessionID, - ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, res.UpstreamModel), + ChannelUsageFields: channelUsageFields, PricingAt: pricingAt, CyberBlocked: cyberBlocked, NativeCompactionV2: nativeV2, @@ -1355,7 +1360,7 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { h.anthropicErrorResponse(c, http.StatusBadRequest, "invalid_request_error", "model is required") return } - reqModel := modelResult.String() + reqModel := strings.Clone(modelResult.String()) body = rewriteInboundDeepSeekCallIDs(apiKey, reqModel, body) if service.IsChatUnsupportedMediaModel(reqModel) { h.anthropicErrorResponse(c, http.StatusBadRequest, "invalid_request_error", "This model is not supported on the Messages endpoint") @@ -1643,6 +1648,7 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) sessionID := service.ExtractClientSessionID(c) cyberBlocked := service.GetOpsCyberPolicy(c) != nil + channelUsageFields := clientRequestedUsageFields(c, channelMappingMsg, reqModel, res.UpstreamModel) h.submitOpenAIUsageRecordTask(c.Request.Context(), res, func(ctx context.Context) { if err := h.gatewayService.RecordUsage(ctx, &service.OpenAIRecordUsageInput{ Result: res, @@ -1658,7 +1664,7 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { APIKeyService: h.apiKeyService, QuotaPlatform: quotaPlatform, SessionID: sessionID, - ChannelUsageFields: clientRequestedUsageFields(c, channelMappingMsg, reqModel, res.UpstreamModel), + ChannelUsageFields: channelUsageFields, PricingAt: pricingAt, CyberBlocked: cyberBlocked, }); err != nil { @@ -3453,6 +3459,7 @@ func (h *OpenAIGatewayHandler) submitUsageRecordTask(parent context.Context, tas } func (h *OpenAIGatewayHandler) submitOpenAIUsageRecordTask(parent context.Context, result *service.OpenAIForwardResult, task service.UsageRecordTask) { + result.DetachRequestStrings() // Money-critical bills never drop on pool overflow: media, search surcharge, voice. if result != nil && (result.ImageCount > 0 || result.VideoCount > 0 || result.SearchCount > 0 || result.WebSearchCalls > 0 || result.AudioUsage != nil) { diff --git a/backend/internal/handler/openai_gateway_usage_context_test.go b/backend/internal/handler/openai_gateway_usage_context_test.go index 7091c9c0..9e9fa4e8 100644 --- a/backend/internal/handler/openai_gateway_usage_context_test.go +++ b/backend/internal/handler/openai_gateway_usage_context_test.go @@ -2,12 +2,38 @@ package handler import ( "context" + "runtime" "testing" + "time" + "weak" "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" + "github.com/Wei-Shaw/sub2api/internal/service" "github.com/stretchr/testify/require" ) +func TestQueuedUsageTaskReleasesParentContextBeforeExecution(t *testing.T) { + type bodyKey struct{} + task, bodyRef := func() (service.UsageRecordTask, weak.Pointer[byte]) { + body := make([]byte, 1<<20) + parent := context.WithValue(context.Background(), bodyKey{}, body) + parent = context.WithValue(parent, ctxkey.RequestID, "request-before-reuse") + wrapped, _ := wrapUsageRecordTaskContext(parent, func(ctx context.Context) { + require.Nil(t, ctx.Value(bodyKey{})) + require.Equal(t, "request-before-reuse", ctx.Value(ctxkey.RequestID)) + require.ErrorIs(t, ctx.Err(), context.Canceled) + }) + return wrapped, weak.Make(&body[0]) + }() + require.Eventually(t, func() bool { + runtime.GC() + return bodyRef.Value() == nil + }, 3*time.Second, 5*time.Millisecond, "queued billing task still holds the request body") + worker, cancel := context.WithCancel(context.Background()) + cancel() + task(worker) +} + func TestSubmitUsageRecordTaskCopiesRequestContext(t *testing.T) { parent := context.WithValue(context.Background(), ctxkey.ClientRequestID, "client-request-123") parent = context.WithValue(parent, ctxkey.RequestID, "request-456") diff --git a/backend/internal/handler/openai_images.go b/backend/internal/handler/openai_images.go index 403470c9..5f7816df 100644 --- a/backend/internal/handler/openai_images.go +++ b/backend/internal/handler/openai_images.go @@ -83,7 +83,7 @@ func (h *OpenAIGatewayHandler) Images(c *gin.Context) { } requestModel := parsed.Model ensureCompositeTargetPlatform(c, apiKey, requestModel) - clientRequestModel := clientRequestedModel(c, requestModel) + clientRequestModel := strings.Clone(clientRequestedModel(c, requestModel)) routingModel := requestModel if resolvedModel, ok := service.ResolvedUpstreamModelFromContext(c.Request.Context()); ok { routingModel = resolvedModel @@ -449,6 +449,7 @@ func (h *OpenAIGatewayHandler) Images(c *gin.Context) { upstreamModel = result.UpstreamModel } sessionID := service.ExtractClientSessionID(c) + result.DetachRequestStrings() usageInput := &service.OpenAIRecordUsageInput{ Result: result, APIKey: apiKey, diff --git a/backend/internal/handler/usage_record_gin_context_reuse_test.go b/backend/internal/handler/usage_record_gin_context_reuse_test.go new file mode 100644 index 00000000..713f286a --- /dev/null +++ b/backend/internal/handler/usage_record_gin_context_reuse_test.go @@ -0,0 +1,263 @@ +//go:build unit + +package handler + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" + pkghttputil "github.com/Wei-Shaw/sub2api/internal/pkg/httputil" + 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" +) + +// A usage task runs on a worker after the handler has returned, and gin hands the finished request's *gin.Context to +// the next request. A task that reads the Context there (usage closures used to call +// clientRequestedUsageFields(c, ...) inside the worker) records the NEXT request's public model name as this request's +// RequestedModel / ModelMappingChain, and, for a channel billed by the requested model, as its billing model. +// +// Every flow below runs through the real handler and service code with the usage worker blocked. For the "recycled" +// variant the Context is then returned to the pool by hand (Request replaced, Keys reset: what gin does for the next +// request) before the worker is released. The usage-log and billing repositories must receive exactly what the request +// itself carried, with or without the reuse. + +const usageFlowPublicModel = "my-public-alias" +const usageFlowOtherRequestModel = "OTHER-REQUEST-MODEL" + +type usageRecordWant struct { + requestedModel string + upstreamModel string + mappingChain string + reasoningEffort string + serviceTier string + inboundEndpoint string + upstreamEndpoint string +} + +type usageRecordDump struct { + log map[string]any + cmd map[string]any +} + +type usageRecordFlow struct { + name string + want usageRecordWant + // run sends one request through the handler; recycled returns the gin.Context to its pool before the usage worker + // is released. + run func(t *testing.T, recycled bool) usageRecordDump +} + +// usageRecordMap turns a usage log / billing command into a comparable map without the fields that differ between any +// two runs (ids, timestamps, durations, shared objects, generated request ids). +func usageRecordMap(t *testing.T, v any) map[string]any { + t.Helper() + raw, err := json.Marshal(v) + require.NoError(t, err) + out := map[string]any{} + require.NoError(t, json.Unmarshal(raw, &out)) + for _, k := range []string{"ID", "CreatedAt", "DurationMs", "FirstTokenMs", "User", "APIKey", "Account", "Group", "Subscription", "RequestedAt", "OccurredAt"} { + delete(out, k) + } + if id, _ := out["RequestID"].(string); strings.HasPrefix(id, "generated:") { + delete(out, "RequestID") + } + return out +} + +func usageRecordString(m map[string]any, key string) string { + s, _ := m[key].(string) + return s +} + +// newUsageFlowRequest builds the request the way the gateway middleware hands it to a handler: JSON body already read +// into a PrereadBody. +func newUsageFlowRequest(body []byte, path string) *http.Request { + req := httptest.NewRequest(http.MethodPost, path, bytes.NewReader(nil)) + req.Body = pkghttputil.NewPrereadBody(body) + req.ContentLength = int64(len(body)) + req.Header.Set("Content-Type", "application/json") + return req +} + +// recycleGinContext does to the finished request's Context what gin does when it serves the next request with it. +func recycleGinContext(c *gin.Context) { + next := httptest.NewRequest(http.MethodPost, "/v1/other", nil). + WithContext(context.WithValue(context.Background(), ctxkey.RequestedPublicModel, usageFlowOtherRequestModel)) + c.Request = next + c.Keys = nil +} + +func newBlockedUsagePool(t *testing.T) (pool *service.UsageRecordWorkerPool, release func()) { + t.Helper() + pool = service.NewUsageRecordWorkerPoolWithOptions(service.UsageRecordWorkerPoolOptions{ + WorkerCount: 1, QueueSize: 64, TaskTimeout: 5 * time.Second, OverflowPolicy: config.UsageRecordOverflowPolicySync, + }) + block, started := make(chan struct{}), make(chan struct{}) + pool.Submit(func(context.Context) { close(started); <-block }) + <-started + release = sync.OnceFunc(func() { close(block) }) + t.Cleanup(func() { release(); pool.Stop() }) + return pool, release +} + +func claudeUsageRecordFlow(name string, passthrough bool, publicModel, extraBody string, want usageRecordWant) usageRecordFlow { + return usageRecordFlow{name: name, want: want, run: func(t *testing.T, recycled bool) usageRecordDump { + const model = "claude-3-7-sonnet-20250219" + group := &service.Group{ID: 9700, Hydrated: true, Platform: service.PlatformAnthropic, Status: service.StatusActive, RateMultiplier: 1} + account := &service.Account{ + ID: 9701, Name: "usage-record", Platform: service.PlatformAnthropic, + Type: service.AccountTypeAPIKey, Status: service.StatusActive, Schedulable: true, + Concurrency: 1, GroupIDs: []int64{group.ID}, + AccountGroups: []service.AccountGroup{{AccountID: 9701, GroupID: group.ID}}, + Credentials: map[string]any{"api_key": "synthetic-test-key", "base_url": "https://api.anthropic.com"}, + Extra: map[string]any{"anthropic_passthrough": passthrough}, + } + cfg := &config.Config{RunMode: config.RunModeStandard} + cfg.Default.RateMultiplier = 1 + cfg.Gateway.MaxLineSize = 1024 * 1024 + billingCache := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, &config.Config{RunMode: config.RunModeSimple}, nil) + t.Cleanup(billingCache.Stop) + usage := &passthroughFailureHandlerUsage{} + billing := &passthroughFailureHandlerBilling{} + upstream := &passthroughFailureHandlerUpstream{wire: "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_p\",\"type\":\"message\",\"role\":\"assistant\",\"model\":\"" + model + "\",\"content\":[],\"usage\":{\"input_tokens\":11,\"cache_read_input_tokens\":7}}}\n\n" + + "event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"answer\"}}\n\n" + + "event: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"output_tokens\":3}}\n\n" + + "event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n"} + cache := &passthroughFailureHandlerCache{bindings: make(map[string]int64), upstreamCalls: &upstream.calls} + snapshot := service.NewSchedulerSnapshotService(&fakeSchedulerCache{accounts: []*service.Account{account}}, nil, nil, nil, nil) + gateway := service.NewGatewayService( + nil, &fakeGroupRepo{group: group}, usage, billing, nil, nil, nil, cache, cfg, + snapshot, nil, service.NewBillingService(cfg, nil), nil, billingCache, nil, + upstream, &service.DeferredService{}, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, + ) + pool, release := newBlockedUsagePool(t) + h := &GatewayHandler{ + gatewayService: gateway, billingCacheService: billingCache, cfg: cfg, + concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(&fakeConcurrencyCache{}), SSEPingFormatClaude, 0), + maxAccountSwitches: 2, + usageRecordWorkerPool: pool, + } + key := &service.APIKey{ + ID: 9702, UserID: 9703, GroupID: &group.ID, Group: group, Status: service.StatusActive, + User: &service.User{ID: 9703, Status: service.StatusActive, Balance: 100, Concurrency: 10}, + } + + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + body := []byte(`{"model":"` + model + `","stream":true,"max_tokens":64,` + extraBody + `"metadata":{"user_id":"user_` + strings.Repeat("a", 64) + `_account__session_123e4567-e89b-12d3-a456-426614174000"},"messages":[{"role":"user","content":"hello"}]}`) + ctx := context.WithValue(context.Background(), ctxkey.Group, group) + if publicModel != "" { + ctx = context.WithValue(ctx, ctxkey.RequestedPublicModel, publicModel) + } + c.Request = newUsageFlowRequest(body, EndpointMessages).WithContext(ctx) + c.Request = c.Request.WithContext(service.WithOpsGinContext(c.Request.Context(), c)) + c.Set(string(middleware.ContextKeyAPIKey), key) + c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: key.UserID, Concurrency: 10}) + h.Messages(c) + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + require.Contains(t, rec.Body.String(), "answer") + + if recycled { + recycleGinContext(c) + } + release() + require.Eventually(t, func() bool { + usage.mu.Lock() + defer usage.mu.Unlock() + billing.mu.Lock() + defer billing.mu.Unlock() + return len(usage.logs) >= 1 && len(billing.commands) >= 1 + }, 8*time.Second, 10*time.Millisecond, "the usage task did not run after the worker was released") + usage.mu.Lock() + defer usage.mu.Unlock() + billing.mu.Lock() + defer billing.mu.Unlock() + require.Len(t, usage.logs, 1) + require.Len(t, billing.commands, 1) + return usageRecordDump{log: usageRecordMap(t, usage.logs[0]), cmd: usageRecordMap(t, billing.commands[0])} + }} +} + +func claudeUsageWant(requested, chain, effort string) usageRecordWant { + const model = "claude-3-7-sonnet-20250219" + return usageRecordWant{ + requestedModel: requested, upstreamModel: model, mappingChain: chain, reasoningEffort: effort, + inboundEndpoint: "/v1/messages", upstreamEndpoint: "/v1/messages", + } +} + +func claudeUsageRecordFlows() []usageRecordFlow { + const chain = usageFlowPublicModel + "→claude-3-7-sonnet-20250219" + publicWant := claudeUsageWant(usageFlowPublicModel, chain, "") + return []usageRecordFlow{ + claudeUsageRecordFlow("claude_native_plain", false, "", "", claudeUsageWant("claude-3-7-sonnet-20250219", "", "")), + claudeUsageRecordFlow("claude_native_public", false, usageFlowPublicModel, "", publicWant), + claudeUsageRecordFlow("claude_passthrough_public", true, usageFlowPublicModel, "", publicWant), + claudeUsageRecordFlow("claude_native_thinking_effort", false, usageFlowPublicModel, `"thinking":{"type":"enabled","budget_tokens":1024},"output_config":{"effort":"high"},`, claudeUsageWant(usageFlowPublicModel, chain, "high")), + } +} + +func requireUsageRecords(t *testing.T, got usageRecordDump, want usageRecordWant) { + t.Helper() + for _, rec := range []struct { + kind string + m map[string]any + }{{"usage log", got.log}, {"billing command", got.cmd}} { + require.Equal(t, want.upstreamModel, usageRecordString(rec.m, "Model"), rec.kind+" Model") + require.Equal(t, want.reasoningEffort, usageRecordString(rec.m, "ReasoningEffort"), rec.kind+" ReasoningEffort") + require.Equal(t, want.serviceTier, usageRecordString(rec.m, "ServiceTier"), rec.kind+" ServiceTier") + } + require.Equal(t, want.requestedModel, usageRecordString(got.log, "RequestedModel"), "usage log RequestedModel must be the request's own public model") + require.Equal(t, want.upstreamModel, usageRecordString(got.log, "UpstreamModel"), "usage log UpstreamModel") + require.Equal(t, want.mappingChain, usageRecordString(got.log, "ModelMappingChain"), "usage log ModelMappingChain") + require.Equal(t, want.inboundEndpoint, usageRecordString(got.log, "InboundEndpoint"), "usage log InboundEndpoint") + require.Equal(t, want.upstreamEndpoint, usageRecordString(got.log, "UpstreamEndpoint"), "usage log UpstreamEndpoint") +} + +// The values the usage-log and billing repositories receive for a request whose Context is still intact: this pins +// the fields billing and the usage page read (models, tier, effort, endpoints) for every handler flow. +func TestUsageRecordsCarryTheRequestsOwnValues(t *testing.T) { + gin.SetMode(gin.TestMode) + flows := claudeUsageRecordFlows() + require.Len(t, flows, 4) + for _, flow := range flows { + t.Run(flow.name, func(t *testing.T) { + requireUsageRecords(t, flow.run(t, false), flow.want) + }) + } +} + +// The same flows when the Context has already been given to the next request by the time the worker runs: nothing a +// record carries may change. Before the usage closures stopped reading the Context, RequestedModel and +// ModelMappingChain came out as the next request's model in the affected flows. +func TestUsageRecordsDoNotFollowARecycledGinContext(t *testing.T) { + gin.SetMode(gin.TestMode) + var flows []usageRecordFlow + for _, flow := range claudeUsageRecordFlows() { + if flow.want.requestedModel == usageFlowPublicModel && flow.name != "claude_native_thinking_effort" { + flows = append(flows, flow) + } + } + require.Len(t, flows, 2) + for _, flow := range flows { + t.Run(flow.name, func(t *testing.T) { + intact := flow.run(t, false) + recycled := flow.run(t, true) + requireUsageRecords(t, recycled, flow.want) + // every other field too, not only the ones named above + require.Equal(t, intact.log, recycled.log, "usage log differs once the Context was reused") + require.Equal(t, intact.cmd, recycled.cmd, "billing command differs once the Context was reused") + }) + } +} diff --git a/backend/internal/pkg/ip/request_host.go b/backend/internal/pkg/ip/request_host.go new file mode 100644 index 00000000..96bcbe3e --- /dev/null +++ b/backend/internal/pkg/ip/request_host.go @@ -0,0 +1,107 @@ +package ip + +import ( + "net" + "net/netip" + "strconv" + "strings" +) + +// ValidateRequestHost validates strict host[:port] syntax and rejects +// multi-value commas, userinfo (@), path/query/fragment delimiters, backslashes, +// whitespace, and control characters. +func ValidateRequestHost(raw string) (string, bool) { + hostport := strings.TrimSpace(raw) + if hostport == "" || len(hostport) > 255 { + return "", false + } + for i := 0; i < len(hostport); i++ { + ch := hostport[i] + if ch <= 0x20 || ch == 0x7f { + return "", false + } + switch ch { + case ',', '@', '/', '\\', '?', '#': + return "", false + } + } + + var host, port string + if strings.HasPrefix(hostport, "[") { + if strings.HasSuffix(hostport, "]") { + host = hostport[1 : len(hostport)-1] + } else { + var err error + host, port, err = net.SplitHostPort(hostport) + if err != nil || port == "" { + return "", false + } + } + addr, err := netip.ParseAddr(host) + if err != nil || !addr.Is6() || addr.Zone() != "" { + return "", false + } + } else if strings.Contains(hostport, ":") { + var err error + host, port, err = net.SplitHostPort(hostport) + if err != nil || port == "" { + return "", false + } + } else { + host = hostport + } + + if port != "" { + if !isValidPortString(port) { + return "", false + } + } + + if !isValidHostNameOrIP(host) { + return "", false + } + return hostport, true +} + +func isValidPortString(port string) bool { + if port == "" || len(port) > 5 || port[0] == '0' { + return false + } + for i := 0; i < len(port); i++ { + if port[i] < '0' || port[i] > '9' { + return false + } + } + n, err := strconv.Atoi(port) + return err == nil && n >= 1 && n <= 65535 +} + +func isValidHostNameOrIP(host string) bool { + if host == "" { + return false + } + if addr, err := netip.ParseAddr(host); err == nil && addr.IsValid() && addr.Zone() == "" { + return true + } + if len(host) > 253 { + return false + } + labels := strings.Split(host, ".") + for _, label := range labels { + if len(label) == 0 || len(label) > 63 { + return false + } + if label[0] == '-' || label[len(label)-1] == '-' { + return false + } + for i := 0; i < len(label); i++ { + ch := label[i] + isAlpha := (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') + isDigit := ch >= '0' && ch <= '9' + if !isAlpha && !isDigit && ch != '-' { + return false + } + } + } + return true +} diff --git a/backend/internal/repository/channel_monitor_v2_repo.go b/backend/internal/repository/channel_monitor_v2_repo.go index 7f9dc7e6..3e0fc1d0 100644 --- a/backend/internal/repository/channel_monitor_v2_repo.go +++ b/backend/internal/repository/channel_monitor_v2_repo.go @@ -5,6 +5,7 @@ import ( "database/sql" "encoding/json" "fmt" + "math" "sort" "strings" "time" @@ -1370,18 +1371,46 @@ func (a *metricAccumulator) metric(minutes float64, admin bool) service.ChannelM } return m } + +const ( + channelMonitorV2HistogramInfBound int64 = 2147483647 + channelMonitorV2HistogramMaxFiniteBound int64 = 600000 +) + func latencyMetric(sum, count int64, hist map[int64]int64) service.ChannelMonitorV2Latency { result := service.ChannelMonitorV2Latency{SampleCount: count} if count > 0 { avg := float64(sum) / float64(count) result.AvgMs = &avg } - result.P50Ms = histPercentile(hist, 0.50) - result.P90Ms = histPercentile(hist, 0.90) - result.P95Ms = histPercentile(hist, 0.95) + result.P50Ms = resolveHistogramPercentile(hist, 0.50, result.AvgMs) + result.P90Ms = resolveHistogramPercentile(hist, 0.90, result.AvgMs) + result.P95Ms = resolveHistogramPercentile(hist, 0.95, result.AvgMs) return result } + +func resolveHistogramPercentile(hist map[int64]int64, p float64, avgMs *float64) *int64 { + raw := rawHistPercentile(hist, p) + if raw == nil || *raw < channelMonitorV2HistogramInfBound { + return raw + } + // The +Inf bucket is not a measured latency. Approximate it with the + // aggregate average, bounded below by the last finite bucket (600s). + fallback := channelMonitorV2HistogramMaxFiniteBound + if avgMs != nil && *avgMs > float64(fallback) && *avgMs < float64(channelMonitorV2HistogramInfBound) { + rounded := int64(math.Round(*avgMs)) + if rounded < channelMonitorV2HistogramInfBound { + fallback = rounded + } + } + return &fallback +} + func histPercentile(hist map[int64]int64, p float64) *int64 { + return resolveHistogramPercentile(hist, p, nil) +} + +func rawHistPercentile(hist map[int64]int64, p float64) *int64 { var total int64 keys := make([]int64, 0, len(hist)) for bound, count := range hist { diff --git a/backend/internal/repository/channel_monitor_v2_repo_test.go b/backend/internal/repository/channel_monitor_v2_repo_test.go index 5161180e..99d6f57a 100644 --- a/backend/internal/repository/channel_monitor_v2_repo_test.go +++ b/backend/internal/repository/channel_monitor_v2_repo_test.go @@ -73,6 +73,20 @@ func TestChannelMonitorV2HistogramPercentilesAreMergedFromCounts(t *testing.T) { require.Equal(t, int64(1000), *lat.P95Ms) } +func TestChannelMonitorV2HistogramOverflowNeverLeaksInt32MaxSentinel(t *testing.T) { + allOverflow := map[int64]int64{channelMonitorV2HistogramInfBound: 9} + lat := latencyMetric(9*1193692, 9, allOverflow) + require.Equal(t, int64(1193692), *lat.P50Ms) + require.Equal(t, int64(1193692), *lat.P90Ms) + require.Equal(t, int64(1193692), *lat.P95Ms) + + tail := latencyMetric(90*2000+10*900000, 100, map[int64]int64{3000: 90, channelMonitorV2HistogramInfBound: 10}) + require.Equal(t, int64(3000), *tail.P50Ms) + require.Equal(t, int64(3000), *tail.P90Ms) + require.Equal(t, channelMonitorV2HistogramMaxFiniteBound, *tail.P95Ms) + require.Equal(t, channelMonitorV2HistogramMaxFiniteBound, *histPercentile(allOverflow, .5)) +} + func TestChannelMonitorV2MetricIncludesSuccessRate(t *testing.T) { acc := newMetricAccumulator() acc.success, acc.errors = 80, 20 diff --git a/backend/internal/repository/redis.go b/backend/internal/repository/redis.go index 3bd14ca9..9e75fcc5 100644 --- a/backend/internal/repository/redis.go +++ b/backend/internal/repository/redis.go @@ -11,15 +11,8 @@ import ( // InitRedis 初始化 Redis 客户端 // -// 性能优化说明: -// 原实现使用 go-redis 默认配置,未设置连接池和超时参数: -// 1. 默认连接池大小可能不足以支撑高并发 -// 2. 无超时控制可能导致慢操作阻塞 -// -// 新实现支持可配置的连接池和超时参数: -// 1. PoolSize: 控制最大并发连接数(默认 128) -// 2. MinIdleConns: 保持最小空闲连接,减少冷启动延迟(默认 10) -// 3. DialTimeout/ReadTimeout/WriteTimeout: 精确控制各阶段超时 +// FIFO 轮转检查连接寿命;空闲连接超过上限时关闭,以便突发后收缩。 +// 池耗尽的等待上限独立于读写超时,默认值见 config.go。 func InitRedis(cfg *config.Config) *redis.Client { client := redis.NewClient(buildRedisOptions(cfg)) if cfg.Server.EnableServerTiming { @@ -40,6 +33,9 @@ func ProvideReasoningRedis(cfg *config.Config) *ReasoningRedisClient { opts.ContextTimeoutEnabled = true // Replay is optional; do not prewarm a second set of idle connections. opts.MinIdleConns = 0 + reasoningConfig := cfg.Redis + reasoningConfig.MinIdleConns = 0 + opts.MaxIdleConns = redisMaxIdleConns(reasoningConfig) client := redis.NewClient(opts) if cfg.Server.EnableServerTiming { client.AddHook(serverTimingRedisHook{}) @@ -51,15 +47,23 @@ func ProvideReasoningRedis(cfg *config.Config) *ReasoningRedisClient { // 从配置文件读取连接池和超时参数,支持生产环境调优 func buildRedisOptions(cfg *config.Config) *redis.Options { opts := &redis.Options{ - Addr: cfg.Redis.Address(), - Username: cfg.Redis.Username, - Password: cfg.Redis.Password, - DB: cfg.Redis.DB, - DialTimeout: time.Duration(cfg.Redis.DialTimeoutSeconds) * time.Second, // 建连超时 - ReadTimeout: time.Duration(cfg.Redis.ReadTimeoutSeconds) * time.Second, // 读取超时 - WriteTimeout: time.Duration(cfg.Redis.WriteTimeoutSeconds) * time.Second, // 写入超时 - PoolSize: cfg.Redis.PoolSize, // 连接池大小 - MinIdleConns: cfg.Redis.MinIdleConns, // 最小空闲连接 + Addr: cfg.Redis.Address(), + Username: cfg.Redis.Username, + Password: cfg.Redis.Password, + DB: cfg.Redis.DB, + DialTimeout: time.Duration(cfg.Redis.DialTimeoutSeconds) * time.Second, // 建连超时 + ReadTimeout: time.Duration(cfg.Redis.ReadTimeoutSeconds) * time.Second, // 读取超时 + WriteTimeout: time.Duration(cfg.Redis.WriteTimeoutSeconds) * time.Second, // 写入超时 + PoolSize: cfg.Redis.PoolSize, // 连接池大小 + MinIdleConns: cfg.Redis.MinIdleConns, // 最小空闲连接 + MaxIdleConns: redisMaxIdleConns(cfg.Redis), + PoolFIFO: cfg.Redis.PoolFIFO, + PoolTimeout: time.Duration(cfg.Redis.PoolTimeoutMS) * time.Millisecond, + ConnMaxIdleTime: redisConnMaxIdleTime(cfg.Redis.ConnMaxIdleTimeSeconds), + } + if lifetime := time.Duration(cfg.Redis.ConnMaxLifetimeSeconds) * time.Second; lifetime > 0 { + opts.ConnMaxLifetime = lifetime + opts.ConnMaxLifetimeJitter = lifetime / 10 } if cfg.Redis.EnableTLS { @@ -71,3 +75,27 @@ func buildRedisOptions(cfg *config.Config) *redis.Options { return opts } + +// Normalize the new idle cap against existing explicit pool settings so older +// configurations do not churn their prewarmed connections or fail validation. +func redisMaxIdleConns(r config.RedisConfig) int { + maxIdle := r.MaxIdleConns + if maxIdle <= 0 { + return 0 + } + if maxIdle < r.MinIdleConns { + maxIdle = r.MinIdleConns + } + if r.PoolSize > 0 && maxIdle > r.PoolSize { + maxIdle = r.PoolSize + } + return maxIdle +} + +func redisConnMaxIdleTime(seconds int) time.Duration { + if seconds <= 0 { + // go-redis replaces zero with 30 minutes; negative disables idle expiry. + return -1 + } + return time.Duration(seconds) * time.Second +} diff --git a/backend/internal/repository/redis_pool_behavior_test.go b/backend/internal/repository/redis_pool_behavior_test.go new file mode 100644 index 00000000..b0a64cd1 --- /dev/null +++ b/backend/internal/repository/redis_pool_behavior_test.go @@ -0,0 +1,205 @@ +package repository + +import ( + "context" + "strconv" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + + "github.com/alicebob/miniredis/v2" + "github.com/redis/go-redis/v9" + "github.com/stretchr/testify/require" +) + +// 这组测试用真实的 go-redis 客户端(选项由 buildRedisOptions 生成)对着 miniredis, +// 验证连接池“只涨不缩”的机理和修法,而不是只检查选项字段: +// - go-redis v9 没有后台回收线程,空闲连接只在被取到时才惰性检查 ConnMaxIdleTime; +// - 默认 LIFO 只会反复取栈顶,栈底的连接永远轮不到;FIFO 才会逐个检查; +// - MaxIdleConns 在归还时就关掉超限的连接,不依赖后续流量; +// - PoolTimeout 决定池耗尽时多久放弃。 + +func redisPoolTestConfig(t *testing.T, srv *miniredis.Miniredis) config.RedisConfig { + t.Helper() + port, err := strconv.Atoi(srv.Port()) + require.NoError(t, err) + return config.RedisConfig{ + Host: srv.Host(), + Port: port, + DialTimeoutSeconds: 2, + ReadTimeoutSeconds: 3, + WriteTimeoutSeconds: 3, + PoolSize: 64, + PoolFIFO: true, + PoolTimeoutMS: 1000, + ConnMaxIdleTimeSeconds: 300, + } +} + +func newRedisPoolTestClient(t *testing.T, cfg config.RedisConfig) *redis.Client { + t.Helper() + client := redis.NewClient(buildRedisOptions(&config.Config{Redis: cfg})) + t.Cleanup(func() { _ = client.Close() }) + return client +} + +// holdConnections 让 n 个请求同时各占一条连接 hold 这么久(服务端 BLPOP 阻塞), +// 返回时它们都已归还到池里。用 Do 传字符串超时,因为 go-redis 的 BLPop 会把小于 1 秒的超时截成 1 秒。 +func holdConnections(client *redis.Client, n int, hold time.Duration) { + var wg sync.WaitGroup + start := make(chan struct{}) + timeout := strconv.FormatFloat(hold.Seconds(), 'f', 3, 64) + for i := 0; i < n; i++ { + wg.Add(1) + go func() { + defer wg.Done() + <-start + // 超时返回 redis.Nil,是预期结果。 + _ = client.Do(context.Background(), "BLPOP", "redis-pool-hold", timeout).Err() + }() + } + close(start) + wg.Wait() +} + +func TestRedisPoolFIFORecyclesStaleIdleConnectionsLIFODoesNot(t *testing.T) { + for _, tc := range []struct { + name string + fifo bool + }{ + {name: "fifo", fifo: true}, + {name: "lifo", fifo: false}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + srv := miniredis.RunT(t) + cfg := redisPoolTestConfig(t, srv) + cfg.PoolFIFO = tc.fifo + cfg.ConnMaxIdleTimeSeconds = 1 + client := newRedisPoolTestClient(t, cfg) + ctx := context.Background() + + // 突发:12 个请求同时在途,池子被撑到 12 条连接,之后全部空闲。 + holdConnections(client, 12, 250*time.Millisecond) + require.Equal(t, uint32(12), client.PoolStats().TotalConns) + + // 空闲超过 ConnMaxIdleTime 之后,没有流量时一条都不会少:没有后台回收线程。 + time.Sleep(1300 * time.Millisecond) + require.Equal(t, uint32(12), client.PoolStats().TotalConns) + require.Equal(t, 12, srv.CurrentConnectionCount()) + + // 流量恢复(只要一点点):FIFO 从最老的连接开始逐个检查,把过期的都关掉; + // LIFO 只会检查栈顶,取到一条新连接之后一直复用它,栈底那些过期连接永远留在池里。 + for i := 0; i < 30; i++ { + require.NoError(t, client.Ping(ctx).Err()) + } + total := client.PoolStats().TotalConns + if tc.fifo { + require.LessOrEqual(t, total, uint32(5), "FIFO 应该把 12 条过期连接换成少数几条新连接") + require.Eventually(t, func() bool { return srv.CurrentConnectionCount() <= 5 }, 2*time.Second, 10*time.Millisecond) + return + } + require.GreaterOrEqual(t, total, uint32(9), "LIFO 下栈底的过期连接不会被回收") + require.GreaterOrEqual(t, srv.CurrentConnectionCount(), 9) + }) + } +} + +func TestRedisPoolMaxIdleConnsShrinksPoolRightAfterBurst(t *testing.T) { + burstThenTraffic := func(t *testing.T, maxIdle int) (*redis.Client, *miniredis.Miniredis) { + srv := miniredis.RunT(t) + cfg := redisPoolTestConfig(t, srv) + cfg.MaxIdleConns = maxIdle + client := newRedisPoolTestClient(t, cfg) + + holdConnections(client, 12, 150*time.Millisecond) + // go-redis 判断“空闲是否已满”和把连接放回空闲列表不是一个原子操作,12 个请求同时归还时 + // 上限可能被多放过几条;之后每个请求取放一次就会再关掉一条超限的,所以这里跑一点点流量。 + for i := 0; i < 20; i++ { + require.NoError(t, client.Ping(context.Background()).Err()) + } + return client, srv + } + + t.Run("capped", func(t *testing.T) { + client, srv := burstThenTraffic(t, 4) + + // 不需要等空闲超时:超限的连接在归还时就被关掉了。 + stats := client.PoolStats() + require.LessOrEqual(t, stats.TotalConns, uint32(4)) + require.Equal(t, stats.TotalConns, stats.IdleConns) + require.Eventually(t, func() bool { return srv.CurrentConnectionCount() <= 4 }, 2*time.Second, 10*time.Millisecond) + }) + + t.Run("uncapped keeps the high-water mark", func(t *testing.T) { + client, srv := burstThenTraffic(t, 0) + + // 这就是线上的“只涨不缩”:突发撑出来的连接全部留在池里,后续流量也不会关掉它们。 + require.Equal(t, uint32(12), client.PoolStats().TotalConns) + require.Equal(t, 12, srv.CurrentConnectionCount()) + }) +} + +func TestRedisPoolExhaustionFailsFastWithConfiguredPoolTimeout(t *testing.T) { + srv := miniredis.RunT(t) + cfg := redisPoolTestConfig(t, srv) + cfg.PoolSize = 2 + cfg.PoolTimeoutMS = 100 // 不配置时 go-redis 用 ReadTimeout+1s=4s + client := newRedisPoolTestClient(t, cfg) + + // 两个长阻塞命令占满整个池。 + var blockers sync.WaitGroup + for i := 0; i < 2; i++ { + blockers.Add(1) + go func() { + defer blockers.Done() + _ = client.Do(context.Background(), "BLPOP", "redis-pool-hold", "2").Err() + }() + } + require.Eventually(t, func() bool { + s := client.PoolStats() + return s.TotalConns == 2 && s.IdleConns == 0 + }, 2*time.Second, 5*time.Millisecond) + + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + started := time.Now() + err := client.Ping(ctx).Err() + elapsed := time.Since(started) + + // 池耗尽要快速失败,并且失败原因是池超时,而不是排队排到调用方的 context 超时。 + require.ErrorIs(t, err, redis.ErrPoolTimeout) + require.Less(t, elapsed, 2*time.Second) + // go-redis 会把池超时当作可重试错误:每次尝试都要等满 PoolTimeout,所以最坏约 (1+MaxRetries)×PoolTimeout。 + require.GreaterOrEqual(t, elapsed, 100*time.Millisecond) + require.GreaterOrEqual(t, client.PoolStats().Timeouts, uint32(1)) + t.Logf("pool exhausted: failed after %v, pool timeouts=%d", elapsed, client.PoolStats().Timeouts) + + // 关闭客户端会让还在阻塞的命令立刻返回,不用等满 2 秒。 + require.NoError(t, client.Close()) + blockers.Wait() +} + +// 审计结论的证据:WithTimeout 返回的副本与父客户端共用同一个连接池(不会多开一套连接), +// 关闭父客户端后副本也不可用,连接全部释放。 +func TestRedisWithTimeoutClonesShareOnePoolWithTheirParent(t *testing.T) { + srv := miniredis.RunT(t) + client := newRedisPoolTestClient(t, redisPoolTestConfig(t, srv)) + clone := client.WithTimeout(500 * time.Millisecond) + ctx := context.Background() + + holdConnections(clone, 6, 150*time.Millisecond) + require.Equal(t, uint32(6), client.PoolStats().TotalConns, "副本建的连接在父客户端的池里") + require.Equal(t, client.PoolStats().TotalConns, clone.PoolStats().TotalConns) + require.Equal(t, 6, srv.CurrentConnectionCount()) + + require.NoError(t, client.Ping(ctx).Err()) + require.NoError(t, clone.Ping(ctx).Err()) + require.Equal(t, uint32(6), client.PoolStats().TotalConns, "父客户端和副本复用同一批空闲连接") + + require.NoError(t, client.Close()) + require.ErrorIs(t, clone.Ping(ctx).Err(), redis.ErrClosed) + require.Eventually(t, func() bool { return srv.CurrentConnectionCount() == 0 }, 2*time.Second, 10*time.Millisecond) +} diff --git a/backend/internal/repository/redis_test.go b/backend/internal/repository/redis_test.go index 735ae64b..b74f74db 100644 --- a/backend/internal/repository/redis_test.go +++ b/backend/internal/repository/redis_test.go @@ -53,11 +53,32 @@ func TestBuildRedisOptions(t *testing.T) { require.Equal(t, "localhost", optsTLS.TLSConfig.ServerName) } +func TestBuildRedisPoolOptions(t *testing.T) { + r := config.RedisConfig{PoolSize: 512, MinIdleConns: 8, MaxIdleConns: 64, + PoolFIFO: true, PoolTimeoutMS: 1000, ConnMaxIdleTimeSeconds: 300, ConnMaxLifetimeSeconds: 1800} + opts := buildRedisOptions(&config.Config{Redis: r}) + require.Equal(t, 64, opts.MaxIdleConns) + require.True(t, opts.PoolFIFO) + require.Equal(t, time.Second, opts.PoolTimeout) + require.Equal(t, 5*time.Minute, opts.ConnMaxIdleTime) + require.Equal(t, 30*time.Minute, opts.ConnMaxLifetime) + require.Equal(t, 3*time.Minute, opts.ConnMaxLifetimeJitter) + r.MinIdleConns, r.PoolSize = 256, 4096 + require.Equal(t, 256, redisMaxIdleConns(r)) + r.MinIdleConns, r.PoolSize = 0, 32 + require.Equal(t, 32, redisMaxIdleConns(r)) + r.MaxIdleConns = 0 + require.Zero(t, redisMaxIdleConns(r)) + client := redis.NewClient(buildRedisOptions(&config.Config{})) + t.Cleanup(func() { _ = client.Close() }) + require.Equal(t, time.Duration(-1), client.Options().ConnMaxIdleTime) +} + func TestProvideReasoningRedisPreservesOrdinaryOptions(t *testing.T) { cfg := &config.Config{Redis: config.RedisConfig{ Host: "localhost", Port: 6379, Username: "app-user", Password: "secret", DB: 2, DialTimeoutSeconds: 5, ReadTimeoutSeconds: 3, WriteTimeoutSeconds: 4, - PoolSize: 100, MinIdleConns: 10, EnableTLS: true, + PoolSize: 100, MinIdleConns: 10, MaxIdleConns: 6, EnableTLS: true, }} ordinaryOptions := buildRedisOptions(cfg) reasoning := ProvideReasoningRedis(cfg) @@ -65,8 +86,10 @@ func TestProvideReasoningRedisPreservesOrdinaryOptions(t *testing.T) { opts := reasoning.Options() require.False(t, ordinaryOptions.ContextTimeoutEnabled) require.Equal(t, 10, ordinaryOptions.MinIdleConns) + require.Equal(t, 10, ordinaryOptions.MaxIdleConns) require.True(t, opts.ContextTimeoutEnabled) require.Zero(t, opts.MinIdleConns) + require.Equal(t, 6, opts.MaxIdleConns, "reasoning pool has no prewarm floor") require.Equal(t, ordinaryOptions.Addr, opts.Addr) require.Equal(t, ordinaryOptions.Username, opts.Username) require.Equal(t, ordinaryOptions.Password, opts.Password) diff --git a/backend/internal/service/openai_gateway_request_body.go b/backend/internal/service/openai_gateway_request_body.go index 6891e75d..f14b8cd0 100644 --- a/backend/internal/service/openai_gateway_request_body.go +++ b/backend/internal/service/openai_gateway_request_body.go @@ -1021,12 +1021,12 @@ func newOpenAIRequestView(body []byte) openAIRequestView { view := openAIRequestView{body: body} var seen uint8 - // parseRawJSONView reads body without copying; view keeps body alive for extracted strings. + // Extracted strings can outlive the request through billing and logging. parseRawJSONView(body).ForEach(func(key, value gjson.Result) bool { switch key.Str { case "model": if seen&modelField == 0 { - view.Model = strings.TrimSpace(value.String()) + view.Model = strings.Clone(strings.TrimSpace(value.String())) seen |= modelField } case "stream": @@ -1036,22 +1036,22 @@ func newOpenAIRequestView(body []byte) openAIRequestView { } case "prompt_cache_key": if seen&promptCacheKeyField == 0 { - view.PromptCacheKey = strings.TrimSpace(value.String()) + view.PromptCacheKey = strings.Clone(strings.TrimSpace(value.String())) seen |= promptCacheKeyField } case "previous_response_id": if seen&previousResponseIDField == 0 { - view.PreviousResponseID = strings.TrimSpace(value.String()) + view.PreviousResponseID = strings.Clone(strings.TrimSpace(value.String())) seen |= previousResponseIDField } case "service_tier": if seen&serviceTierField == 0 { - view.ServiceTier = strings.TrimSpace(value.String()) + view.ServiceTier = strings.Clone(strings.TrimSpace(value.String())) seen |= serviceTierField } case "reasoning": if seen&reasoningField == 0 { - view.ReasoningEffort = strings.TrimSpace(value.Get("effort").String()) + view.ReasoningEffort = strings.Clone(strings.TrimSpace(value.Get("effort").String())) seen |= reasoningField } } diff --git a/backend/internal/service/request_string_detach.go b/backend/internal/service/request_string_detach.go new file mode 100644 index 00000000..801ab3e8 --- /dev/null +++ b/backend/internal/service/request_string_detach.go @@ -0,0 +1,65 @@ +package service + +import ( + "reflect" + "strings" +) + +// 请求体里切出来的短字符串(模型名、reasoning effort、prompt_cache_key……)大多是零拷贝子串, +// 指针指向请求体本身。这些字符串一旦被放进「活得比请求久」的对象——计费任务队列、usage_logs +// 批量写入队列、结果对象——一个 20 字节的模型名就会把整份请求体(可达数 MB)钉在内存里,直到 +// 队列被消费完。计费库一变慢,队列里排着几千份已经结束的请求体,这是进程内存涨到 +// GOMEMLIMIT 的主要放大器。 +// +// detachStringFields 把一个结构体上所有导出的 string / *string / []string 字段换成自己的拷贝, +// 值不变,只是不再指向请求体。拷贝只有几十个小字符串,相对一次请求可以忽略。 + +// DetachRequestStrings 复制结果里所有字符串字段,使其不再引用请求体。 +func (r *ForwardResult) DetachRequestStrings() { detachStringFields(r) } + +// DetachRequestStrings 复制结果里所有字符串字段,使其不再引用请求体。 +func (r *OpenAIForwardResult) DetachRequestStrings() { detachStringFields(r) } + +// Detached 返回字符串字段都已复制的副本。 +func (f ChannelUsageFields) Detached() ChannelUsageFields { + detachStringFields(&f) + return f +} + +// detachStringFields 复制 v(必须是指向结构体的指针)的导出 string、*string、[]string 字段。 +// *string 换成指向新字符串的新指针,不改被指向的原对象(它可能被别处共享)。 +func detachStringFields(v any) { + rv := reflect.ValueOf(v) + if rv.Kind() != reflect.Pointer || rv.IsNil() || rv.Elem().Kind() != reflect.Struct { + return + } + rv = rv.Elem() + for i := 0; i < rv.NumField(); i++ { + f := rv.Field(i) + if !f.CanSet() { + continue + } + switch f.Kind() { + case reflect.String: + if f.Len() > 0 { + f.SetString(strings.Clone(f.String())) + } + case reflect.Pointer: + if f.IsNil() || f.Type().Elem().Kind() != reflect.String { + continue + } + cp := reflect.New(f.Type().Elem()) + cp.Elem().SetString(strings.Clone(f.Elem().String())) + f.Set(cp) + case reflect.Slice: + if f.IsNil() || f.Type().Elem().Kind() != reflect.String { + continue + } + cp := reflect.MakeSlice(f.Type(), f.Len(), f.Len()) + for j := 0; j < f.Len(); j++ { + cp.Index(j).SetString(strings.Clone(f.Index(j).String())) + } + f.Set(cp) + } + } +} diff --git a/backend/internal/service/request_string_detach_test.go b/backend/internal/service/request_string_detach_test.go new file mode 100644 index 00000000..3a6248ed --- /dev/null +++ b/backend/internal/service/request_string_detach_test.go @@ -0,0 +1,127 @@ +package service + +import ( + "net/http" + "runtime" + "strings" + "testing" + "time" + "unsafe" + "weak" + + "github.com/stretchr/testify/require" +) + +// aliasingString returns a string that is a window into buf, the way gjson/parseRawJSONView hand out +// substrings of a request body. +func aliasingString(buf []byte, from, to int) string { + return unsafe.String(&buf[from], to-from) +} + +func requireBodyCollected(t *testing.T, w weak.Pointer[byte], msg string) { + t.Helper() + require.Eventually(t, func() bool { + runtime.GC() + return w.Value() == nil + }, 3*time.Second, 5*time.Millisecond, msg) +} + +func newAliasedBody(size int) (buf []byte, w weak.Pointer[byte]) { + buf = []byte(`{"model":"claude-opus-5-5","effort":"high"}` + strings.Repeat(" ", size)) + return buf, weak.Make(&buf[0]) +} + +// The strings of a usage result are queued for as long as billing is slow. If they point into the request +// body they pin all of it; DetachRequestStrings must leave them with memory of their own. +func TestDetachRequestStringsReleasesTheRequestBody(t *testing.T) { + type kase struct { + name string + detach func(buf []byte) (keep any) + } + cases := []kase{ + {"ForwardResult", func(buf []byte) any { + effort := aliasingString(buf, 37, 41) + r := &ForwardResult{ + Model: aliasingString(buf, 10, 25), + UpstreamModel: aliasingString(buf, 10, 25), + UpstreamResponseServiceTier: aliasingString(buf, 37, 41), + ReasoningEffort: &effort, + RequestedReasoningEffort: &effort, + ImageOutputSizes: []string{aliasingString(buf, 10, 15)}, + } + r.DetachRequestStrings() + return r + }}, + {"OpenAIForwardResult", func(buf []byte) any { + tier := aliasingString(buf, 37, 41) + r := &OpenAIForwardResult{ + Model: aliasingString(buf, 10, 25), + BillingModel: aliasingString(buf, 10, 25), + UpstreamModel: aliasingString(buf, 10, 25), + ServiceTier: &tier, + RequestID: aliasingString(buf, 2, 7), + } + r.DetachRequestStrings() + return r + }}, + {"ChannelUsageFields", func(buf []byte) any { + f := ChannelUsageFields{OriginalModel: aliasingString(buf, 10, 25), ChannelMappedModel: aliasingString(buf, 10, 25), ModelMappingChain: aliasingString(buf, 10, 25)}.Detached() + return f + }}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + keep, w := func() (any, weak.Pointer[byte]) { + buf, w := newAliasedBody(1 << 20) + return tc.detach(buf), w + }() + requireBodyCollected(t, w, "a detached result still pins the 1 MiB request body") + runtime.KeepAlive(keep) + }) + } +} + +func TestDetachRequestStringsKeepsEveryValue(t *testing.T) { + buf, _ := newAliasedBody(16) + effort := aliasingString(buf, 37, 41) + r := &OpenAIForwardResult{ + Model: aliasingString(buf, 10, 25), RequestID: "req-1", ServiceTier: &effort, + ImageOutputSizes: []string{"1K", aliasingString(buf, 10, 15)}, + Usage: OpenAIUsage{InputTokens: 12, OutputTokens: 34}, + Duration: 5 * time.Second, + ResponseHeaders: http.Header{"X-Test": {"1"}}, + } + r.DetachRequestStrings() + require.Equal(t, "claude-opus-5-5", r.Model) + require.Equal(t, "req-1", r.RequestID) + require.NotNil(t, r.ServiceTier) + require.Equal(t, "high", *r.ServiceTier) + require.Equal(t, []string{"1K", "claud"}, r.ImageOutputSizes) + require.Equal(t, 12, r.Usage.InputTokens) + require.Equal(t, 34, r.Usage.OutputTokens) + require.Equal(t, 5*time.Second, r.Duration) + require.Equal(t, "1", r.ResponseHeaders.Get("X-Test")) + // the *string pointee is replaced, not edited in place: whoever shared the old pointer still holds the old pointer + require.NotSame(t, &effort, r.ServiceTier) + var nilResult *OpenAIForwardResult + nilResult.DetachRequestStrings() // must not panic + var nilForward *ForwardResult + nilForward.DetachRequestStrings() +} + +// The request view hands its model / cache key / tier / effort strings to usage results and logs. +func TestOpenAIRequestViewStringsDoNotPinTheBody(t *testing.T) { + view, w := func() (openAIRequestView, weak.Pointer[byte]) { + body := []byte(`{"model":"deepseek-v4-flash","stream":true,"prompt_cache_key":"pck-123","previous_response_id":"resp_1","service_tier":"priority","reasoning":{"effort":"high"},"input":"` + strings.Repeat("p", 1<<20) + `"}`) + v := newOpenAIRequestView(body) + v.body = nil // the view's own body field is request-scoped; only the extracted strings outlive it + return v, weak.Make(&body[0]) + }() + requireBodyCollected(t, w, "newOpenAIRequestView strings point into the request body") + require.Equal(t, "deepseek-v4-flash", view.Model) + require.True(t, view.Stream) + require.Equal(t, "pck-123", view.PromptCacheKey) + require.Equal(t, "resp_1", view.PreviousResponseID) + require.Equal(t, "priority", view.ServiceTier) + require.Equal(t, "high", view.ReasoningEffort) +} diff --git a/backend/internal/service/update_source_baselines.go b/backend/internal/service/update_source_baselines.go index 3b24b84a..b75b154f 100644 --- a/backend/internal/service/update_source_baselines.go +++ b/backend/internal/service/update_source_baselines.go @@ -4,8 +4,8 @@ package service // this project's release version. A reviewed checkpoint does not imply every // feature was merged. Update only after the corresponding review/sync completes. const ( - forkImportedVersion = "2.3.175" - forkImportedCommit = "595b9a2fef6fd141a4a1f94a1659b98b093d7add" + forkImportedVersion = "2.4.5" + forkImportedCommit = "1e242d7a64c02d93f4f0c68023a436b99c3e8c16" originalReviewedCommit = "348997267d756eab5729bb6b78a275a15d18796a" ) diff --git a/deploy/config.example.yaml b/deploy/config.example.yaml index 5bc66d75..16fb22cf 100644 --- a/deploy/config.example.yaml +++ b/deploy/config.example.yaml @@ -955,10 +955,19 @@ redis: db: 0 # Connection pool size (max concurrent connections) # 连接池大小(最大并发连接数) - pool_size: 1024 - # Minimum number of idle connections (高并发场景建议 128+,保持足够热连接) + pool_size: 512 + # Minimum number of idle connections # 最小空闲连接数 - min_idle_conns: 128 + min_idle_conns: 8 + # Idle cap is normalized to [min_idle_conns, pool_size]; 0 disables the cap. + max_idle_conns: 64 + # Rotate idle connections so old connections can expire. + pool_fifo: true + # Wait for an available pooled connection (milliseconds). + pool_timeout_ms: 1000 + # 0 disables idle expiry / maximum lifetime respectively. + conn_max_idle_time_seconds: 300 + conn_max_lifetime_seconds: 1800 # Enable TLS/SSL connection # 是否启用 TLS/SSL 连接 enable_tls: false diff --git a/docs/release-notes/v2.1.76.md b/docs/release-notes/v2.1.76.md new file mode 100644 index 00000000..ad6636de --- /dev/null +++ b/docs/release-notes/v2.1.76.md @@ -0,0 +1,17 @@ +选择性同步二改 v2.4.5,修复计费队列请求串号和内存保留、监控超大延迟显示,并收紧登录跳转和运维 WebSocket 校验。 + +## 修复与优化 + +- Redis 连接池采用 FIFO 轮转、空闲连接上限、独立池等待超时和连接寿命回收。现有显式参数继续优先,独立 reasoning 池保留调用方 deadline 和无预热行为;配置示例补齐新选项。 +- 异步计费入队前复制请求级元数据、公开模型和映射字段,并复制可能引用大请求体的短字符串,避免队列持有已结束请求的上下文,或 Gin 复用后记录下一次请求的模型。保留计费同步兜底、在途余额引用和预授权所有权。 +- 监控直方图 +Inf 溢出标记不再显示成真实的超大毫秒值;溢出分位值仍属于分桶近似。前端拦截负数、非有限值和历史 sentinel。 +- Ops WebSocket 校验 HTTP(S) Origin 与请求 Host,停止信任 X-Forwarded-Host;拒绝全网段代理信任并规范 IPv4-mapped CIDR,保留既有端口和缺失 Origin 策略。 +- 登录及 OAuth 发起/回调共用站内跳转校验,兼容重复 query 参数,拒绝反斜杠和控制字符;后端 OAuth 跳转校验同步收紧。 + +## 升级与验证 + +现有生图分组、Images API、批量生图、用户 Key、价格/倍率、原生厂商路由和个人主题保留,无限画布继续移除。无 SQL 迁移、依赖升级或生产配置文件改动;新 Redis 默认值适用于未显式配置的选项,保留 v2.1.75 程序用于回滚。 + +同步阶段通过 686 个独立顶层 Go 测试、包含子测试共 1,728 项,前端 174 项测试、11 项本地浏览器交互检查,以及前端生产构建和 Linux embed 构建。正式发布增加所选请求隔离/Redis/跳转安全路径的 race 回归,并按精确提交 CI、正式归档/GHCR 校验、数据库备份实际恢复和受控服务切换流程执行。最终部署证据单独保存,不调用付费模型或生图接口。 + +原版正式版本仍为 v0.2.25。本版为选择性适配;新账本/PG hold/配额镜像、完整 MFA/Key seal、全请求体索引及其他延期模块未整组导入,完整来源与取舍见[同步记录](../../maintenance/notes/upstream-sync-20261128-v245.md)。 diff --git a/frontend/src/components/auth/DingTalkOAuthSection.vue b/frontend/src/components/auth/DingTalkOAuthSection.vue index dcb2fbc5..179d880f 100644 --- a/frontend/src/components/auth/DingTalkOAuthSection.vue +++ b/frontend/src/components/auth/DingTalkOAuthSection.vue @@ -37,6 +37,7 @@