diff --git a/.gitignore b/.gitignore index 3ee8dfee88..1af51f759f 100644 --- a/.gitignore +++ b/.gitignore @@ -133,6 +133,7 @@ deploy/docker-compose.override.yml .gocache/ vite.config.js docs/* +!docs/agent-resource-safety.md !docs/admin-api-keys.md !docs/mcp.md !docs/PAYMENT.md diff --git a/backend/cmd/server/wire.go b/backend/cmd/server/wire.go index 6834ad78df..05c3334f13 100644 --- a/backend/cmd/server/wire.go +++ b/backend/cmd/server/wire.go @@ -111,6 +111,8 @@ func provideCleanup( emailQueue *service.EmailQueueService, billingCache *service.BillingCacheService, usageRecordWorkerPool *service.UsageRecordWorkerPool, + balanceNotify *service.BalanceNotifyService, + digestSessions *service.DigestSessionStore, subscriptionService *service.SubscriptionService, oauth *service.OAuthService, openaiOAuth *service.OpenAIOAuthService, @@ -143,6 +145,18 @@ func provideCleanup( // 应用层清理步骤可并行执行,基础设施资源(Redis/Ent)最后按顺序关闭。 parallelSteps := []cleanupStep{ + {"DigestSessionStore", func() error { + if digestSessions != nil { + digestSessions.Close() + } + return nil + }}, + {"BalanceNotifyService", func() error { + if balanceNotify != nil { + balanceNotify.Stop() + } + return nil + }}, {"PluginManager", func() error { if pluginManager != nil { pluginManager.Stop() diff --git a/backend/cmd/server/wire_gen.go b/backend/cmd/server/wire_gen.go index 80bdf0c732..1356765b79 100644 --- a/backend/cmd/server/wire_gen.go +++ b/backend/cmd/server/wire_gen.go @@ -359,7 +359,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { channelMonitorRunner := service.ProvideChannelMonitorRunner(channelMonitorService, settingService, channelMonitorQuotaFetcher) channelMonitorV2Aggregator := service.ProvideChannelMonitorV2Aggregator(channelMonitorV2Repository, db, settingService) userPlatformQuotaUsageFlusher := service.ProvideUserPlatformQuotaUsageFlusher(configConfig, billingCache, serviceUserPlatformQuotaRepository, timingWheelService) - v := provideCleanup(client, redisClient, opsMetricsCollector, opsAggregationService, opsAlertEvaluatorService, opsCleanupService, opsScheduledReportService, opsSystemLogSink, opsService, opsIngressRejectAggregator, apiKeyService, authCacheInvalidationWorker, schedulerSnapshotService, tokenRefreshService, accountExpiryService, cnProviderBalanceCheckService, openAICodexVersionSyncService, claudeCodeVersionSyncService, proxyExpiryService, subscriptionExpiryService, usageCleanupService, idempotencyCleanupService, geminiCachedContentService, batchImageCleanupService, batchImageWorkerRuntime, pricingService, emailQueueService, billingCacheService, usageRecordWorkerPool, subscriptionService, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, grokOAuthService, openAIGatewayService, scheduledTestRunnerService, backupService, paymentOrderExpiryService, channelMonitorRunner, channelMonitorV2Aggregator, userPlatformQuotaUsageFlusher, upstreamBillingProbeService, ollamaCloudUsageService, openCodeGoUsageService, auditLogService, openAIQuotaAutoResetService, promptService, pluginManager) + v := provideCleanup(client, redisClient, opsMetricsCollector, opsAggregationService, opsAlertEvaluatorService, opsCleanupService, opsScheduledReportService, opsSystemLogSink, opsService, opsIngressRejectAggregator, apiKeyService, authCacheInvalidationWorker, schedulerSnapshotService, tokenRefreshService, accountExpiryService, cnProviderBalanceCheckService, openAICodexVersionSyncService, claudeCodeVersionSyncService, proxyExpiryService, subscriptionExpiryService, usageCleanupService, idempotencyCleanupService, geminiCachedContentService, batchImageCleanupService, batchImageWorkerRuntime, pricingService, emailQueueService, billingCacheService, usageRecordWorkerPool, balanceNotifyService, digestSessionStore, subscriptionService, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, grokOAuthService, openAIGatewayService, scheduledTestRunnerService, backupService, paymentOrderExpiryService, channelMonitorRunner, channelMonitorV2Aggregator, userPlatformQuotaUsageFlusher, upstreamBillingProbeService, ollamaCloudUsageService, openCodeGoUsageService, auditLogService, openAIQuotaAutoResetService, promptService, pluginManager) application := &Application{ Server: httpServer, PromptAudit: promptService, @@ -426,6 +426,8 @@ func provideCleanup( emailQueue *service.EmailQueueService, billingCache *service.BillingCacheService, usageRecordWorkerPool *service.UsageRecordWorkerPool, + balanceNotify *service.BalanceNotifyService, + digestSessions *service.DigestSessionStore, subscriptionService *service.SubscriptionService, oauth *service.OAuthService, openaiOAuth *service.OpenAIOAuthService, @@ -457,6 +459,18 @@ func provideCleanup( } parallelSteps := []cleanupStep{ + {"DigestSessionStore", func() error { + if digestSessions != nil { + digestSessions.Close() + } + return nil + }}, + {"BalanceNotifyService", func() error { + if balanceNotify != nil { + balanceNotify.Stop() + } + return nil + }}, {"PluginManager", func() error { if pluginManager != nil { pluginManager.Stop() diff --git a/backend/cmd/server/wire_gen_test.go b/backend/cmd/server/wire_gen_test.go index bb56c6735f..b8e601a508 100644 --- a/backend/cmd/server/wire_gen_test.go +++ b/backend/cmd/server/wire_gen_test.go @@ -81,6 +81,8 @@ func TestProvideCleanup_WithMinimalDependencies_NoPanic(t *testing.T) { emailQueueSvc, billingCacheSvc, &service.UsageRecordWorkerPool{}, + service.ProvideBalanceNotifyService(nil, nil, nil, nil), + service.NewDigestSessionStore(), &service.SubscriptionService{}, oauthSvc, openAIOAuthSvc, diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go index bd90fd7ffb..4b9a59cad0 100644 --- a/backend/internal/config/config.go +++ b/backend/internal/config/config.go @@ -1049,6 +1049,12 @@ type GatewayConfig struct { OpenAIHighEffortFirstOutputTimeoutSeconds int `mapstructure:"openai_high_effort_first_output_timeout_seconds"` // 请求体最大字节数,用于网关请求体大小限制 MaxBodySize int64 `mapstructure:"max_body_size"` + // RequestBodyMemoryBudgetBytes bounds buffered ingress allocations per instance; 0 disables it. + RequestBodyMemoryBudgetBytes int64 `mapstructure:"request_body_memory_budget_bytes"` + // RequestBodyReadTimeoutSeconds bounds each socket read during upload; 0 disables it. + RequestBodyReadTimeoutSeconds int `mapstructure:"request_body_read_timeout_seconds"` + // DownstreamWriteTimeoutSeconds bounds each HTTP write/flush, not the lifetime of a stream. + DownstreamWriteTimeoutSeconds int `mapstructure:"downstream_write_timeout_seconds"` // TextMaxBodySize limits endpoints that cannot carry inline image/video payloads. TextMaxBodySize int64 `mapstructure:"text_max_body_size"` // 非流式上游响应体读取上限(字节),用于防止无界读取导致内存放大 @@ -1143,7 +1149,10 @@ type GatewayConfig struct { // ImageNonstreamKeepaliveInterval: 图片非流式 JSON keepalive 间隔(秒),0表示禁用 ImageNonstreamKeepaliveInterval int `mapstructure:"image_nonstream_keepalive_interval"` // MaxLineSize: 上游 SSE 单行最大字节数(0使用默认值) - MaxLineSize int `mapstructure:"max_line_size"` + MaxLineSize int `mapstructure:"max_line_size"` + SSEQueueMaxBytes int64 `mapstructure:"sse_queue_max_bytes"` + SSEEventMaxBytes int64 `mapstructure:"sse_event_max_bytes"` + SSEEventMaxLines int `mapstructure:"sse_event_max_lines"` // 是否记录上游错误响应体摘要(避免输出请求内容) LogUpstreamErrorBody bool `mapstructure:"log_upstream_error_body"` @@ -2584,6 +2593,9 @@ func setDefaults() { viper.SetDefault("gateway.antigravity_fallback_cooldown_minutes", 1) viper.SetDefault("gateway.antigravity_extra_retries", 10) viper.SetDefault("gateway.max_body_size", int64(256*1024*1024)) + viper.SetDefault("gateway.request_body_memory_budget_bytes", int64(1024*1024*1024)) + viper.SetDefault("gateway.request_body_read_timeout_seconds", 120) + viper.SetDefault("gateway.downstream_write_timeout_seconds", 120) viper.SetDefault("gateway.text_max_body_size", int64(32*1024*1024)) viper.SetDefault("gateway.upstream_response_read_max_bytes", DefaultUpstreamResponseReadMaxBytes) viper.SetDefault("gateway.models_list_read_max_bytes", DefaultModelsListReadMaxBytes) @@ -2605,6 +2617,9 @@ func setDefaults() { viper.SetDefault("gateway.image_stream_keepalive_interval", 10) viper.SetDefault("gateway.image_nonstream_keepalive_interval", 0) viper.SetDefault("gateway.max_line_size", 500*1024*1024) + viper.SetDefault("gateway.sse_queue_max_bytes", int64(8*1024*1024)) + viper.SetDefault("gateway.sse_event_max_bytes", int64(0)) + viper.SetDefault("gateway.sse_event_max_lines", 4096) viper.SetDefault("gateway.scheduling.sticky_session_max_waiting", 3) viper.SetDefault("gateway.scheduling.sticky_session_wait_timeout", 120*time.Second) viper.SetDefault("gateway.scheduling.fallback_wait_timeout", 30*time.Second) @@ -3408,6 +3423,18 @@ func (c *Config) Validate() error { if c.Gateway.MaxBodySize <= 0 { return fmt.Errorf("gateway.max_body_size must be positive") } + if c.Gateway.RequestBodyMemoryBudgetBytes < 0 { + return fmt.Errorf("gateway.request_body_memory_budget_bytes must be non-negative") + } + if c.Gateway.RequestBodyReadTimeoutSeconds < 0 || c.Gateway.RequestBodyReadTimeoutSeconds > 3600 { + return fmt.Errorf("gateway.request_body_read_timeout_seconds must be between 0 and 3600") + } + if c.Gateway.DownstreamWriteTimeoutSeconds < 0 || c.Gateway.DownstreamWriteTimeoutSeconds > 3600 { + return fmt.Errorf("gateway.downstream_write_timeout_seconds must be between 0 and 3600") + } + if c.Gateway.SSEQueueMaxBytes < 0 || c.Gateway.SSEEventMaxBytes < 0 || c.Gateway.SSEEventMaxLines < 0 { + return fmt.Errorf("gateway.sse_queue_max_bytes, sse_event_max_bytes and sse_event_max_lines must be non-negative") + } if c.Gateway.TextMaxBodySize <= 0 || c.Gateway.TextMaxBodySize > c.Gateway.MaxBodySize { return fmt.Errorf("gateway.text_max_body_size must be positive and no greater than gateway.max_body_size") } diff --git a/backend/internal/config/config_test.go b/backend/internal/config/config_test.go index adb48e5bb2..bc579aecfd 100644 --- a/backend/internal/config/config_test.go +++ b/backend/internal/config/config_test.go @@ -144,6 +144,12 @@ func TestLoadHTTPIngressSafetyDefaults(t *testing.T) { require.False(t, cfg.Server.TrustedProxiesConfigured) require.True(t, cfg.TrustForwardedIPForAPIKeyACL()) require.Equal(t, int64(32*1024*1024), cfg.Gateway.TextMaxBodySize) + require.Equal(t, int64(1<<30), cfg.Gateway.RequestBodyMemoryBudgetBytes) + require.Equal(t, 120, cfg.Gateway.RequestBodyReadTimeoutSeconds) + require.Equal(t, 120, cfg.Gateway.DownstreamWriteTimeoutSeconds) + require.Equal(t, 500<<20, cfg.Gateway.MaxLineSize) + require.Equal(t, int64(8<<20), cfg.Gateway.SSEQueueMaxBytes) + require.Equal(t, 4096, cfg.Gateway.SSEEventMaxLines) require.True(t, cfg.APIKeyAuth.InvalidAbuse.Enabled) require.Equal(t, 120, cfg.APIKeyAuth.InvalidAbuse.Threshold) require.Equal(t, 16384, cfg.APIKeyAuth.InvalidAbuse.Capacity) @@ -1634,6 +1640,16 @@ func TestValidateConfigErrors(t *testing.T) { mutate func(*Config) wantErr string }{ + { + name: "negative ingress memory budget", + mutate: func(c *Config) { c.Gateway.RequestBodyMemoryBudgetBytes = -1 }, + wantErr: "gateway.request_body_memory_budget_bytes", + }, + { + name: "negative upload timeout", + mutate: func(c *Config) { c.Gateway.RequestBodyReadTimeoutSeconds = -1 }, + wantErr: "gateway.request_body_read_timeout_seconds", + }, { name: "server read header timeout", mutate: func(c *Config) { c.Server.ReadHeaderTimeout = 0 }, diff --git a/backend/internal/handler/gateway_handler.go b/backend/internal/handler/gateway_handler.go index be7cc0a1b0..58372073dd 100644 --- a/backend/internal/handler/gateway_handler.go +++ b/backend/internal/handler/gateway_handler.go @@ -147,6 +147,9 @@ func (h *GatewayHandler) Messages(c *gin.Context) { // 读取请求体 body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg) if err != nil { + if handleRequestBodyReadError(c, err) { + return + } if maxErr, ok := extractMaxBytesError(err); ok { h.errorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) return @@ -599,6 +602,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) { forceCacheBilling := fs.ForceCacheBilling quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) sessionID := service.ExtractClientSessionID(c) + 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, @@ -616,7 +620,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"), @@ -962,6 +966,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) { forceCacheBilling := fs.ForceCacheBilling quotaPlatform := service.QuotaPlatform(c.Request.Context(), currentAPIKey) sessionID := service.ExtractClientSessionID(c) + 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, @@ -979,7 +984,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"), @@ -2158,6 +2163,9 @@ func (h *GatewayHandler) CountTokens(c *gin.Context) { // 读取请求体 body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg) if err != nil { + if handleRequestBodyReadError(c, err) { + return + } if maxErr, ok := extractMaxBytesError(err); ok { h.errorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) return diff --git a/backend/internal/handler/gateway_handler_chat_completions.go b/backend/internal/handler/gateway_handler_chat_completions.go index ab9f931390..55abd416a2 100644 --- a/backend/internal/handler/gateway_handler_chat_completions.go +++ b/backend/internal/handler/gateway_handler_chat_completions.go @@ -47,6 +47,9 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { // Read request body body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg) if err != nil { + if handleRequestBodyReadError(c, err) { + return + } if maxErr, ok := extractMaxBytesError(err); ok { h.chatCompletionsErrorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) return @@ -333,6 +336,7 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) sessionID := service.ExtractClientSessionID(c) stampForwardRequestedReasoningEffort(result, service.RequestedReasoningEffortFromContext(c.Request.Context())) + 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, @@ -349,7 +353,7 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { RequestPayloadHash: requestPayloadHash, APIKeyService: h.apiKeyService, SessionID: sessionID, - ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel), + ChannelUsageFields: channelUsageFields, }); err != nil { reqLog.Error("gateway.cc.record_usage_failed", zap.Int64("account_id", account.ID), diff --git a/backend/internal/handler/gateway_handler_responses.go b/backend/internal/handler/gateway_handler_responses.go index 1800e5dda5..233cf07f3b 100644 --- a/backend/internal/handler/gateway_handler_responses.go +++ b/backend/internal/handler/gateway_handler_responses.go @@ -47,6 +47,9 @@ func (h *GatewayHandler) Responses(c *gin.Context) { // Read request body body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg) if err != nil { + if handleRequestBodyReadError(c, err) { + return + } if maxErr, ok := extractMaxBytesError(err); ok { h.responsesErrorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) return @@ -315,6 +318,7 @@ func (h *GatewayHandler) Responses(c *gin.Context) { quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) sessionID := service.ExtractClientSessionID(c) stampForwardRequestedReasoningEffort(result, service.RequestedReasoningEffortFromContext(c.Request.Context())) + 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, @@ -331,7 +335,7 @@ func (h *GatewayHandler) Responses(c *gin.Context) { RequestPayloadHash: requestPayloadHash, APIKeyService: h.apiKeyService, SessionID: sessionID, - ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel), + ChannelUsageFields: channelUsageFields, }); err != nil { reqLog.Error("gateway.responses.record_usage_failed", zap.Int64("account_id", account.ID), diff --git a/backend/internal/handler/gateway_systemone.go b/backend/internal/handler/gateway_systemone.go index f9cc753c79..4f0d650985 100644 --- a/backend/internal/handler/gateway_systemone.go +++ b/backend/internal/handler/gateway_systemone.go @@ -56,6 +56,9 @@ func (h *GatewayHandler) SystemOne(c *gin.Context) { body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg) if err != nil { + if handleRequestBodyReadError(c, err) { + return + } if maxErr, ok := extractMaxBytesError(err); ok { h.errorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) return @@ -258,9 +261,13 @@ func (h *GatewayHandler) recordSystemOneUsage(c *gin.Context, apiKey *service.AP sessionID := service.ExtractClientSessionID(c) requestPayloadHash := service.HashUsageRequestPayload(body) + // An interior pointer into SystemOneForwardResult would also retain its + // response body while usage waits in the queue. Copy only billing metadata. + forwardResult := result.ForwardResult + channelUsageFields := clientRequestedUsageFields(c, mapping, model, result.UpstreamModel) h.submitMandatoryUsageRecordTask(c.Request.Context(), func(ctx context.Context) { if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{ - Result: &result.ForwardResult, + Result: &forwardResult, APIKey: apiKey, User: apiKey.User, Account: account, @@ -274,7 +281,7 @@ func (h *GatewayHandler) recordSystemOneUsage(c *gin.Context, apiKey *service.AP RequestPayloadHash: requestPayloadHash, APIKeyService: h.apiKeyService, QuotaPlatform: quotaPlatform, - ChannelUsageFields: clientRequestedUsageFields(c, mapping, model, result.UpstreamModel), + ChannelUsageFields: channelUsageFields, }); err != nil { logger.L().With( zap.String("component", "handler.gateway.systemone"), diff --git a/backend/internal/handler/gemini_cached_contents_handler.go b/backend/internal/handler/gemini_cached_contents_handler.go index 2071c16129..ad6cb765dc 100644 --- a/backend/internal/handler/gemini_cached_contents_handler.go +++ b/backend/internal/handler/gemini_cached_contents_handler.go @@ -65,6 +65,9 @@ func (h *GatewayHandler) geminiCachedContentsPreamble(c *gin.Context, component func readGeminiCachedContentBody(c *gin.Context) ([]byte, bool) { body, err := pkghttputil.ReadRequestBodyWithPrealloc(c.Request) if err != nil { + if handleRequestBodyReadError(c, err) { + return nil, false + } if maxErr, ok := extractMaxBytesError(err); ok { googleError(c, http.StatusRequestEntityTooLarge, buildBodyTooLargeMessage(maxErr.Limit)) return nil, false diff --git a/backend/internal/handler/gemini_v1beta_handler.go b/backend/internal/handler/gemini_v1beta_handler.go index 3c8c34bb53..57c91802fd 100644 --- a/backend/internal/handler/gemini_v1beta_handler.go +++ b/backend/internal/handler/gemini_v1beta_handler.go @@ -374,6 +374,9 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) { body, err := pkghttputil.ReadRequestBodyWithPrealloc(c.Request) if err != nil { + if handleRequestBodyReadError(c, err) { + return + } if maxErr, ok := extractMaxBytesError(err); ok { googleError(c, http.StatusRequestEntityTooLarge, buildBodyTooLargeMessage(maxErr.Limit)) return @@ -830,6 +833,7 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) { quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) sessionID := service.ExtractClientSessionID(c) // 长上下文阶梯由目录数据驱动,统一在计费路径内生效,入口无需声明。 + 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, @@ -847,7 +851,7 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) { ForceCacheBilling: forceCacheBilling, APIKeyService: h.apiKeyService, SessionID: sessionID, - ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel), + ChannelUsageFields: channelUsageFields, }); err != nil { logger.L().With( zap.String("component", "handler.gemini_v1beta.models"), diff --git a/backend/internal/handler/grok_audio.go b/backend/internal/handler/grok_audio.go index 7455485d7b..91814fdf4c 100644 --- a/backend/internal/handler/grok_audio.go +++ b/backend/internal/handler/grok_audio.go @@ -4,12 +4,12 @@ import ( "context" "encoding/json" "errors" - "io" "net/http" "strconv" "strings" "time" + pkghttputil "github.com/Wei-Shaw/sub2api/internal/pkg/httputil" "github.com/Wei-Shaw/sub2api/internal/pkg/ip" "github.com/Wei-Shaw/sub2api/internal/pkg/logger" middleware2 "github.com/Wei-Shaw/sub2api/internal/server/middleware" @@ -203,6 +203,9 @@ func (h *OpenAIGatewayHandler) GrokVoice(c *gin.Context, endpoint string) { body, err := readGrokVoiceGatewayBody(c) if err != nil { + if handleRequestBodyReadError(c, err) { + return + } h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", err.Error()) return } @@ -344,6 +347,7 @@ func (h *OpenAIGatewayHandler) recordGrokVoiceUsage( model = endpoint } + 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, @@ -359,7 +363,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"), @@ -383,7 +387,7 @@ func readGrokVoiceGatewayBody(c *gin.Context) ([]byte, error) { } return nil, errors.New("request body is required") } - return io.ReadAll(c.Request.Body) + return pkghttputil.ReadRequestBodyWithPrealloc(c.Request) } // extractGrokTTSInputText pulls the primary spoken text from a TTS JSON body. diff --git a/backend/internal/handler/grok_audio_body_test.go b/backend/internal/handler/grok_audio_body_test.go new file mode 100644 index 0000000000..84621dce9f --- /dev/null +++ b/backend/internal/handler/grok_audio_body_test.go @@ -0,0 +1,53 @@ +package handler + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + pkghttputil "github.com/Wei-Shaw/sub2api/internal/pkg/httputil" + "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" +) + +func TestGrokVoiceRequestBodyMemoryOverload(t *testing.T) { + cfg := &config.Config{RunMode: config.RunModeSimple} + billing := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil) + t.Cleanup(billing.Stop) + h := &OpenAIGatewayHandler{ + gatewayService: &service.OpenAIGatewayService{}, + billingCacheService: billing, + apiKeyService: &service.APIKeyService{}, + concurrencyHelper: &ConcurrencyHelper{concurrencyService: service.NewConcurrencyService(nil)}, + cfg: cfg, + } + for _, endpoint := range []string{"tts", "stt", "custom-voices"} { + t.Run(endpoint, func(t *testing.T) { + router := gin.New() + router.Use(middleware.RequestBodyLimit(1024, pkghttputil.NewBodyMemoryBudget(1))) + router.Use(func(c *gin.Context) { + c.Set(string(middleware.ContextKeyAPIKey), &service.APIKey{ + Group: &service.Group{Platform: service.PlatformGrok}, + User: &service.User{ID: 1}, + }) + c.Next() + }) + // A normal Grok group without an allowlist reaches the handler before + // any middleware reads its body. + router.Use(middleware.GroupModelAllowlist()) + router.POST("/v1/"+endpoint, func(c *gin.Context) { h.GrokVoice(c, endpoint) }) + req := httptest.NewRequest(http.MethodPost, "/v1/"+endpoint, strings.NewReader(`{"input":"hello"}`)) + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + router.ServeHTTP(rec, req) + + require.Equal(t, http.StatusServiceUnavailable, rec.Code, rec.Body.String()) + require.Equal(t, "1", rec.Header().Get("Retry-After")) + require.Contains(t, rec.Body.String(), "Request body buffering capacity is exhausted") + }) + } +} diff --git a/backend/internal/handler/grok_media.go b/backend/internal/handler/grok_media.go index 03dabf7520..db4b4c3f3b 100644 --- a/backend/internal/handler/grok_media.go +++ b/backend/internal/handler/grok_media.go @@ -90,6 +90,9 @@ func (h *OpenAIGatewayHandler) handleGrokMedia(c *gin.Context, endpoint service. if endpoint.RequiresRequestBody() { body, err = pkghttputil.ReadRequestBodyWithPrealloc(c.Request) if err != nil { + if handleRequestBodyReadError(c, err) { + return + } if maxErr, ok := extractMaxBytesError(err); ok { h.errorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) return @@ -757,6 +760,7 @@ func recordGrokMediaUsage( payloadForHash = []byte(videoTaskID) } } + requestPayloadHash := service.HashUsageRequestPayload(payloadForHash) h.submitOpenAIUsageRecordTask(c.Request.Context(), result, func(ctx context.Context) { if err := h.gatewayService.RecordUsage(ctx, &service.OpenAIRecordUsageInput{ Result: result, @@ -768,7 +772,7 @@ func recordGrokMediaUsage( UpstreamEndpoint: upstreamEndpoint, UserAgent: userAgent, IPAddress: clientIP, - RequestPayloadHash: service.HashUsageRequestPayload(payloadForHash), + RequestPayloadHash: requestPayloadHash, APIKeyService: h.apiKeyService, QuotaPlatform: quotaPlatform, SessionID: sessionID, diff --git a/backend/internal/handler/image_task_handler.go b/backend/internal/handler/image_task_handler.go index f9b28668ae..deff4b7a2b 100644 --- a/backend/internal/handler/image_task_handler.go +++ b/backend/internal/handler/image_task_handler.go @@ -77,6 +77,9 @@ func (h *AsyncImageHandler) Submit(c *gin.Context) { body, err := pkghttputil.ReadRequestBodyWithPrealloc(c.Request) if err != nil { + if handleRequestBodyReadError(c, err) { + return + } if maxErr, ok := extractMaxBytesError(err); ok { imageTaskJSONError(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) return diff --git a/backend/internal/handler/openai_alpha_search.go b/backend/internal/handler/openai_alpha_search.go index 3c25b66a08..dd93c44581 100644 --- a/backend/internal/handler/openai_alpha_search.go +++ b/backend/internal/handler/openai_alpha_search.go @@ -52,6 +52,9 @@ func (h *OpenAIGatewayHandler) AlphaSearch(c *gin.Context) { body, err := pkghttputil.ReadRequestBodyWithPrealloc(c.Request) if err != nil { + if handleRequestBodyReadError(c, err) { + return + } if maxErr, ok := extractMaxBytesError(err); ok { h.errorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) return @@ -293,6 +296,7 @@ func (h *OpenAIGatewayHandler) recordAlphaSearchUsage( inboundEndpoint := GetInboundEndpoint(c) upstreamEndpoint := GetUpstreamEndpoint(c, account.Platform) quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) + pricingAt := service.OpenAIPricingAtFromContext(c.Request.Context()) h.submitMandatoryUsageRecordTask(c.Request.Context(), func(ctx context.Context) { if err := h.gatewayService.RecordUsage(ctx, &service.OpenAIRecordUsageInput{ @@ -310,7 +314,7 @@ func (h *OpenAIGatewayHandler) recordAlphaSearchUsage( QuotaPlatform: quotaPlatform, SessionID: sessionID, ChannelUsageFields: channelMapping.ToUsageFields(requestedModel, result.UpstreamModel), - PricingAt: service.OpenAIPricingAtFromContext(c.Request.Context()), + 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 0a371f12eb..d6bec93e98 100644 --- a/backend/internal/handler/openai_chat_completions.go +++ b/backend/internal/handler/openai_chat_completions.go @@ -51,6 +51,9 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) { body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg) if err != nil { + if handleRequestBodyReadError(c, err) { + return + } if maxErr, ok := extractMaxBytesError(err); ok { h.errorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) return @@ -292,6 +295,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, @@ -306,7 +310,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_embeddings.go b/backend/internal/handler/openai_embeddings.go index 6c900c482e..dbcd7c9979 100644 --- a/backend/internal/handler/openai_embeddings.go +++ b/backend/internal/handler/openai_embeddings.go @@ -48,6 +48,9 @@ func (h *OpenAIGatewayHandler) Embeddings(c *gin.Context) { body, err := pkghttputil.ReadRequestBodyWithPrealloc(c.Request) if err != nil { + if handleRequestBodyReadError(c, err) { + return + } if maxErr, ok := extractMaxBytesError(err); ok { h.errorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) return @@ -271,6 +274,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, @@ -285,7 +289,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_count_tokens.go b/backend/internal/handler/openai_gateway_count_tokens.go index 2df4f4f2d0..050a5057bd 100644 --- a/backend/internal/handler/openai_gateway_count_tokens.go +++ b/backend/internal/handler/openai_gateway_count_tokens.go @@ -42,6 +42,9 @@ func (h *OpenAIGatewayHandler) ResponsesInputTokens(c *gin.Context) { body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg) if err != nil { + if handleRequestBodyReadError(c, err) { + return + } if maxErr, ok := extractMaxBytesError(err); ok { h.errorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) return @@ -135,6 +138,9 @@ func (h *OpenAIGatewayHandler) ResponsesInputTokens(c *gin.Context) { func (h *OpenAIGatewayHandler) GrokCountTokens(c *gin.Context) { body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg) if err != nil { + if handleRequestBodyReadError(c, err) { + return + } if maxErr, ok := extractMaxBytesError(err); ok { h.anthropicErrorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) return @@ -205,6 +211,9 @@ func (h *OpenAIGatewayHandler) CountTokens(c *gin.Context) { body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg) if err != nil { + if handleRequestBodyReadError(c, err) { + return + } if maxErr, ok := extractMaxBytesError(err); ok { h.anthropicErrorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) return diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 02c61704ab..4ce98398cd 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -270,9 +270,10 @@ func wrapUsageRecordTaskContext(parent context.Context, task service.UsageRecord if parent != nil { done = service.InflightReservationFromContext(parent).Acquire() } + requestContext := usageRecordContext(parent, context.Background()) return func(ctx context.Context) { defer done() - task(usageRecordContext(parent, ctx)) + task(usageRecordContext(requestContext, ctx)) }, done } @@ -422,6 +423,9 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { // Read request body body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg) if err != nil { + if handleRequestBodyReadError(c, err) { + return + } if maxErr, ok := extractMaxBytesError(err); ok { h.errorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) return @@ -840,6 +844,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, @@ -855,7 +860,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, @@ -1201,6 +1206,9 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg) if err != nil { + if handleRequestBodyReadError(c, err) { + return + } if maxErr, ok := extractMaxBytesError(err); ok { h.anthropicErrorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) return @@ -1434,6 +1442,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, @@ -1449,7 +1458,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 { diff --git a/backend/internal/handler/openai_images.go b/backend/internal/handler/openai_images.go index 95ccbd9a73..a8e6413e7b 100644 --- a/backend/internal/handler/openai_images.go +++ b/backend/internal/handler/openai_images.go @@ -50,6 +50,9 @@ func (h *OpenAIGatewayHandler) Images(c *gin.Context) { body, err := pkghttputil.ReadRequestBodyWithPrealloc(c.Request) if err != nil { + if handleRequestBodyReadError(c, err) { + return + } if maxErr, ok := extractMaxBytesError(err); ok { h.errorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) return @@ -409,6 +412,7 @@ func (h *OpenAIGatewayHandler) Images(c *gin.Context) { upstreamModel = result.UpstreamModel } sessionID := service.ExtractClientSessionID(c) + channelUsageFields := clientRequestedUsageFields(c, channelMapping, requestModel, upstreamModel) h.submitMandatoryUsageRecordTask(c.Request.Context(), func(ctx context.Context) { if err := h.gatewayService.RecordUsage(ctx, &service.OpenAIRecordUsageInput{ Result: result, @@ -424,7 +428,7 @@ func (h *OpenAIGatewayHandler) Images(c *gin.Context) { APIKeyService: h.apiKeyService, QuotaPlatform: quotaPlatform, SessionID: sessionID, - ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, requestModel, upstreamModel), + ChannelUsageFields: channelUsageFields, }); err != nil { logger.L().With( zap.String("component", "handler.openai_gateway.images"), diff --git a/backend/internal/handler/request_body_limit.go b/backend/internal/handler/request_body_limit.go index de24551ba9..4fd1aa13b9 100644 --- a/backend/internal/handler/request_body_limit.go +++ b/backend/internal/handler/request_body_limit.go @@ -7,8 +7,20 @@ import ( "github.com/Wei-Shaw/sub2api/internal/config" pkghttputil "github.com/Wei-Shaw/sub2api/internal/pkg/httputil" + middleware2 "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/gin-gonic/gin" ) +// handleRequestBodyReadError handles cancellation and temporary capacity errors +// before callers classify malformed or oversized request bodies. +func handleRequestBodyReadError(c *gin.Context, err error) bool { + if err != nil && failoverClientGone(c) { + c.Abort() + return true + } + return middleware2.RejectRequestBodyMemoryOverload(c, err) +} + func extractMaxBytesError(err error) (*http.MaxBytesError, bool) { var maxErr *http.MaxBytesError if errors.As(err, &maxErr) { diff --git a/backend/internal/handler/request_body_limit_test.go b/backend/internal/handler/request_body_limit_test.go index bd9b817797..826657cd1a 100644 --- a/backend/internal/handler/request_body_limit_test.go +++ b/backend/internal/handler/request_body_limit_test.go @@ -2,6 +2,7 @@ package handler import ( "bytes" + "context" "io" "net/http" "net/http/httptest" @@ -43,3 +44,39 @@ func TestRequestBodyLimitTooLarge(t *testing.T) { require.Equal(t, http.StatusRequestEntityTooLarge, recorder.Code) require.Contains(t, recorder.Body.String(), buildBodyTooLargeMessage(limit)) } + +func TestHandleRequestBodyReadErrorCancellation(t *testing.T) { + for _, tc := range []struct { + name string + cancelled bool + committed bool + }{ + {name: "cancelled", cancelled: true}, + {name: "cancelled_after_commit", cancelled: true, committed: true}, + {name: "ordinary_read_error"}, + } { + t.Run(tc.name, func(t *testing.T) { + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + if tc.cancelled { + cancel() + } + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil).WithContext(ctx) + if tc.committed { + _, err := c.Writer.WriteString("already committed") + require.NoError(t, err) + } + bodyBefore := recorder.Body.String() + require.Equal(t, tc.cancelled, handleRequestBodyReadError(c, io.ErrUnexpectedEOF)) + require.Equal(t, tc.cancelled, c.IsAborted()) + status := http.StatusOK + if tc.cancelled && !tc.committed { + status = statusClientClosedRequest + } + require.Equal(t, status, c.Writer.Status()) + require.Equal(t, bodyBefore, recorder.Body.String(), "cancelled clients must not receive an error body") + }) + } +} diff --git a/backend/internal/handler/usage_record_async_boundary_test.go b/backend/internal/handler/usage_record_async_boundary_test.go new file mode 100644 index 0000000000..9cf2ca12de --- /dev/null +++ b/backend/internal/handler/usage_record_async_boundary_test.go @@ -0,0 +1,85 @@ +package handler + +import ( + "go/ast" + "go/parser" + "go/token" + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +// Gin contexts belong to their request. Enforce the async boundary across all +// usage entry points, including rarely exercised provider and auxiliary routes. +func TestUsageRecordTasksDoNotCaptureGinContext(t *testing.T) { + _, filename, _, ok := runtime.Caller(0) + require.True(t, ok) + paths, err := filepath.Glob(filepath.Join(filepath.Dir(filename), "*.go")) + require.NoError(t, err) + files := token.NewFileSet() + for _, path := range paths { + if strings.HasSuffix(path, "_test.go") { + continue + } + file, err := parser.ParseFile(files, path, nil, parser.SkipObjectResolution) + require.NoError(t, err) + for _, declaration := range file.Decls { + function, ok := declaration.(*ast.FuncDecl) + if !ok || function.Body == nil { + continue + } + contexts := make(map[string]bool) + for _, param := range function.Type.Params.List { + pointer, ok := param.Type.(*ast.StarExpr) + if !ok { + continue + } + typeName, ok := pointer.X.(*ast.SelectorExpr) + if !ok || typeName.Sel.Name != "Context" { + continue + } + pkg, ok := typeName.X.(*ast.Ident) + if !ok || pkg.Name != "gin" { + continue + } + for _, name := range param.Names { + contexts[name.Name] = true + } + } + if len(contexts) == 0 { + continue + } + ast.Inspect(function.Body, func(node ast.Node) bool { + call, ok := node.(*ast.CallExpr) + if !ok { + return true + } + method, ok := call.Fun.(*ast.SelectorExpr) + if !ok { + return true + } + switch method.Sel.Name { + case "submitUsageRecordTask", "submitMandatoryUsageRecordTask", "submitOpenAIUsageRecordTask": + default: + return true + } + for _, arg := range call.Args { + task, ok := arg.(*ast.FuncLit) + if !ok { + continue + } + ast.Inspect(task.Body, func(node ast.Node) bool { + if name, ok := node.(*ast.Ident); ok && contexts[name.Name] { + t.Errorf("%s: usage task captures gin.Context %q; snapshot required fields before submitting", files.Position(name.Pos()), name.Name) + } + return true + }) + } + return true + }) + } + } +} diff --git a/backend/internal/handler/usage_record_context_reuse_test.go b/backend/internal/handler/usage_record_context_reuse_test.go new file mode 100644 index 0000000000..779fff2c6b --- /dev/null +++ b/backend/internal/handler/usage_record_context_reuse_test.go @@ -0,0 +1,105 @@ +//go:build unit + +package handler + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" + "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" +) + +// Exercise the actual forwarding handlers with their usage worker blocked. The +// same Gin context then handles another request before the queued charge runs. +// HandleContext makes that reuse deterministic, including under -race (where +// sync.Pool is allowed to randomly discard entries). +func TestGatewayUsageKeepsModelAfterGinContextReuse(t *testing.T) { + for _, endpoint := range []string{"chat/completions", "responses"} { + t.Run(endpoint, func(t *testing.T) { + cfg := &config.Config{} + groupID := int64(9300) + group := &service.Group{ID: groupID, Hydrated: true, Platform: service.PlatformAnthropic, Status: service.StatusActive, RateMultiplier: 1} + account := &service.Account{ + ID: 9301, Platform: service.PlatformAnthropic, Type: service.AccountTypeAPIKey, + Status: service.StatusActive, Schedulable: true, Concurrency: 1, + Credentials: map[string]any{"api_key": "test-key"}, + AccountGroups: []service.AccountGroup{{AccountID: 9301, GroupID: groupID}}, + } + snapshot := service.NewSchedulerSnapshotService(&fakeSchedulerCache{accounts: []*service.Account{account}}, nil, nil, nil, nil) + usageRepo := &openAIWSUsageHandlerUsageLogRepoStub{created: make(chan *service.UsageLog, 1)} + billingRepo := &compatStreamUsageBillingRepo{} + billingCache := service.NewBillingCacheService(newHandlerInflightCache(100), nil, nil, nil, nil, nil, cfg, nil) + t.Cleanup(billingCache.Stop) + upstream := &compatStreamUsageUpstream{response: &http.Response{ + StatusCode: http.StatusOK, + Body: io.NopCloser(strings.NewReader(compatStreamUsagePartialStream + compatStreamUsageCompletion)), + Header: http.Header{"X-Request-Id": []string{"usage-context-reuse"}}, + }} + gw := service.NewGatewayService( + nil, &fakeGroupRepo{group: group}, usageRepo, billingRepo, nil, nil, nil, nil, cfg, + snapshot, nil, service.NewBillingService(cfg, nil), nil, nil, nil, upstream, + &service.DeferredService{}, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, + ) + pool := newUsageRecordTestPool(t) + blocked, release := make(chan struct{}), make(chan struct{}) + var releaseOnce sync.Once + unblock := func() { releaseOnce.Do(func() { close(release) }) } + t.Cleanup(unblock) + pool.Submit(func(context.Context) { close(blocked); <-release }) + <-blocked + h := &GatewayHandler{ + gatewayService: gw, billingCacheService: billingCache, cfg: cfg, maxAccountSwitches: 1, + usageRecordWorkerPool: pool, + concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(&fakeConcurrencyCache{}), SSEPingFormatClaude, 0), + } + apiKey := &service.APIKey{ID: 9302, UserID: 9303, GroupID: &groupID, Group: group, User: &service.User{ID: 9303, Balance: 100}} + var first *gin.Context + router := gin.New() + router.POST("/v1/"+endpoint, func(c *gin.Context) { + first = c + c.Request = c.Request.WithContext(context.WithValue(c.Request.Context(), ctxkey.RequestedPublicModel, "public-model-A")) + c.Set(string(middleware.ContextKeyAPIKey), apiKey) + c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 9303}) + if endpoint == "chat/completions" { + h.ChatCompletions(c) + } else { + h.Responses(c) + } + }) + router.GET("/next", func(c *gin.Context) { + c.Request = c.Request.WithContext(context.WithValue(c.Request.Context(), ctxkey.RequestedPublicModel, "public-model-B")) + }) + body := `{"model":"claude-sonnet-4.5","stream":true,"input":"hello"}` + if endpoint == "chat/completions" { + body = `{"model":"claude-sonnet-4.5","stream":true,"messages":[{"role":"user","content":"hello"}]}` + } + req := httptest.NewRequest(http.MethodPost, "/v1/"+endpoint, strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + recorder := httptest.NewRecorder() + router.ServeHTTP(recorder, req) + require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String()) + require.Equal(t, uint64(1), pool.Stats().WaitingTasks) + + first.Request = httptest.NewRequest(http.MethodGet, "/next", nil) + router.HandleContext(first) + unblock() + select { + case usage := <-usageRepo.created: + require.Equal(t, "public-model-A", usage.RequestedModel) + case <-time.After(2 * time.Second): + t.Fatal("queued request usage was not recorded") + } + }) + } +} diff --git a/backend/internal/pkg/apicompat/anthropic_to_responses_response.go b/backend/internal/pkg/apicompat/anthropic_to_responses_response.go index 2e7c85d3c9..e29bcdeaf9 100644 --- a/backend/internal/pkg/apicompat/anthropic_to_responses_response.go +++ b/backend/internal/pkg/apicompat/anthropic_to_responses_response.go @@ -198,6 +198,10 @@ type AnthropicEventToResponsesState struct { CurrentSummary string // reasoning CurrentThinking AnthropicContentBlock PreserveThinkingSignatures bool + textAccumBuffer *strings.Builder + currentArgsBuffer *strings.Builder + currentSummaryBuffer *strings.Builder + currentSignatureBuffer *strings.Builder // PendingToolInput holds tool arguments that arrived complete on // content_block_start instead of as input_json_delta. It is only consumed at @@ -332,6 +336,8 @@ func anthToResHandleContentBlockStart(evt *AnthropicStreamEvent, state *Anthropi state.CurrentItemType = "reasoning" state.CurrentThinking = *evt.ContentBlock state.CurrentSummary = evt.ContentBlock.Thinking + state.currentSummaryBuffer = nil + state.currentSignatureBuffer = nil state.ContentIndex = 0 events = append(events, makeResponsesEvent(state, "response.output_item.added", &ResponsesStreamEvent{ @@ -380,6 +386,7 @@ func anthToResHandleContentBlockStart(evt *AnthropicStreamEvent, state *Anthropi Part: &ResponsesContentPart{Type: "output_text", Text: ""}, })) state.TextAccum = "" + state.textAccumBuffer = nil case "tool_use": // Close previous item if any @@ -421,7 +428,7 @@ func anthToResHandleContentBlockDelta(evt *AnthropicStreamEvent, state *Anthropi if evt.Delta.Text == "" { return nil } - state.TextAccum += evt.Delta.Text + state.TextAccum = appendStreamString(&state.textAccumBuffer, state.TextAccum, evt.Delta.Text) return []ResponsesStreamEvent{makeResponsesEvent(state, "response.output_text.delta", &ResponsesStreamEvent{ OutputIndex: state.OutputIndex, ContentIndex: state.ContentIndex, @@ -433,7 +440,7 @@ func anthToResHandleContentBlockDelta(evt *AnthropicStreamEvent, state *Anthropi if evt.Delta.Thinking == "" { return nil } - state.CurrentSummary += evt.Delta.Thinking + state.CurrentSummary = appendStreamString(&state.currentSummaryBuffer, state.CurrentSummary, evt.Delta.Thinking) return []ResponsesStreamEvent{makeResponsesEvent(state, "response.reasoning_summary_text.delta", &ResponsesStreamEvent{ OutputIndex: state.OutputIndex, SummaryIndex: 0, @@ -448,7 +455,7 @@ func anthToResHandleContentBlockDelta(evt *AnthropicStreamEvent, state *Anthropi // A real delta supersedes whatever content_block_start carried; keeping // both would splice two complete JSON documents together. state.PendingToolInput = "" - state.CurrentArgs += evt.Delta.PartialJSON + state.CurrentArgs = appendStreamString(&state.currentArgsBuffer, state.CurrentArgs, evt.Delta.PartialJSON) return []ResponsesStreamEvent{makeResponsesEvent(state, "response.function_call_arguments.delta", &ResponsesStreamEvent{ OutputIndex: state.OutputIndex, Delta: evt.Delta.PartialJSON, @@ -460,7 +467,7 @@ func anthToResHandleContentBlockDelta(evt *AnthropicStreamEvent, state *Anthropi case "signature_delta": // Keep signatures in the opaque bridge envelope, never in visible text. if state.PreserveThinkingSignatures { - state.CurrentThinking.Signature += evt.Delta.Signature + state.CurrentThinking.Signature = appendStreamString(&state.currentSignatureBuffer, state.CurrentThinking.Signature, evt.Delta.Signature) } return nil } @@ -489,6 +496,7 @@ func anthToResHandleContentBlockStop(evt *AnthropicStreamEvent, state *Anthropic // the done event below still repeats exactly what the deltas streamed. if state.CurrentArgs == "" && state.PendingToolInput != "" { state.CurrentArgs = state.PendingToolInput + state.currentArgsBuffer = nil events = append(events, makeResponsesEvent(state, "response.function_call_arguments.delta", &ResponsesStreamEvent{ OutputIndex: state.OutputIndex, Delta: state.PendingToolInput, @@ -521,6 +529,7 @@ func anthToResHandleContentBlockStop(evt *AnthropicStreamEvent, state *Anthropic // item itself stays open since more blocks may follow. text := state.TextAccum state.TextAccum = "" + state.textAccumBuffer = nil contentIndex := state.ContentIndex state.CurrentContent = append(state.CurrentContent, ResponsesContentPart{Type: "output_text", Text: text}) // 关掉一个 part 就推进 content_index:上面那句注释说的「item 保持打开, @@ -648,10 +657,14 @@ func closeCurrentResponsesItem(state *AnthropicEventToResponsesState) []Response state.CurrentName = "" state.CurrentContent = nil state.CurrentArgs = "" + state.currentArgsBuffer = nil state.PendingToolInput = "" state.CurrentSummary = "" + state.currentSummaryBuffer = nil state.CurrentThinking = AnthropicContentBlock{} + state.currentSignatureBuffer = nil state.TextAccum = "" + state.textAccumBuffer = nil state.OutputIndex++ state.ContentIndex = 0 diff --git a/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge.go b/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge.go index 20a590c1c6..29b5bbbe17 100644 --- a/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge.go +++ b/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge.go @@ -577,7 +577,7 @@ type ChatCompletionsToAnthropicStreamState struct { toolAnnounced map[int]bool toolName map[int]string pendingToolCallID map[int]string - pendingToolArgs map[int]string + pendingToolArgs map[int]*strings.Builder // Reasoning (DeepSeek-style): reasoning_content streamed before content. // No separate reasoning block index — it uses ContentBlockIndex like the @@ -606,7 +606,7 @@ func NewChatCompletionsToAnthropicStreamState(model string) *ChatCompletionsToAn toolAnnounced: make(map[int]bool), toolName: make(map[int]string), pendingToolCallID: make(map[int]string), - pendingToolArgs: make(map[int]string), + pendingToolArgs: make(map[int]*strings.Builder), } } @@ -841,7 +841,12 @@ func handleCCAnthropicToolCall(state *ChatCompletionsToAnthropicStreamState, too }, }) } else { - state.pendingToolArgs[idx] += toolCall.Function.Arguments + buffer := state.pendingToolArgs[idx] + if buffer == nil { + buffer = &strings.Builder{} + state.pendingToolArgs[idx] = buffer + } + _, _ = buffer.WriteString(toolCall.Function.Arguments) } } @@ -872,7 +877,8 @@ func announceCCAnthropicToolBlock(state *ChatCompletionsToAnthropicStreamState, Input: json.RawMessage("{}"), }, }} - if pending := state.pendingToolArgs[idx]; pending != "" { + if buffer := state.pendingToolArgs[idx]; buffer != nil && buffer.Len() > 0 { + pending := buffer.String() delete(state.pendingToolArgs, idx) state.CurrentToolHadDelta = true events = append(events, AnthropicStreamEvent{ diff --git a/backend/internal/pkg/apicompat/chatcompletions_responses_bridge.go b/backend/internal/pkg/apicompat/chatcompletions_responses_bridge.go index f56f78066c..ac7472e778 100644 --- a/backend/internal/pkg/apicompat/chatcompletions_responses_bridge.go +++ b/backend/internal/pkg/apicompat/chatcompletions_responses_bridge.go @@ -1594,9 +1594,10 @@ type ChatCompletionsToResponsesStreamState struct { Reasoning strings.Builder // Tool-call lifecycle, keyed by the upstream tool_call index. - ToolCalls map[int]*ChatToolCall - ToolItemIDs map[int]string - ToolOutputIndex map[int]int + ToolCalls map[int]*ChatToolCall + ToolItemIDs map[int]string + ToolOutputIndex map[int]int + toolArgumentBuffers map[int]*strings.Builder // CustomTools 是客户端请求中 custom/freeform 工具的名字集合(见 // CustomToolNames)。命中的调用按 custom_tool_call 生命周期下发,codex 才能 @@ -1756,7 +1757,7 @@ func ChatCompletionsChunkToResponsesEvents( // emitted delta and the stored value stay in sync. Some upstreams // (e.g. GLM/Zhipu) pack id+name+arguments into the first tool_call // chunk; without this reset the first chunk's arguments would be - // counted twice (once from this copy, once from the += below), + // counted twice (once from this copy, once from the append below), // producing a doubled, invalid JSON like {"a":1}{"a":1}. copyCall.Function.Arguments = "" state.ToolCalls[idx] = ©Call @@ -1773,7 +1774,7 @@ func ChatCompletionsChunkToResponsesEvents( } events = append(events, announceChatToolItem(state, idx, stored, false)...) if toolCall.Function.Arguments != "" { - stored.Function.Arguments += toolCall.Function.Arguments + stored.Function.Arguments = appendIndexedStreamString(&state.toolArgumentBuffers, idx, stored.Function.Arguments, toolCall.Function.Arguments) // 未宣告(名字未到)时仅累积,宣告时统一补发;custom 调用的 // arguments 是包裹 input 的 JSON 片段,无法增量还原为自由文本 // 输入,缓冲整份 arguments 收尾时一次性下发(见 closeChatToolItems); diff --git a/backend/internal/pkg/apicompat/responses_to_anthropic.go b/backend/internal/pkg/apicompat/responses_to_anthropic.go index 424affde73..976d01de8b 100644 --- a/backend/internal/pkg/apicompat/responses_to_anthropic.go +++ b/backend/internal/pkg/apicompat/responses_to_anthropic.go @@ -182,12 +182,14 @@ type ResponsesEventToAnthropicState struct { MessageStartSent bool MessageStopSent bool - ContentBlockIndex int - ContentBlockOpen bool - CurrentBlockType string // "text" | "thinking" | "tool_use" - CurrentToolName string - CurrentToolArgs string - CurrentToolHadDelta bool + ContentBlockIndex int + ContentBlockOpen bool + CurrentBlockType string // "text" | "thinking" | "tool_use" + CurrentToolName string + CurrentToolArgs string + CurrentToolHadDelta bool + currentToolArgsBuffer *strings.Builder + currentToolArgsValidation *streamStringBytes // PendingThinkingSignature is filled from reasoning.encrypted_content and // emitted as signature_delta before the thinking block is closed. PendingThinkingSignature string @@ -361,6 +363,8 @@ func resToAnthHandleOutputItemAdded(evt *ResponsesStreamEvent, state *ResponsesE state.CurrentBlockType = "tool_use" state.CurrentToolName = evt.Item.Name state.CurrentToolArgs = "" + state.currentToolArgsBuffer = nil + state.currentToolArgsValidation = nil state.CurrentToolHadDelta = false state.HasToolCall = true @@ -501,8 +505,9 @@ func resToAnthHandleFuncArgsDelta(evt *ResponsesStreamEvent, state *ResponsesEve } if state.CurrentBlockType == "tool_use" && state.CurrentToolName == "Read" { - state.CurrentToolArgs += evt.Delta - if state.CurrentToolHadDelta || !json.Valid([]byte(state.CurrentToolArgs)) { + previousArgs := state.CurrentToolArgs + state.CurrentToolArgs = appendStreamString(&state.currentToolArgsBuffer, state.CurrentToolArgs, evt.Delta) + if state.CurrentToolHadDelta || !json.Valid(appendStreamStringBytes(&state.currentToolArgsValidation, previousArgs, state.CurrentToolArgs, evt.Delta)) { return nil } @@ -805,6 +810,8 @@ func closeCurrentBlock(state *ResponsesEventToAnthropicState) []AnthropicStreamE state.ContentBlockIndex++ state.CurrentToolName = "" state.CurrentToolArgs = "" + state.currentToolArgsBuffer = nil + state.currentToolArgsValidation = nil state.CurrentToolHadDelta = false events = append(events, AnthropicStreamEvent{ Type: "content_block_stop", diff --git a/backend/internal/pkg/apicompat/responses_to_chatcompletions.go b/backend/internal/pkg/apicompat/responses_to_chatcompletions.go index 2b8f2b8117..0c9afd8ead 100644 --- a/backend/internal/pkg/apicompat/responses_to_chatcompletions.go +++ b/backend/internal/pkg/apicompat/responses_to_chatcompletions.go @@ -132,6 +132,7 @@ type ResponsesEventToChatState struct { NextToolCallIndex int // next sequential tool_call index to assign OutputIndexToToolIndex map[int]int // Responses output_index → Chat tool_calls index OutputIndexToArguments map[int]string + argumentBuffers map[int]*strings.Builder IncludeUsage bool Usage *ChatUsage } @@ -296,7 +297,7 @@ func resToChatHandleFuncArgsDelta(evt *ResponsesStreamEvent, state *ResponsesEve if !ok { return nil } - state.OutputIndexToArguments[evt.OutputIndex] += evt.Delta + state.OutputIndexToArguments[evt.OutputIndex] = appendIndexedStreamString(&state.argumentBuffers, evt.OutputIndex, state.OutputIndexToArguments[evt.OutputIndex], evt.Delta) return []ChatCompletionsChunk{makeChatDeltaChunk(state, ChatDelta{ ToolCalls: []ChatToolCall{{ @@ -325,6 +326,7 @@ func resToChatHandleFuncArgsDone(evt *ResponsesStreamEvent, state *ResponsesEven remainder := completed[len(current):] state.OutputIndexToArguments[evt.OutputIndex] = completed + delete(state.argumentBuffers, evt.OutputIndex) return []ChatCompletionsChunk{makeChatDeltaChunk(state, ChatDelta{ ToolCalls: []ChatToolCall{{ Index: &idx, diff --git a/backend/internal/pkg/apicompat/stream_accumulation_memory_test.go b/backend/internal/pkg/apicompat/stream_accumulation_memory_test.go new file mode 100644 index 0000000000..f6a8ea2e53 --- /dev/null +++ b/backend/internal/pkg/apicompat/stream_accumulation_memory_test.go @@ -0,0 +1,356 @@ +package apicompat + +import ( + "fmt" + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +type streamAccumulationFieldCase struct { + name string + blockType string + field func(*AnthropicEventToResponsesState) *string + delta func(string) *AnthropicDelta +} + +func streamAccumulationFieldCases() []streamAccumulationFieldCase { + return []streamAccumulationFieldCase{ + {"text", "text", func(s *AnthropicEventToResponsesState) *string { return &s.TextAccum }, func(v string) *AnthropicDelta { return &AnthropicDelta{Type: "text_delta", Text: v} }}, + {"thinking", "thinking", func(s *AnthropicEventToResponsesState) *string { return &s.CurrentSummary }, func(v string) *AnthropicDelta { return &AnthropicDelta{Type: "thinking_delta", Thinking: v} }}, + {"arguments", "tool_use", func(s *AnthropicEventToResponsesState) *string { return &s.CurrentArgs }, func(v string) *AnthropicDelta { return &AnthropicDelta{Type: "input_json_delta", PartialJSON: v} }}, + {"signature", "thinking", func(s *AnthropicEventToResponsesState) *string { return &s.CurrentThinking.Signature }, func(v string) *AnthropicDelta { return &AnthropicDelta{Type: "signature_delta", Signature: v} }}, + } +} + +func TestStreamAccumulationAnthropicPublicStringsAndReset(t *testing.T) { + for _, tc := range streamAccumulationFieldCases() { + t.Run(tc.name, func(t *testing.T) { + state := NewAnthropicEventToResponsesState() + state.PreserveThinkingSignatures = true + block := &AnthropicContentBlock{Type: tc.blockType, ID: "call_seed", Name: "tool"} + if tc.name == "thinking" { + block.Thinking = "seed-" + } + if tc.name == "signature" { + block.Signature = "seed-" + } + AnthropicEventToResponsesEvents(&AnthropicStreamEvent{Type: "content_block_start", ContentBlock: block}, state) + if tc.name == "thinking" || tc.name == "signature" { + require.Equal(t, "seed-", *tc.field(state), "content block seeds remain visible") + } else { + *tc.field(state) = "seed-" + } + appendDelta := func(value string) { + AnthropicEventToResponsesEvents(&AnthropicStreamEvent{Type: "content_block_delta", Delta: tc.delta(value)}, state) + } + + appendDelta("one") + require.Equal(t, "seed-one", *tc.field(state)) + firstSnapshot := *tc.field(state) + appendDelta("-two") + require.Equal(t, "seed-one-two", *tc.field(state)) + require.Equal(t, "seed-one", firstSnapshot, "later deltas must not mutate borrowed strings") + secondSnapshot := *tc.field(state) + + // An external assignment with the same length must replace the old + // accumulator, not be mistaken for a synchronized public field. + replacement := strings.Repeat("r", len(secondSnapshot)) + *tc.field(state) = replacement + appendDelta("!") + require.Equal(t, replacement+"!", *tc.field(state)) + require.Equal(t, "seed-one-two", secondSnapshot) + + *tc.field(state) = "" + appendDelta("after-reset") + require.Equal(t, "after-reset", *tc.field(state)) + closedSnapshot := *tc.field(state) + closedEvents := AnthropicEventToResponsesEvents(&AnthropicStreamEvent{Type: "content_block_stop"}, state) + require.Empty(t, *tc.field(state)) + + AnthropicEventToResponsesEvents(&AnthropicStreamEvent{Type: "content_block_start", ContentBlock: &AnthropicContentBlock{Type: tc.blockType, ID: "call_next", Name: "tool"}}, state) + appendDelta(strings.Repeat("next", 128)) + require.Equal(t, strings.Repeat("next", 128), *tc.field(state), "a new block must not reuse the previous prefix") + require.Equal(t, "after-reset", closedSnapshot) + require.Equal(t, "seed-one", firstSnapshot) + if tc.name == "text" { + require.Len(t, closedEvents, 2) + require.Equal(t, "after-reset", closedEvents[0].Text) + require.Equal(t, "after-reset", closedEvents[1].Part.Text) + } + }) + } +} + +func TestStreamAccumulationAnthropicCopiedStateBranches(t *testing.T) { + for _, tc := range streamAccumulationFieldCases() { + t.Run(tc.name, func(t *testing.T) { + original := NewAnthropicEventToResponsesState() + original.PreserveThinkingSignatures = true + appendDelta := func(state *AnthropicEventToResponsesState, value string) { + AnthropicEventToResponsesEvents(&AnthropicStreamEvent{Type: "content_block_delta", Delta: tc.delta(value)}, state) + } + appendDelta(original, "base") + baseSnapshot := *tc.field(original) + copied := *original + + // Sequential copies historically had independent string values. + // This does not promise concurrent mutation of shared state is safe. + appendDelta(original, "/left") + appendDelta(&copied, "/right") + require.Equal(t, "base/left", *tc.field(original)) + require.Equal(t, "base/right", *tc.field(&copied)) + appendDelta(original, "/again") + require.Equal(t, "base/left/again", *tc.field(original)) + require.Equal(t, "base/right", *tc.field(&copied)) + require.Equal(t, "base", baseSnapshot) + }) + } +} + +func TestStreamAccumulationResponsesChatToolIsolation(t *testing.T) { + state := NewResponsesEventToChatState() + for _, idx := range []int{2, 7} { + ResponsesEventToChatChunks(&ResponsesStreamEvent{Type: "response.output_item.added", OutputIndex: idx, Item: &ResponsesOutput{Type: "function_call", CallID: fmt.Sprintf("call_%d", idx), Name: "tool"}}, state) + } + appendDelta := func(idx int, delta, want string) { + t.Helper() + ResponsesEventToChatChunks(&ResponsesStreamEvent{Type: "response.function_call_arguments.delta", OutputIndex: idx, Delta: delta}, state) + require.Equal(t, want, state.OutputIndexToArguments[idx]) + } + state.OutputIndexToArguments[2] = `{"a":` + appendDelta(2, "1", `{"a":1`) + firstSnapshot := state.OutputIndexToArguments[2] + appendDelta(7, `{"b":`, `{"b":`) + appendDelta(2, "}", `{"a":1}`) + appendDelta(7, "2}", `{"b":2}`) + require.Equal(t, `{"a":1`, firstSnapshot) + require.Equal(t, `{"a":1}`, state.OutputIndexToArguments[2]) + + ResponsesEventToChatChunks(&ResponsesStreamEvent{Type: "response.function_call_arguments.done", OutputIndex: 2, Arguments: `{"a":1} `}, state) + require.Equal(t, `{"a":1} `, state.OutputIndexToArguments[2]) + appendDelta(2, "\n", "{\"a\":1} \n") + state.OutputIndexToArguments[2] = "external" + appendDelta(2, "!", "external!") + delete(state.OutputIndexToArguments, 2) + appendDelta(2, "fresh", "fresh") + require.Equal(t, `{"b":2}`, state.OutputIndexToArguments[7]) +} + +func streamAccumulationChatToolChunk(idx int, name, arguments string) *ChatCompletionsChunk { + return &ChatCompletionsChunk{Choices: []ChatChunkChoice{{Delta: ChatDelta{ToolCalls: []ChatToolCall{{Index: &idx, ID: fmt.Sprintf("call_%d", idx), Type: "function", Function: ChatFunctionCall{Name: name, Arguments: arguments}}}}}}} +} + +func TestStreamAccumulationChatResponsesToolIsolation(t *testing.T) { + state := NewChatCompletionsToResponsesStreamState("model") + appendDelta := func(idx int, name, delta, want string) { + t.Helper() + ChatCompletionsChunkToResponsesEvents(streamAccumulationChatToolChunk(idx, name, delta), state) + require.Equal(t, want, state.ToolCalls[idx].Function.Arguments) + } + appendDelta(0, "first", `{"a":`, `{"a":`) + firstSnapshot := state.ToolCalls[0].Function.Arguments + appendDelta(1, "second", `{"b":`, `{"b":`) + appendDelta(0, "", "1}", `{"a":1}`) + appendDelta(1, "", "2}", `{"b":2}`) + require.Equal(t, `{"a":`, firstSnapshot) + require.Equal(t, `{"a":1}`, state.ToolCalls[0].Function.Arguments) + + state.ToolCalls[0].Function.Arguments = `{"c":3` + appendDelta(0, "", "}", `{"c":3}`) + state.ToolCalls[0].Function.Arguments = "" + appendDelta(0, "", "{}", "{}") + oldCall := state.ToolCalls[0] + delete(state.ToolCalls, 0) + appendDelta(0, "replacement", `{"new":`, `{"new":`) + appendDelta(0, "", "4}", `{"new":4}`) + require.Equal(t, "{}", oldCall.Function.Arguments, "replacing an indexed call must leave the old call immutable") + require.Equal(t, `{"b":2}`, state.ToolCalls[1].Function.Arguments) + require.NoError(t, state.ValidateToolCallArguments()) +} + +func TestStreamAccumulationReadRawArgumentsAndReset(t *testing.T) { + state := NewResponsesEventToAnthropicState() + startTool := func(idx int) { + ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{Type: "response.output_item.added", OutputIndex: idx, Item: &ResponsesOutput{Type: "function_call", CallID: fmt.Sprintf("call_%d", idx), Name: "Read"}}, state) + } + startTool(0) + state.CurrentToolArgs = `{"file_path":"` + ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{Type: "response.function_call_arguments.delta", OutputIndex: 0, Delta: "/tmp/one"}, state) + require.Equal(t, `{"file_path":"/tmp/one`, state.CurrentToolArgs) + require.NotNil(t, state.currentToolArgsValidation) + require.Equal(t, state.CurrentToolArgs, string(state.currentToolArgsValidation.data)) + firstSnapshot := state.CurrentToolArgs + firstValidationSnapshot := state.currentToolArgsValidation.data + // Same-length caller replacement must also be respected by this special + // path, whose externally visible raw JSON differs from sanitized output. + state.CurrentToolArgs = `{"file_path":"/tmp/two` + events := ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{Type: "response.function_call_arguments.delta", OutputIndex: 0, Delta: `","pages":""}`}, state) + require.Len(t, events, 1) + require.JSONEq(t, `{"file_path":"/tmp/two"}`, events[0].Delta.PartialJSON) + require.Equal(t, `{"file_path":"/tmp/two","pages":""}`, state.CurrentToolArgs) + require.Equal(t, state.CurrentToolArgs, string(state.currentToolArgsValidation.data)) + require.Equal(t, firstSnapshot, string(firstValidationSnapshot), "external replacement must not overwrite a borrowed validation prefix") + rawSnapshot := state.CurrentToolArgs + require.Equal(t, `{"file_path":"/tmp/one`, firstSnapshot) + + ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{Type: "response.function_call_arguments.done", OutputIndex: 0}, state) + require.Empty(t, state.CurrentToolArgs) + require.Nil(t, state.currentToolArgsValidation) + startTool(1) + require.Nil(t, state.currentToolArgsValidation) + ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{Type: "response.function_call_arguments.delta", OutputIndex: 1, Delta: `{"file_path":"/tmp/new"}`}, state) + require.Equal(t, `{"file_path":"/tmp/new"}`, state.CurrentToolArgs) + require.Equal(t, state.CurrentToolArgs, string(state.currentToolArgsValidation.data)) + require.Equal(t, `{"file_path":"/tmp/two","pages":""}`, rawSnapshot) + require.JSONEq(t, `{"file_path":"/tmp/two"}`, events[0].Delta.PartialJSON) +} + +func TestStreamAccumulationReadValidationCopiedStateBranches(t *testing.T) { + original := NewResponsesEventToAnthropicState() + ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{Type: "response.output_item.added", OutputIndex: 0, Item: &ResponsesOutput{Type: "function_call", CallID: "call_read", Name: "Read"}}, original) + appendDelta := func(state *ResponsesEventToAnthropicState, value string) { + t.Helper() + events := ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{Type: "response.function_call_arguments.delta", OutputIndex: 0, Delta: value}, state) + require.Empty(t, events, "unfinished strings must not pass the complete-JSON gate") + require.NotNil(t, state.currentToolArgsValidation) + require.Equal(t, state.CurrentToolArgs, string(state.currentToolArgsValidation.data)) + require.Equal(t, state.CurrentToolArgs, state.currentToolArgsValidation.snapshot) + } + original.CurrentToolArgs = `{"file_path":"` + appendDelta(original, "base") + baseSnapshot := original.CurrentToolArgs + baseValidationSnapshot := original.currentToolArgsValidation.data + copied := *original + + appendDelta(original, "/left") + leftValidationSnapshot := original.currentToolArgsValidation.data + appendDelta(&copied, "/right") + require.Equal(t, `{"file_path":"base/left`, original.CurrentToolArgs) + require.Equal(t, original.CurrentToolArgs, string(original.currentToolArgsValidation.data)) + require.Equal(t, `{"file_path":"base/right`, copied.CurrentToolArgs) + appendDelta(original, "/again") + require.Equal(t, `{"file_path":"base/left/again`, original.CurrentToolArgs) + require.Equal(t, `{"file_path":"base/right`, string(copied.currentToolArgsValidation.data)) + require.Equal(t, baseSnapshot, string(baseValidationSnapshot)) + require.Equal(t, `{"file_path":"base/left`, string(leftValidationSnapshot)) + + beforeReset := original.currentToolArgsValidation.data + original.CurrentToolArgs = "" + appendDelta(original, `{"file_path":"reset`) + require.Equal(t, `{"file_path":"reset`, original.CurrentToolArgs) + require.Equal(t, `{"file_path":"base/left/again`, string(beforeReset)) + require.Equal(t, `{"file_path":"base/right`, string(copied.currentToolArgsValidation.data)) +} + +func TestStreamAccumulationReadValidationStopsAfterComplete(t *testing.T) { + state := NewResponsesEventToAnthropicState() + ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{Type: "response.output_item.added", OutputIndex: 0, Item: &ResponsesOutput{Type: "function_call", CallID: "call_read", Name: "Read"}}, state) + const raw = `{"file_path":"/tmp/file","pages":""}` + events := ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{Type: "response.function_call_arguments.delta", OutputIndex: 0, Delta: raw}, state) + require.Len(t, events, 1) + require.True(t, state.CurrentToolHadDelta) + validation := state.currentToolArgsValidation + require.NotNil(t, validation) + require.Equal(t, raw, string(validation.data)) + validationCapacity := cap(validation.data) + + for _, trailing := range []string{" ", strings.Repeat("x", 1024)} { + previous := state.CurrentToolArgs + events := ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{Type: "response.function_call_arguments.delta", OutputIndex: 0, Delta: trailing}, state) + require.Empty(t, events, "a completed Read tool must not emit another sanitized delta") + require.Equal(t, previous+trailing, state.CurrentToolArgs, "the existing public string still accumulates late deltas") + require.Same(t, validation, state.currentToolArgsValidation) + require.Equal(t, raw, string(validation.data)) + require.Equal(t, raw, validation.snapshot) + require.Equal(t, validationCapacity, cap(validation.data)) + } + require.JSONEq(t, `{"file_path":"/tmp/file"}`, events[0].Delta.PartialJSON) + ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{Type: "response.function_call_arguments.done", OutputIndex: 0}, state) + require.Nil(t, state.currentToolArgsValidation) + require.Empty(t, state.CurrentToolArgs) +} + +func TestStreamAccumulationDeferredAnthropicTools(t *testing.T) { + state := NewChatCompletionsToAnthropicStreamState("model") + var events []AnthropicStreamEvent + feed := func(idx int, name, args string) { + events = append(events, ChatCompletionsChunkToAnthropicEvents(streamAccumulationChatToolChunk(idx, name, args), state)...) + } + feed(0, "", `{"a":`) + feed(1, "", `{"b":`) + feed(0, "", "1") + feed(1, "", "2") + feed(0, "first", "}") + feed(1, "second", "}") + events = append(events, FinalizeChatCompletionsAnthropicStream(state)...) + blocks := assembleToolUseBlocks(events) + require.Len(t, blocks, 2) + require.Equal(t, "first", blocks[0].Name) + require.Equal(t, `{"a":1}`, blocks[0].Input) + require.Equal(t, "second", blocks[1].Name) + require.Equal(t, `{"b":2}`, blocks[1].Input) + require.Empty(t, FinalizeChatCompletionsAnthropicStream(state)) +} + +var streamAccumulationBenchmarkSink string + +// ReportAllocs measures cumulative allocation traffic, not retained heap/RSS. +// A fixed 64-byte delta makes total-size scaling expose repeated prefix copies. +func BenchmarkStreamAccumulationAnthropic64ByteDeltas(b *testing.B) { + for _, tc := range streamAccumulationFieldCases() { + for _, size := range []int{32 << 10, 128 << 10, 512 << 10} { + b.Run(fmt.Sprintf("%s/%dKiB", tc.name, size>>10), func(b *testing.B) { + payload := strings.Repeat("x", 64) + event := &AnthropicStreamEvent{Type: "content_block_delta", Delta: tc.delta(payload)} + b.ReportAllocs() + b.SetBytes(int64(size)) + b.ResetTimer() + for i := 0; i < b.N; i++ { + state := NewAnthropicEventToResponsesState() + state.PreserveThinkingSignatures = true + for received := 0; received < size; received += len(payload) { + AnthropicEventToResponsesEvents(event, state) + } + streamAccumulationBenchmarkSink = *tc.field(state) + if len(streamAccumulationBenchmarkSink) != size { + b.Fatalf("accumulated %d bytes, want %d", len(streamAccumulationBenchmarkSink), size) + } + } + }) + } + } +} + +// Read's existing complete-JSON gate inspects the accumulated arguments on +// every delta. Keep the file_path string unfinished to measure that independent +// cost without changing when the converter emits sanitized tool input. +func BenchmarkStreamAccumulationRead64ByteDeltas(b *testing.B) { + for _, size := range []int{32 << 10, 128 << 10, 512 << 10} { + b.Run(fmt.Sprintf("%dKiB", size>>10), func(b *testing.B) { + const prefix = `{"file_path":"` + firstEvent := &ResponsesStreamEvent{Type: "response.function_call_arguments.delta", OutputIndex: 0, Delta: prefix + strings.Repeat("x", 64-len(prefix))} + nextEvent := &ResponsesStreamEvent{Type: "response.function_call_arguments.delta", OutputIndex: 0, Delta: strings.Repeat("x", 64)} + b.ReportAllocs() + b.SetBytes(int64(size)) + b.ResetTimer() + for i := 0; i < b.N; i++ { + state := NewResponsesEventToAnthropicState() + state.MessageStartSent = true + state.ContentBlockOpen = true + state.CurrentBlockType = "tool_use" + state.CurrentToolName = "Read" + state.OutputIndexToBlockIdx[0] = 0 + ResponsesEventToAnthropicEvents(firstEvent, state) + for received := 64; received < size; received += 64 { + ResponsesEventToAnthropicEvents(nextEvent, state) + } + streamAccumulationBenchmarkSink = state.CurrentToolArgs + if len(streamAccumulationBenchmarkSink) != size || state.CurrentToolHadDelta { + b.Fatalf("unfinished Read arguments: bytes=%d, emitted=%v", len(streamAccumulationBenchmarkSink), state.CurrentToolHadDelta) + } + } + }) + } +} diff --git a/backend/internal/pkg/apicompat/stream_string_buffer.go b/backend/internal/pkg/apicompat/stream_string_buffer.go new file mode 100644 index 0000000000..fa16797846 --- /dev/null +++ b/backend/internal/pkg/apicompat/stream_string_buffer.go @@ -0,0 +1,48 @@ +package apicompat + +import "strings" + +// appendStreamString changes only how an existing cumulative string is stored. +// Callers still publish its complete value after each delta. A caller-provided +// seed or replacement stays authoritative, including an explicit empty string. +// Builders are never copied or pooled: previously published String snapshots +// remain immutable when the next block starts or an external value replaces it. +func appendStreamString(buffer **strings.Builder, current, delta string) string { + if delta == "" { + return current + } + if *buffer == nil || (*buffer).String() != current { + *buffer = &strings.Builder{} + _, _ = (*buffer).WriteString(current) + } + _, _ = (*buffer).WriteString(delta) + return (*buffer).String() +} + +func appendIndexedStreamString(buffers *map[int]*strings.Builder, index int, current, delta string) string { + if *buffers == nil { + *buffers = make(map[int]*strings.Builder) + } + buffer := (*buffers)[index] + value := appendStreamString(&buffer, current, delta) + (*buffers)[index] = buffer + return value +} + +// streamStringBytes keeps matching bytes for APIs that require []byte without +// copying the growing public string on every call. The shared snapshot also +// detects sequentially diverging state copies: a mismatch creates a new buffer +// instead of overwriting another state's accumulated prefix. +type streamStringBytes struct { + data []byte + snapshot string +} + +func appendStreamStringBytes(buffer **streamStringBytes, previous, current, delta string) []byte { + if *buffer == nil || (*buffer).snapshot != previous { + *buffer = &streamStringBytes{data: append([]byte(nil), previous...)} + } + (*buffer).data = append((*buffer).data, delta...) + (*buffer).snapshot = current + return (*buffer).data +} diff --git a/backend/internal/pkg/httputil/body.go b/backend/internal/pkg/httputil/body.go index 3a6fab4b78..2923520dde 100644 --- a/backend/internal/pkg/httputil/body.go +++ b/backend/internal/pkg/httputil/body.go @@ -4,6 +4,7 @@ import ( "bytes" "compress/gzip" "compress/zlib" + "context" "errors" "fmt" "io" @@ -19,7 +20,8 @@ const ( jsonUTF8BOMLen = 3 // maxDecompressedBodySize limits the decompressed request body to 64 MB // to prevent decompression bomb attacks. - maxDecompressedBodySize = 64 << 20 + maxDecompressedBodySize = 64 << 20 + maxRequestZstdWindowSize = 8 << 20 ) // PrereadBody 回填已读取完成的请求体:作为 io.ReadCloser 可被再次顺序消费 @@ -64,11 +66,33 @@ func (p *PrereadBody) Bytes() []byte { // 已由 PrereadBody 回填的请求体直接返回其完整切片(零拷贝),不检查内部 // reader 是否已被消费——见 PrereadBody 的文档说明。 func ReadRequestBodyWithPrealloc(req *http.Request) ([]byte, error) { + body, err := readRequestBodyWithBudget(req) + return body.data, err +} + +// requestBodyBuffer carries only allocations owned by the current helper. +// Borrowed input (notably PrereadBody) has no charge to release: its original +// owner may still retain it even if normalization creates a replacement. +type requestBodyBuffer struct { + data []byte + charged int64 +} + +func (b *requestBodyBuffer) release(ctx context.Context) { + charged := b.charged + *b = requestBodyBuffer{} + releaseRequestBodyMemory(ctx, charged) +} + +func readRequestBodyWithBudget(req *http.Request) (requestBodyBuffer, error) { if req == nil || req.Body == nil { - return nil, nil + return requestBodyBuffer{}, nil + } + if err := req.Context().Err(); err != nil { + return requestBodyBuffer{}, err } if preread, ok := req.Body.(*PrereadBody); ok { - return preread.Bytes(), nil + return requestBodyBuffer{data: preread.Bytes()}, nil } capHint := requestBodyReadInitCap @@ -83,9 +107,9 @@ func ReadRequestBodyWithPrealloc(req *http.Request) ([]byte, error) { } } - raw, err := readRequestBodyChunks(req.Body, capHint, req.ContentLength) + raw, err := readRequestBodyChunksWithBudget(req.Context(), req.Body, capHint, req.ContentLength) if err != nil { - return nil, err + return requestBodyBuffer{}, err } enc := strings.ToLower(strings.TrimSpace(req.Header.Get("Content-Encoding"))) @@ -93,14 +117,15 @@ func ReadRequestBodyWithPrealloc(req *http.Request) ([]byte, error) { return raw, nil } - decoded, err := decompressRequestBody(enc, raw) + defer raw.release(req.Context()) + decoded, err := decompressRequestBodyWithBudget(req.Context(), enc, raw.data) if err != nil { - return nil, fmt.Errorf("decode Content-Encoding %q: %w", enc, err) + return requestBodyBuffer{}, fmt.Errorf("decode Content-Encoding %q: %w", enc, err) } req.Header.Del("Content-Encoding") req.Header.Del("Content-Length") - req.ContentLength = int64(len(decoded)) + req.ContentLength = int64(len(decoded.data)) return decoded, nil } @@ -108,7 +133,13 @@ func ReadRequestBodyWithPrealloc(req *http.Request) ([]byte, error) { // Read bounded chunks as bytes arrive, then assemble the exact-size result. // This avoids doubling large buffers or eagerly allocating an untrusted // Content-Length before the corresponding bytes have arrived. -func readRequestBodyChunks(reader io.Reader, initialCapacity int, contentLength int64) ([]byte, error) { +func readRequestBodyChunksWithBudget(ctx context.Context, reader io.Reader, initialCapacity int, contentLength int64) (result requestBodyBuffer, err error) { + var reserved int64 + defer func() { + // Chunks and the EOF probe are temporary once the final buffer is + // assembled. On failure there is no result, so refund all allocations. + releaseRequestBodyMemory(ctx, reserved-result.charged) + }() capacity := initialCapacity var chunks [][]byte total := 0 @@ -117,16 +148,26 @@ func readRequestBodyChunks(reader io.Reader, initialCapacity int, contentLength if remaining := contentLength - int64(total); remaining >= 0 && remaining < int64(chunkCapacity) { chunkCapacity = int(remaining) + 1 } + if err := reserveRequestBodyMemory(ctx, int64(chunkCapacity)); err != nil { + return requestBodyBuffer{}, err + } + reserved += int64(chunkCapacity) chunk := make([]byte, chunkCapacity) n := 0 var err error for n < len(chunk) && err == nil { + if err := ctx.Err(); err != nil { + return requestBodyBuffer{}, err + } var read int read, err = reader.Read(chunk[n:]) n += read } + if err := ctx.Err(); err != nil { + return requestBodyBuffer{}, err + } if err != nil && err != io.EOF { - return nil, err + return requestBodyBuffer{}, err } if n > 0 { chunks = append(chunks, chunk[:n]) @@ -134,17 +175,21 @@ func readRequestBodyChunks(reader io.Reader, initialCapacity int, contentLength } if err != nil { if len(chunks) == 0 { - return chunk[:0], nil + return requestBodyBuffer{}, nil } if len(chunks) == 1 { - return chunks[0], nil + return requestBodyBuffer{data: chunks[0], charged: int64(cap(chunks[0]))}, nil } + if err := reserveRequestBodyMemory(ctx, int64(total)); err != nil { + return requestBodyBuffer{}, err + } + reserved += int64(total) body := make([]byte, total) offset := 0 for _, part := range chunks { offset += copy(body[offset:], part) } - return body, nil + return requestBodyBuffer{data: body, charged: int64(total)}, nil } if capacity < requestBodyReadMaxInitCap { capacity *= 2 @@ -158,73 +203,102 @@ func readRequestBodyChunks(reader io.Reader, initialCapacity int, contentLength // ReadLenientJSONRequestBodyWithPrealloc reads a request body and normalizes // JSON string control bytes before strict validation. func ReadLenientJSONRequestBodyWithPrealloc(req *http.Request, maxNormalizedBytes int64) ([]byte, error) { - body, err := ReadRequestBodyWithPrealloc(req) + if req == nil { + return nil, nil + } + body, err := readRequestBodyWithBudget(req) if err != nil { return nil, err } - return NormalizeLenientJSONRequestBody(body, maxNormalizedBytes) + normalized, err := normalizeLenientJSONRequestBody(req.Context(), body.data, maxNormalizedBytes) + if err != nil || normalized.charged > 0 { + body.release(req.Context()) + } + return normalized.data, err } func decompressRequestBody(encoding string, raw []byte) ([]byte, error) { + body, err := decompressRequestBodyWithBudget(context.Background(), encoding, raw) + return body.data, err +} + +func decompressRequestBodyWithBudget(ctx context.Context, encoding string, raw []byte) (requestBodyBuffer, error) { + var reader io.Reader switch encoding { case "zstd": - dec, err := zstd.NewReader(bytes.NewReader(raw)) + if err := reserveRequestBodyMemory(ctx, maxRequestZstdWindowSize); err != nil { + return requestBodyBuffer{}, err + } + defer releaseRequestBodyMemory(ctx, maxRequestZstdWindowSize) + dec, err := zstd.NewReader(bytes.NewReader(raw), + zstd.WithDecoderConcurrency(1), + zstd.WithDecoderMaxWindow(maxRequestZstdWindowSize), + zstd.WithDecoderMaxMemory(maxDecompressedBodySize)) if err != nil { - return nil, err + return requestBodyBuffer{}, err } defer dec.Close() - return io.ReadAll(io.LimitReader(dec, maxDecompressedBodySize)) + reader = dec case "gzip", "x-gzip": gr, err := gzip.NewReader(bytes.NewReader(raw)) if err != nil { - return nil, err + return requestBodyBuffer{}, err } defer func() { _ = gr.Close() }() - return io.ReadAll(io.LimitReader(gr, maxDecompressedBodySize)) + reader = gr case "deflate": zr, err := zlib.NewReader(bytes.NewReader(raw)) if err != nil { - return nil, err + return requestBodyBuffer{}, err } defer func() { _ = zr.Close() }() - return io.ReadAll(io.LimitReader(zr, maxDecompressedBodySize)) + reader = zr default: - return nil, errors.New("unsupported Content-Encoding") + return requestBodyBuffer{}, errors.New("unsupported Content-Encoding") } + decoded, err := readRequestBodyChunksWithBudget(ctx, io.LimitReader(reader, maxDecompressedBodySize+1), requestBodyReadInitCap, -1) + if err != nil { + return requestBodyBuffer{}, err + } + if len(decoded.data) > maxDecompressedBodySize { + decoded.release(ctx) + return requestBodyBuffer{}, &http.MaxBytesError{Limit: maxDecompressedBodySize} + } + return decoded, nil } // NormalizeLenientJSONRequestBody escapes raw control bytes that broken // OpenAI-compatible clients sometimes place inside JSON strings. func NormalizeLenientJSONRequestBody(body []byte, maxNormalizedBytes int64) ([]byte, error) { + normalized, err := normalizeLenientJSONRequestBody(context.Background(), body, maxNormalizedBytes) + return normalized.data, err +} + +func normalizeLenientJSONRequestBody(ctx context.Context, body []byte, maxNormalizedBytes int64) (requestBodyBuffer, error) { + if err := ctx.Err(); err != nil { + return requestBodyBuffer{}, err + } if maxNormalizedBytes <= 0 { maxNormalizedBytes = maxDecompressedBodySize } body = trimUTF8BOM(body) if len(body) == 0 { - return body, nil + return requestBodyBuffer{data: body}, nil } if int64(len(body)) > maxNormalizedBytes { - return nil, &http.MaxBytesError{Limit: maxNormalizedBytes} + return requestBodyBuffer{}, &http.MaxBytesError{Limit: maxNormalizedBytes} } - var out []byte + normalizedSize := int64(len(body)) inString := false escaped := false - for i, b := range body { + for _, b := range body { if inString && isJSONControlByte(b) { - if out == nil { - capHint := len(body) + 6 - if int64(capHint) > maxNormalizedBytes { - capHint = int(maxNormalizedBytes) - } - out = make([]byte, 0, capHint) - out = append(out, body[:i]...) + if maxNormalizedBytes-normalizedSize < 5 { + return requestBodyBuffer{}, &http.MaxBytesError{Limit: maxNormalizedBytes} } - if int64(len(out)+6) > maxNormalizedBytes { - return nil, &http.MaxBytesError{Limit: maxNormalizedBytes} - } - out = appendJSONUnicodeEscape(out, b) + normalizedSize += 5 escaped = false continue } @@ -237,18 +311,41 @@ func NormalizeLenientJSONRequestBody(body []byte, maxNormalizedBytes int64) ([]b case b == '"': inString = !inString } - - if out != nil { - if int64(len(out)+1) > maxNormalizedBytes { - return nil, &http.MaxBytesError{Limit: maxNormalizedBytes} - } - out = append(out, b) + } + if err := ctx.Err(); err != nil { + return requestBodyBuffer{}, err + } + if normalizedSize == int64(len(body)) { + return requestBodyBuffer{data: body}, nil + } + if err := reserveRequestBodyMemory(ctx, normalizedSize); err != nil { + return requestBodyBuffer{}, err + } + // Allocate once after counting expansion, so escaped control bytes cannot + // bypass the ingress budget through append's geometric capacity growth. + out := make([]byte, 0, int(normalizedSize)) + inString, escaped = false, false + for _, b := range body { + if inString && isJSONControlByte(b) { + out = appendJSONUnicodeEscape(out, b) + escaped = false + continue } + switch { + case escaped: + escaped = false + case inString && b == '\\': + escaped = true + case b == '"': + inString = !inString + } + out = append(out, b) } - if out != nil { - return out, nil + if err := ctx.Err(); err != nil { + releaseRequestBodyMemory(ctx, normalizedSize) + return requestBodyBuffer{}, err } - return body, nil + return requestBodyBuffer{data: out, charged: normalizedSize}, nil } func trimUTF8BOM(body []byte) []byte { diff --git a/backend/internal/pkg/httputil/body_budget.go b/backend/internal/pkg/httputil/body_budget.go new file mode 100644 index 0000000000..9c6dc9fbea --- /dev/null +++ b/backend/internal/pkg/httputil/body_budget.go @@ -0,0 +1,98 @@ +package httputil + +import ( + "context" + "errors" + "sync" +) + +// ErrRequestBodyMemoryBudget means this instance cannot buffer another request +// body yet. It is transient overload, not a malformed or oversized request. +var ErrRequestBodyMemoryBudget = errors.New("request body memory budget exhausted") + +// BodyMemoryBudget bounds buffered ingress allocations across requests. It +// counts chunks, their contiguous copy, decoded output and the decoder window; +// it is not a bound on the application's total heap or protocol conversion. +type BodyMemoryBudget struct { + mu sync.Mutex + limit int64 + used int64 +} + +func NewBodyMemoryBudget(limit int64) *BodyMemoryBudget { + return &BodyMemoryBudget{limit: limit} +} + +type bodyMemoryReservation struct { + mu sync.Mutex + budget *BodyMemoryBudget + bytes int64 + closed bool +} + +type bodyMemoryReservationKey struct{} + +// WithRequestBodyMemoryBudget retains final body reservations until the HTTP +// handler returns, including while a buffered request waits for a user slot. +// Read/decode/normalize helpers release temporary allocations when no longer +// owned. No goroutines or wait queue are created on exhaustion. +func WithRequestBodyMemoryBudget(ctx context.Context, budget *BodyMemoryBudget) (context.Context, func()) { + if budget == nil || budget.limit <= 0 || ctx.Value(bodyMemoryReservationKey{}) != nil { + return ctx, func() {} + } + r := &bodyMemoryReservation{budget: budget} + return context.WithValue(ctx, bodyMemoryReservationKey{}, r), func() { + r.mu.Lock() + defer r.mu.Unlock() + if r.closed { + return + } + r.closed = true + budget.mu.Lock() + budget.used -= r.bytes + budget.mu.Unlock() + r.bytes = 0 + } +} + +func reserveRequestBodyMemory(ctx context.Context, n int64) error { + if err := ctx.Err(); err != nil { + return err + } + r, _ := ctx.Value(bodyMemoryReservationKey{}).(*bodyMemoryReservation) + if r == nil || n <= 0 { + return nil + } + r.mu.Lock() + defer r.mu.Unlock() + if r.closed { + return ErrRequestBodyMemoryBudget + } + r.budget.mu.Lock() + defer r.budget.mu.Unlock() + if n > r.budget.limit-r.budget.used { + return ErrRequestBodyMemoryBudget + } + r.budget.used += n + r.bytes += n + return nil +} + +// releaseRequestBodyMemory refunds storage that a helper no longer owns. Each +// allocation must be released once, or left for the handler's final cleanup. +// Cleanup may race with a cancelled read, so a closed reservation is a no-op. +func releaseRequestBodyMemory(ctx context.Context, n int64) { + r, _ := ctx.Value(bodyMemoryReservationKey{}).(*bodyMemoryReservation) + if r == nil || n <= 0 { + return + } + r.mu.Lock() + defer r.mu.Unlock() + if r.closed { + return + } + r.budget.mu.Lock() + r.budget.used -= n + r.budget.mu.Unlock() + r.bytes -= n +} diff --git a/backend/internal/pkg/httputil/body_budget_test.go b/backend/internal/pkg/httputil/body_budget_test.go new file mode 100644 index 0000000000..3f2f06c7f7 --- /dev/null +++ b/backend/internal/pkg/httputil/body_budget_test.go @@ -0,0 +1,367 @@ +package httputil + +import ( + "bytes" + "compress/gzip" + "context" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/klauspost/compress/zstd" +) + +func TestRequestBodyMemoryBudgetSharedUntilRelease(t *testing.T) { + budget := NewBodyMemoryBudget(1024) + ctx, release := WithRequestBodyMemoryBudget(context.Background(), budget) + req := httptest.NewRequest("POST", "/", bytes.NewReader(bytes.Repeat([]byte{'x'}, 700))).WithContext(ctx) + got, err := ReadRequestBodyWithPrealloc(req) + if err != nil || len(got) != 700 { + t.Fatalf("read: %d %v", len(got), err) + } + ctx2, release2 := WithRequestBodyMemoryBudget(context.Background(), budget) + defer release2() + req2 := httptest.NewRequest("POST", "/", bytes.NewReader(bytes.Repeat([]byte{'x'}, 700))).WithContext(ctx2) + if _, err := ReadRequestBodyWithPrealloc(req2); !errors.Is(err, ErrRequestBodyMemoryBudget) { + t.Fatalf("want capacity error, got %v", err) + } + release() + release() // Idempotent cleanup cannot refund another request's allocation. + if _, err := ReadRequestBodyWithPrealloc(req2); err != nil { + t.Fatal(err) + } +} + +func TestRequestBodyMemoryBudgetUnknownLengthAndConcurrency(t *testing.T) { + budget := NewBodyMemoryBudget(4096) + ctx, release := WithRequestBodyMemoryBudget(context.Background(), budget) + req := httptest.NewRequest("POST", "/", io.NopCloser(bytes.NewReader(bytes.Repeat([]byte{'x'}, 8192)))).WithContext(ctx) + req.ContentLength = -1 + if _, err := ReadRequestBodyWithPrealloc(req); !errors.Is(err, ErrRequestBodyMemoryBudget) { + t.Fatalf("unknown length bypassed budget: %v", err) + } + release() + var wg sync.WaitGroup + for range 20 { + wg.Go(func() { + ctx, release := WithRequestBodyMemoryBudget(context.Background(), budget) + defer release() + _ = reserveRequestBodyMemory(ctx, 1024) + }) + } + wg.Wait() + if budget.used != 0 { + t.Fatalf("leaked reservations: %d", budget.used) + } +} + +func TestDecompressRequestBodyRejectsExcessiveZstdWindow(t *testing.T) { + for _, exponent := range []byte{20, 24, 29} { + raw := []byte{0x28, 0xb5, 0x2f, 0xfd, 0, (exponent - 10) << 3, 9, 0, 0, 'x'} + decoded, err := decompressRequestBody("zstd", raw) + if exponent == 20 { + if err != nil || string(decoded) != "x" { + t.Fatalf("small window: %q %v", decoded, err) + } + } else if err == nil { + t.Fatalf("accepted window 2^%d", exponent) + } + } +} + +func TestDecompressRequestBodyRejectsOversizeInsteadOfTruncating(t *testing.T) { + var compressed bytes.Buffer + encoder := gzip.NewWriter(&compressed) + chunk := bytes.Repeat([]byte{' '}, 1<<20) + for range maxDecompressedBodySize / len(chunk) { + _, _ = encoder.Write(chunk) + } + _, _ = encoder.Write([]byte{'x'}) + if err := encoder.Close(); err != nil { + t.Fatal(err) + } + budget := NewBodyMemoryBudget(256 << 20) + ctx, release := WithRequestBodyMemoryBudget(context.Background(), budget) + defer release() + req := newRequestWithBody(t, compressed.Bytes(), "gzip").WithContext(ctx) + decoded, err := ReadRequestBodyWithPrealloc(req) + var maxErr *http.MaxBytesError + if decoded != nil || !errors.As(err, &maxErr) || maxErr.Limit != maxDecompressedBodySize { + t.Fatalf("silently truncated: len=%d err=%v", len(decoded), err) + } + if used := requestBodyBudgetUsed(budget); used != 0 { + t.Fatalf("oversize decoded body retained %d bytes", used) + } +} + +func TestDecodedRequestBodySharesMemoryBudget(t *testing.T) { + var compressed bytes.Buffer + encoder := gzip.NewWriter(&compressed) + _, _ = encoder.Write(bytes.Repeat([]byte{'x'}, 4096)) + _ = encoder.Close() + ctx, release := WithRequestBodyMemoryBudget(context.Background(), NewBodyMemoryBudget(2048)) + defer release() + req := httptest.NewRequest("POST", "/", bytes.NewReader(compressed.Bytes())).WithContext(ctx) + req.Header.Set("Content-Encoding", "gzip") + if _, err := ReadRequestBodyWithPrealloc(req); !errors.Is(err, ErrRequestBodyMemoryBudget) { + t.Fatalf("decode bypassed budget: %v", err) + } +} + +func TestNormalizedRequestBodySharesMemoryBudget(t *testing.T) { + body := []byte(`{"input":"` + strings.Repeat("\x00", 100) + `"}`) + ctx, release := WithRequestBodyMemoryBudget(context.Background(), NewBodyMemoryBudget(600)) + defer release() + req := httptest.NewRequest("POST", "/", bytes.NewReader(body)).WithContext(ctx) + if _, err := ReadLenientJSONRequestBodyWithPrealloc(req, 4096); !errors.Is(err, ErrRequestBodyMemoryBudget) { + t.Fatalf("normalization bypassed budget: %v", err) + } +} + +func requestBodyBudgetUsed(budget *BodyMemoryBudget) int64 { + budget.mu.Lock() + defer budget.mu.Unlock() + return budget.used +} + +func TestRequestBodyMemoryBudgetRetainsOnlyFinalAllocation(t *testing.T) { + for _, encoding := range []string{"identity", "gzip", "zstd"} { + for _, normalize := range []bool{false, true} { + name := encoding + if normalize { + name += "/normalized" + } + t.Run(name, func(t *testing.T) { + text := strings.Repeat("x", requestBodyReadMaxInitCap+64) + if normalize { + text += "\x00" + } + payload := []byte(`{"input":"` + text + `"}`) + raw := payload + switch encoding { + case "gzip": + var compressed bytes.Buffer + encoder := gzip.NewWriter(&compressed) + if _, err := encoder.Write(payload); err != nil { + t.Fatal(err) + } + if err := encoder.Close(); err != nil { + t.Fatal(err) + } + raw = compressed.Bytes() + case "zstd": + encoder, err := zstd.NewWriter(nil, zstd.WithEncoderConcurrency(1)) + if err != nil { + t.Fatal(err) + } + raw = encoder.EncodeAll(payload, nil) + if err := encoder.Close(); err != nil { + t.Fatal(err) + } + } + budget := NewBodyMemoryBudget(32 << 20) + ctx, release := WithRequestBodyMemoryBudget(context.Background(), budget) + defer release() + req := newRequestWithBody(t, raw, encoding).WithContext(ctx) + // Unknown length exercises chunk growth and its extra EOF probe. + req.ContentLength = -1 + got, err := ReadLenientJSONRequestBodyWithPrealloc(req, 4<<20) + if err != nil { + t.Fatal(err) + } + want := bytes.ReplaceAll(payload, []byte{0}, []byte(`\u0000`)) + if !bytes.Equal(got, want) { + t.Fatal("body contents changed") + } + if used := requestBodyBudgetUsed(budget); used != int64(cap(got)) { + t.Fatalf("retained %d bytes, final allocation is %d", used, cap(got)) + } + release() + if used := requestBodyBudgetUsed(budget); used != 0 { + t.Fatalf("handler cleanup retained %d bytes", used) + } + }) + } + } +} + +func TestRequestBodyMemoryBudgetReusesTransientCapacityWhileHandlersWait(t *testing.T) { + const bodySize = requestBodyReadMaxInitCap + 512 + // Enough for two retained bodies plus the third body before concatenation. + // A third simultaneous final copy must still be rejected. + budget := NewBodyMemoryBudget(3*bodySize + 1) + payload := bytes.Repeat([]byte{'x'}, bodySize) + readDone := make(chan error, 2) + finish := make(chan struct{}) + var handlers sync.WaitGroup + defer func() { + close(finish) + handlers.Wait() + if used := requestBodyBudgetUsed(budget); used != 0 { + t.Errorf("completed handlers retained %d bytes", used) + } + }() + handler := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + ctx, release := WithRequestBodyMemoryBudget(req.Context(), budget) + defer release() + body, err := ReadRequestBodyWithPrealloc(req.WithContext(ctx)) + if err != nil { + w.WriteHeader(http.StatusServiceUnavailable) + return + } + readDone <- nil + <-finish + // Keep the final body live for the entire waiting handler. + _, _ = w.Write(body[:1]) + }) + for range 2 { + handlers.Go(func() { + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodPost, "/", bytes.NewReader(payload))) + if recorder.Code != http.StatusOK { + readDone <- errors.New("temporary allocations blocked a second held request") + } + }) + select { + case err := <-readDone: + if err != nil { + t.Fatal(err) + } + case <-time.After(5 * time.Second): + t.Fatal("request did not finish reading") + } + } + if used := requestBodyBudgetUsed(budget); used != 2*bodySize { + t.Fatalf("waiting handlers retain %d bytes, want %d", used, 2*bodySize) + } + thirdDone := make(chan *httptest.ResponseRecorder, 1) + handlers.Go(func() { + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodPost, "/", bytes.NewReader(payload))) + thirdDone <- recorder + }) + select { + case recorder := <-thirdDone: + if recorder.Code != http.StatusServiceUnavailable { + t.Fatalf("third request escaped the transient peak budget: %d", recorder.Code) + } + case <-readDone: + t.Fatal("third request escaped the transient peak budget") + case <-time.After(5 * time.Second): + t.Fatal("third request did not reject overload") + } + if used := requestBodyBudgetUsed(budget); used != 2*bodySize { + t.Fatalf("failed request retained temporary storage: %d", used) + } +} + +type requestBodyBudgetReaderFunc func([]byte) (int, error) + +func (read requestBodyBudgetReaderFunc) Read(p []byte) (int, error) { return read(p) } + +func TestRequestBodyMemoryBudgetRefundsFailedOwnedBuffers(t *testing.T) { + for _, name := range []string{"unknown_length_overload", "concat_overload", "normalization_overload", "normalization_size", "invalid_gzip", "invalid_zstd", "read_error", "cancellation"} { + t.Run(name, func(t *testing.T) { + budget := NewBodyMemoryBudget(16 << 20) + parent, cancel := context.WithCancel(context.Background()) + defer cancel() + ctx, release := WithRequestBodyMemoryBudget(parent, budget) + defer release() + // A previous returned/borrowed allocation must survive this failure. + if err := reserveRequestBodyMemory(ctx, 100); err != nil { + t.Fatal(err) + } + payload := []byte(`{"input":"` + strings.Repeat("x", 100) + `"}`) + maxNormalized := int64(4 << 20) + encoding := "" + var wantErr error + switch name { + case "unknown_length_overload": + budget.limit = 4096 + payload = bytes.Repeat([]byte{'x'}, 8192) + wantErr = ErrRequestBodyMemoryBudget + case "concat_overload": + budget.limit = 20000 + payload = bytes.Repeat([]byte{'x'}, 8192) + wantErr = ErrRequestBodyMemoryBudget + case "normalization_overload": + budget.limit = 600 + payload = []byte(`{"input":"` + strings.Repeat("\x00", 100) + `"}`) + wantErr = ErrRequestBodyMemoryBudget + case "normalization_size": + maxNormalized = 64 + case "invalid_gzip": + encoding = "gzip" + case "invalid_zstd": + encoding = "zstd" + case "read_error": + wantErr = io.ErrUnexpectedEOF + case "cancellation": + wantErr = context.Canceled + } + req := newRequestWithBody(t, payload, encoding).WithContext(ctx) + req.ContentLength = -1 + if name == "normalization_overload" { + req.ContentLength = int64(len(payload)) + } + if name == "read_error" { + req.Body = io.NopCloser(io.MultiReader(bytes.NewReader(payload), requestBodyBudgetReaderFunc(func([]byte) (int, error) { + return 0, io.ErrUnexpectedEOF + }))) + } + if name == "cancellation" { + reader := bytes.NewReader(payload) + req.Body = io.NopCloser(requestBodyBudgetReaderFunc(func(p []byte) (int, error) { + n, err := reader.Read(p) + cancel() + return n, err + })) + } + got, err := ReadLenientJSONRequestBodyWithPrealloc(req, maxNormalized) + if got != nil || err == nil || wantErr != nil && !errors.Is(err, wantErr) { + t.Fatalf("expected failed read (%v), got len=%d err=%v", wantErr, len(got), err) + } + if used := requestBodyBudgetUsed(budget); used != 100 { + t.Fatalf("failed read retained temporary storage or refunded another owner: %d", used) + } + }) + } +} + +func TestRequestBodyMemoryBudgetPreservesBorrowedPrereadAllocation(t *testing.T) { + budget := NewBodyMemoryBudget(4096) + ctx, release := WithRequestBodyMemoryBudget(context.Background(), budget) + defer release() + payload := []byte(`{"input":"hello` + "\x00" + `"}`) + req := newRequestWithBody(t, payload, "").WithContext(ctx) + original, err := ReadRequestBodyWithPrealloc(req) + if err != nil { + t.Fatal(err) + } + req.Body = NewPrereadBody(original) + if _, err := ReadLenientJSONRequestBodyWithPrealloc(req, 1); err == nil { + t.Fatal("oversize preread body was accepted") + } + if used := requestBodyBudgetUsed(budget); used != int64(cap(original)) { + t.Fatalf("failed normalization refunded borrowed storage: %d", used) + } + normalized, err := ReadLenientJSONRequestBodyWithPrealloc(req, 4096) + if err != nil { + t.Fatal(err) + } + if used := requestBodyBudgetUsed(budget); used != int64(cap(original)+cap(normalized)) { + t.Fatalf("original and normalized bodies remain live but only %d bytes are charged", used) + } + again, err := ReadRequestBodyWithPrealloc(req) + if err != nil || !bytes.Equal(again, payload) || &again[0] != &original[0] { + t.Fatal("normalization changed the borrowed preread body") + } + if used := requestBodyBudgetUsed(budget); used != int64(cap(original)+cap(normalized)) { + t.Fatalf("preread fast path changed the budget: %d", used) + } +} diff --git a/backend/internal/pkg/httputil/read_timeout.go b/backend/internal/pkg/httputil/read_timeout.go new file mode 100644 index 0000000000..9c74c450a0 --- /dev/null +++ b/backend/internal/pkg/httputil/read_timeout.go @@ -0,0 +1,156 @@ +package httputil + +import ( + "bufio" + "errors" + "io" + "net" + "net/http" + "sync/atomic" + "time" +) + +// WithBodyReadTimeout bounds each socket read while receiving a body. It does +// not set a whole-request deadline or limit the duration of an SSE response. +func WithBodyReadTimeout(next http.Handler, timeout time.Duration) http.Handler { + if timeout <= 0 { + return next + } + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Body != nil && r.Body != http.NoBody { + body := &bodyReadTimeout{ReadCloser: r.Body, controller: http.NewResponseController(w), timeout: timeout} + r.Body = body + if r.ProtoMajor == 1 { + writer := &bodyDrainTimeoutWriter{ResponseWriter: w, body: body} + defer func() { + if !writer.hijacked.Load() { + // net/http closes its original body after ServeHTTP returns, + // bypassing our Read and Close methods. + body.startDrain() + } + }() + next.ServeHTTP(writer, r) + return + } + } + next.ServeHTTP(w, r) + }) +} + +type bodyReadTimeout struct { + io.ReadCloser + controller *http.ResponseController + timeout time.Duration + finished atomic.Bool + failed atomic.Bool +} + +func (r *bodyReadTimeout) Read(p []byte) (int, error) { + err := r.controller.SetReadDeadline(time.Now().Add(r.timeout)) + if err != nil && !errors.Is(err, http.ErrNotSupported) { + return 0, err + } + n, readErr := r.ReadCloser.Read(p) + if errors.Is(readErr, io.EOF) { + r.finished.Store(true) + } else if readErr != nil { + r.failed.Store(true) + } + if readErr == nil || errors.Is(readErr, io.EOF) { + _ = r.controller.SetReadDeadline(time.Time{}) + } + // Keep a failed read's deadline: net/http may drain an unread HTTP/1 body + // after the handler returns. Clearing a timeout here could block that drain. + return n, readErr +} + +func (r *bodyReadTimeout) Close() error { + armed := r.startDrain() + err := r.ReadCloser.Close() + if err == nil { + r.finished.Store(true) + } else { + r.failed.Store(true) + } + r.finishDrain(armed) + return err +} + +func (r *bodyReadTimeout) startDrain() bool { + if r.finished.Load() || r.failed.Load() { + return false + } + return r.controller.SetReadDeadline(time.Now().Add(r.timeout)) == nil +} + +func (r *bodyReadTimeout) finishDrain(armed bool) { + if armed && !r.failed.Load() { + _ = r.controller.SetReadDeadline(time.Time{}) + } +} + +// HTTP/1 can drain an unread request body during its first response write or +// flush as well as after the handler returns. These reads use net/http's original +// body, so guard the response operations too. HTTP/2 has no such implicit drain. +type bodyDrainTimeoutWriter struct { + http.ResponseWriter + body *bodyReadTimeout + hijacked atomic.Bool + fullDuplex atomic.Bool +} + +func (w *bodyDrainTimeoutWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter } + +func (w *bodyDrainTimeoutWriter) startDrain() bool { + return !w.fullDuplex.Load() && w.body.startDrain() +} + +func (w *bodyDrainTimeoutWriter) Write(p []byte) (int, error) { + armed := w.startDrain() + defer w.body.finishDrain(armed) + return w.ResponseWriter.Write(p) +} + +func (w *bodyDrainTimeoutWriter) WriteString(s string) (int, error) { + armed := w.startDrain() + defer w.body.finishDrain(armed) + return io.WriteString(w.ResponseWriter, s) +} + +func (w *bodyDrainTimeoutWriter) WriteHeader(status int) { + armed := w.startDrain() + defer w.body.finishDrain(armed) + w.ResponseWriter.WriteHeader(status) +} + +func (w *bodyDrainTimeoutWriter) FlushError() error { + armed := w.startDrain() + defer w.body.finishDrain(armed) + return http.NewResponseController(w.ResponseWriter).Flush() +} + +func (w *bodyDrainTimeoutWriter) Flush() { _ = w.FlushError() } + +func (w *bodyDrainTimeoutWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { + conn, rw, err := http.NewResponseController(w.ResponseWriter).Hijack() + if err == nil { + w.hijacked.Store(true) + _ = conn.SetReadDeadline(time.Time{}) + } + return conn, rw, err +} + +func (w *bodyDrainTimeoutWriter) EnableFullDuplex() error { + if err := http.NewResponseController(w.ResponseWriter).EnableFullDuplex(); err != nil { + return err + } + w.fullDuplex.Store(true) + return nil +} + +func (w *bodyDrainTimeoutWriter) CloseNotify() <-chan bool { + if notifier, ok := w.ResponseWriter.(http.CloseNotifier); ok { //nolint:staticcheck // Gin's ResponseWriter still requires legacy CloseNotify forwarding. + return notifier.CloseNotify() + } + return make(chan bool) +} diff --git a/backend/internal/pkg/httputil/read_timeout_test.go b/backend/internal/pkg/httputil/read_timeout_test.go new file mode 100644 index 0000000000..6d10bc9e6f --- /dev/null +++ b/backend/internal/pkg/httputil/read_timeout_test.go @@ -0,0 +1,261 @@ +package httputil + +import ( + "context" + "errors" + "io" + "net" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +func TestBodyReadTimeoutReleasesStalledUpload(t *testing.T) { + readDone := make(chan error, 1) + srv := httptest.NewServer(WithBodyReadTimeout(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, err := io.ReadAll(r.Body) + readDone <- err + }), 100*time.Millisecond)) + defer srv.Close() + conn, err := net.Dial("tcp", srv.Listener.Addr().String()) + if err != nil { + t.Fatal(err) + } + defer func() { _ = conn.Close() }() + if _, err := io.WriteString(conn, "POST / HTTP/1.1\r\nHost: test\r\nContent-Length: 1024\r\n\r\nx"); err != nil { + t.Fatal(err) + } + select { + case err := <-readDone: + var timeout net.Error + if !errors.As(err, &timeout) || !timeout.Timeout() { + t.Fatalf("want upload timeout, got %v", err) + } + case <-time.After(5 * time.Second): + t.Fatal("stalled upload retained handler") + } +} + +func TestBodyReadTimeoutClosesStalledHTTP1Connection(t *testing.T) { + closed := make(chan struct{}, 1) + handlerDone := make(chan struct{}) + srv := httptest.NewUnstartedServer(WithWriteTimeout(WithBodyReadTimeout(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if _, err := io.ReadAll(r.Body); err != nil { + w.WriteHeader(http.StatusBadRequest) + } + close(handlerDone) + }), 100*time.Millisecond), 100*time.Millisecond)) + srv.Config.ConnState = func(_ net.Conn, state http.ConnState) { + if state == http.StateClosed { + select { + case closed <- struct{}{}: + default: + } + } + } + srv.Start() + defer srv.Close() + conn, err := net.Dial("tcp", srv.Listener.Addr().String()) + if err != nil { + t.Fatal(err) + } + defer func() { _ = conn.Close() }() + // Keep the remainder small enough for net/http's automatic post-handler + // drain. Clearing the failed read's deadline would strand that drain even + // though the application handler itself has already returned. + if _, err := io.WriteString(conn, "POST / HTTP/1.1\r\nHost: test\r\nContent-Length: 1024\r\n\r\nx"); err != nil { + t.Fatal(err) + } + select { + case <-handlerDone: + case <-time.After(2 * time.Second): + t.Fatal("stalled upload retained handler") + } + select { + case <-closed: + case <-time.After(2 * time.Second): + t.Fatal("timed-out upload retained the connection while net/http drained the unread body") + } +} + +func TestBodyReadTimeoutClosesRejectedHTTP1Upload(t *testing.T) { + for _, partialRead := range []bool{false, true} { + for _, response := range []string{"buffered", "flush", "large_write", "close_body"} { + name := response + "/unread" + if partialRead { + name = response + "/partial_read" + } + t.Run(name, func(t *testing.T) { + handlerDone := make(chan error, 1) + closed := make(chan struct{}, 1) + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if partialRead { + if _, err := io.ReadFull(r.Body, make([]byte, 1)); err != nil { + handlerDone <- err + return + } + } + ctx, release := WithRequestBodyMemoryBudget(r.Context(), NewBodyMemoryBudget(1)) + defer release() + _, err := ReadRequestBodyWithPrealloc(r.WithContext(ctx)) + if !errors.Is(err, ErrRequestBodyMemoryBudget) { + handlerDone <- errors.New("request did not exhaust its body budget") + return + } + w.WriteHeader(http.StatusServiceUnavailable) + switch response { + case "flush": + _ = http.NewResponseController(w).Flush() + case "large_write": + _, _ = w.Write([]byte(strings.Repeat("x", 8192))) + case "close_body": + _ = r.Body.Close() + default: + _, _ = io.WriteString(w, "busy") + } + handlerDone <- nil + }) + srv := httptest.NewUnstartedServer(WithWriteTimeout(WithBodyReadTimeout(handler, 50*time.Millisecond), 100*time.Millisecond)) + srv.Config.ConnState = func(_ net.Conn, state http.ConnState) { + if state == http.StateClosed { + select { + case closed <- struct{}{}: + default: + } + } + } + srv.Start() + defer srv.Close() + conn, err := net.Dial("tcp", srv.Listener.Addr().String()) + if err != nil { + t.Fatal(err) + } + defer func() { _ = conn.Close() }() + if _, err := io.WriteString(conn, "POST / HTTP/1.1\r\nHost: test\r\nContent-Length: 1024\r\n\r\nx"); err != nil { + t.Fatal(err) + } + select { + case err := <-handlerDone: + if err != nil { + t.Fatal(err) + } + case <-time.After(2 * time.Second): + t.Fatal("rejection blocked while writing the response or closing the body") + } + select { + case <-closed: + case <-time.After(2 * time.Second): + t.Fatal("rejected upload retained its HTTP/1 connection") + } + }) + } + } +} + +func TestBodyReadTimeoutDoesNotLimitHTTP1ResponseLifetime(t *testing.T) { + for _, readAll := range []bool{false, true} { + name := "implicit_drain" + if readAll { + name = "complete_body" + } + t.Run(name, func(t *testing.T) { + handlerErr := make(chan error, 1) + srv := httptest.NewServer(WithBodyReadTimeout(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var err error + if readAll { + _, err = io.Copy(io.Discard, r.Body) + } else { + _, err = io.ReadFull(r.Body, make([]byte, 1)) + } + if err != nil { + handlerErr <- err + return + } + _, _ = io.WriteString(w, "first\n") + if err = http.NewResponseController(w).Flush(); err != nil { + handlerErr <- err + return + } + // The first flush implicitly consumes any unread body. Its read + // deadline must not cancel the response during upstream thinking. + timer := time.NewTimer(300 * time.Millisecond) + defer timer.Stop() + select { + case <-r.Context().Done(): + handlerErr <- r.Context().Err() + return + case <-timer.C: + } + _, err = io.WriteString(w, "last\n") + handlerErr <- err + }), 100*time.Millisecond)) + defer srv.Close() + client := srv.Client() + client.Timeout = 3 * time.Second + resp, err := client.Post(srv.URL, "application/json", strings.NewReader(`{"input":"hello"}`)) + if err != nil { + t.Fatal(err) + } + defer func() { _ = resp.Body.Close() }() + body, err := io.ReadAll(resp.Body) + if err != nil || string(body) != "first\nlast\n" { + t.Fatalf("response was truncated: %q, %v", body, err) + } + if err := <-handlerErr; err != nil { + t.Fatalf("response lifetime was limited by the upload deadline: %v", err) + } + }) + } +} + +func TestBodyReadTimeoutHTTP2DoesNotCancelOtherStreams(t *testing.T) { + readDone := make(chan error, 1) + srv := httptest.NewUnstartedServer(WithBodyReadTimeout(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/slow" { + _, err := io.ReadAll(r.Body) + readDone <- err + return + } + w.WriteHeader(http.StatusNoContent) + }), 100*time.Millisecond)) + srv.EnableHTTP2 = true + srv.StartTLS() + defer srv.Close() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + reader, writer := io.Pipe() + defer func() { _ = writer.Close() }() + slow, _ := http.NewRequestWithContext(ctx, http.MethodPost, srv.URL+"/slow", reader) + clientDone := make(chan struct{}) + go func() { + defer close(clientDone) + resp, err := srv.Client().Do(slow) + if err == nil { + _ = resp.Body.Close() + } + }() + defer func() { + cancel() + _ = writer.Close() + <-clientDone + }() + select { + case err := <-readDone: + if err == nil { + t.Fatal("stalled HTTP/2 upload accepted") + } + case <-ctx.Done(): + t.Fatal("stalled HTTP/2 upload retained handler") + } + fast, _ := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL+"/fast", nil) + resp, err := srv.Client().Do(fast) + if err != nil { + t.Fatal(err) + } + defer func() { _ = resp.Body.Close() }() + if resp.ProtoMajor != 2 || resp.StatusCode != http.StatusNoContent { + t.Fatalf("other stream failed: %s %s", resp.Proto, resp.Status) + } +} diff --git a/backend/internal/pkg/httputil/upstream_drain.go b/backend/internal/pkg/httputil/upstream_drain.go new file mode 100644 index 0000000000..9aee08bfb2 --- /dev/null +++ b/backend/internal/pkg/httputil/upstream_drain.go @@ -0,0 +1,73 @@ +package httputil + +import ( + "context" + "sync" + "time" +) + +const DefaultUpstreamDrainTimeout = 180 * time.Second + +type upstreamDrainKey struct{} +type upstreamDrainPolicy struct { + client context.Context + timeout time.Duration +} + +// DetachUpstreamContext keeps billing reads alive after the client leaves. It +// records the original cancellation signal without starting a timer or changing +// existing construction-time release semantics. The transport owns the actual +// attempt lifetime and installs the bounded drain when sending the request. +func DetachUpstreamContext(ctx context.Context, timeout ...time.Duration) context.Context { + if ctx == nil { + ctx = context.Background() + } + policy := upstreamDrainPolicy{client: ctx} + if previous, ok := ctx.Value(upstreamDrainKey{}).(upstreamDrainPolicy); ok { + policy = previous + } + if len(timeout) > 0 && timeout[0] > 0 { + policy.timeout = timeout[0] + } + return context.WithValue(context.WithoutCancel(ctx), upstreamDrainKey{}, policy) +} + +// NewUpstreamAttemptContext starts a total drain budget when the original client +// context is cancelled. Incoming bytes do not extend this budget. Until then the +// request may stream for arbitrarily long, and late usage remains readable +// throughout the drain window. release must run on error or response-body close. +func NewUpstreamAttemptContext(parent context.Context, defaultTimeout time.Duration) (context.Context, context.CancelFunc) { + ctx, cancel := context.WithCancel(parent) + policy, ok := parent.Value(upstreamDrainKey{}).(upstreamDrainPolicy) + if !ok || policy.client.Done() == nil { + return ctx, cancel + } + timeout := policy.timeout + if timeout <= 0 { + timeout = defaultTimeout + } + if timeout <= 0 { + timeout = DefaultUpstreamDrainTimeout + } + var mu sync.Mutex + var timer *time.Timer + closed := false + startDrain := func() { + mu.Lock() + defer mu.Unlock() + if !closed { + timer = time.AfterFunc(timeout, cancel) + } + } + stop := context.AfterFunc(policy.client, startDrain) + return ctx, func() { + stop() + mu.Lock() + closed = true + if timer != nil { + timer.Stop() + } + mu.Unlock() + cancel() + } +} diff --git a/backend/internal/pkg/httputil/upstream_drain_test.go b/backend/internal/pkg/httputil/upstream_drain_test.go new file mode 100644 index 0000000000..b6e6f8f9cf --- /dev/null +++ b/backend/internal/pkg/httputil/upstream_drain_test.go @@ -0,0 +1,54 @@ +package httputil + +import ( + "context" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestUpstreamDrainStartsOnlyAfterClientCancellation(t *testing.T) { + client, cancelClient := context.WithCancel(context.Background()) + defer cancelClient() + upstream, release := NewUpstreamAttemptContext(DetachUpstreamContext(client), 30*time.Millisecond) + defer release() + time.Sleep(60 * time.Millisecond) + require.NoError(t, upstream.Err()) + cancelClient() + select { + case <-upstream.Done(): + t.Fatal("cancelled before late usage drain window") + case <-time.After(10 * time.Millisecond): + } + select { + case <-upstream.Done(): + require.ErrorIs(t, upstream.Err(), context.Canceled) + case <-time.After(time.Second): + t.Fatal("drain exceeded total budget") + } +} + +func TestUpstreamDrainOverrideAndNestedDetachKeepOriginalSignal(t *testing.T) { + client, cancelClient := context.WithCancel(context.Background()) + parent := DetachUpstreamContext(DetachUpstreamContext(client, 20*time.Millisecond)) + upstream, release := NewUpstreamAttemptContext(parent, time.Second) + defer release() + cancelClient() + select { + case <-upstream.Done(): + case <-time.After(200 * time.Millisecond): + t.Fatal("nested detach lost original cancellation or override") + } +} + +func TestUpstreamDrainReleaseDoesNotCancelCaller(t *testing.T) { + client, cancelClient := context.WithCancel(context.Background()) + defer cancelClient() + upstream, release := NewUpstreamAttemptContext(DetachUpstreamContext(client), time.Second) + release() + release() + require.ErrorIs(t, upstream.Err(), context.Canceled) + require.NoError(t, client.Err()) + cancelClient() +} diff --git a/backend/internal/pkg/httputil/write_timeout.go b/backend/internal/pkg/httputil/write_timeout.go new file mode 100644 index 0000000000..3fbdc664f5 --- /dev/null +++ b/backend/internal/pkg/httputil/write_timeout.go @@ -0,0 +1,116 @@ +package httputil + +import ( + "bufio" + "context" + "errors" + "io" + "net" + "net/http" + "time" +) + +// WithWriteTimeout bounds individual writes and flushes. Clearing the deadline +// after each operation permits arbitrarily long upstream thinking intervals. +// Wrapping below Gin also covers all its ResponseWriter decorators and keeps +// HTTP/2 deadlines scoped to the individual stream. +func WithWriteTimeout(next http.Handler, timeout time.Duration) http.Handler { + if timeout <= 0 { + return next + } + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ctx, cancel := context.WithCancel(r.Context()) + defer cancel() + writer := &writeTimeoutWriter{ResponseWriter: w, timeout: timeout, cancel: cancel} + next.ServeHTTP(writer, r.WithContext(ctx)) + }) +} + +type writeTimeoutWriter struct { + http.ResponseWriter + timeout time.Duration + cancel context.CancelFunc + err error +} + +func (w *writeTimeoutWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter } + +func (w *writeTimeoutWriter) start() error { + if w.err != nil { + return w.err + } + err := http.NewResponseController(w.ResponseWriter).SetWriteDeadline(time.Now().Add(w.timeout)) + if err != nil && !errors.Is(err, http.ErrNotSupported) { + w.fail(err) + } + return w.err +} + +func (w *writeTimeoutWriter) finish() { + _ = http.NewResponseController(w.ResponseWriter).SetWriteDeadline(time.Time{}) +} + +func (w *writeTimeoutWriter) fail(err error) { + if err != nil { + w.err = err + w.cancel() + } +} + +func (w *writeTimeoutWriter) Write(p []byte) (int, error) { + if err := w.start(); err != nil { + return 0, err + } + defer w.finish() + n, err := w.ResponseWriter.Write(p) + w.fail(err) + return n, err +} + +func (w *writeTimeoutWriter) WriteString(s string) (int, error) { + if err := w.start(); err != nil { + return 0, err + } + defer w.finish() + n, err := io.WriteString(w.ResponseWriter, s) + w.fail(err) + return n, err +} + +func (w *writeTimeoutWriter) WriteHeader(status int) { + if w.start() != nil { + return + } + defer w.finish() + w.ResponseWriter.WriteHeader(status) +} + +func (w *writeTimeoutWriter) FlushError() error { + if err := w.start(); err != nil { + return err + } + defer w.finish() + err := http.NewResponseController(w.ResponseWriter).Flush() + w.fail(err) + return err +} + +func (w *writeTimeoutWriter) Flush() { _ = w.FlushError() } + +func (w *writeTimeoutWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { + return http.NewResponseController(w.ResponseWriter).Hijack() +} + +func (w *writeTimeoutWriter) Push(target string, opts *http.PushOptions) error { + if pusher, ok := w.ResponseWriter.(http.Pusher); ok { + return pusher.Push(target, opts) + } + return http.ErrNotSupported +} + +func (w *writeTimeoutWriter) CloseNotify() <-chan bool { + if notifier, ok := w.ResponseWriter.(http.CloseNotifier); ok { //nolint:staticcheck // Gin still exposes CloseNotify; preserve legacy writer compatibility. + return notifier.CloseNotify() + } + return make(chan bool) +} diff --git a/backend/internal/pkg/httputil/write_timeout_test.go b/backend/internal/pkg/httputil/write_timeout_test.go new file mode 100644 index 0000000000..e5d026ebaa --- /dev/null +++ b/backend/internal/pkg/httputil/write_timeout_test.go @@ -0,0 +1,145 @@ +package httputil + +import ( + "context" + "errors" + "io" + "net" + "net/http" + "net/http/httptest" + "os" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestWriteTimeoutReleasesSlowHTTP1Client(t *testing.T) { + type result struct { + err error + cancelled bool + } + finished := make(chan result, 1) + srv := httptest.NewServer(WithWriteTimeout(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + payload := make([]byte, 64<<10) + for i := 0; i < 1024; i++ { + if _, err := w.Write(payload); err != nil { + finished <- result{err, r.Context().Err() != nil} + return + } + } + finished <- result{} + }), 40*time.Millisecond)) + defer srv.Close() + conn, err := net.Dial("tcp", strings.TrimPrefix(srv.URL, "http://")) + require.NoError(t, err) + defer func() { _ = conn.Close() }() + if tcp, ok := conn.(*net.TCPConn); ok { + require.NoError(t, tcp.SetReadBuffer(1024)) + } + _, err = io.WriteString(conn, "GET / HTTP/1.1\r\nHost: example\r\n\r\n") + require.NoError(t, err) + select { + case got := <-finished: + require.Error(t, got.err) + require.True(t, got.cancelled) + case <-time.After(3 * time.Second): + t.Fatal("slow HTTP/1 client blocked the handler past its write timeout") + } +} + +func TestWriteTimeoutOnlyCancelsSlowHTTP2Stream(t *testing.T) { + finished := make(chan error, 1) + srv := httptest.NewUnstartedServer(WithWriteTimeout(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/fast" { + _, _ = io.WriteString(w, "ok") + return + } + w.Header().Set("Content-Type", "text/event-stream") + _ = http.NewResponseController(w).Flush() + payload := make([]byte, 64<<10) + for i := 0; i < 1024; i++ { + if _, err := w.Write(payload); err != nil { + if r.Context().Err() == nil { + finished <- errors.New("write failed without cancelling request") + } else { + finished <- err + } + return + } + } + finished <- nil + }), 40*time.Millisecond)) + srv.EnableHTTP2 = true + srv.StartTLS() + defer srv.Close() + client := srv.Client() + client.Timeout = 3 * time.Second + resp, err := client.Get(srv.URL + "/slow") + require.NoError(t, err) + defer func() { _ = resp.Body.Close() }() + require.Equal(t, 2, resp.ProtoMajor) + select { + case err := <-finished: + require.Error(t, err) + case <-time.After(3 * time.Second): + t.Fatal("HTTP/2 flow-control stall did not time out") + } + fast, err := client.Get(srv.URL + "/fast") + require.NoError(t, err) + defer func() { _ = fast.Body.Close() }() + body, err := io.ReadAll(fast.Body) + require.NoError(t, err) + require.Equal(t, "ok", string(body)) +} + +func TestWriteTimeoutClearsDeadlineDuringUpstreamThinkTime(t *testing.T) { + srv := httptest.NewServer(WithWriteTimeout(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = io.WriteString(w, "first") + _ = http.NewResponseController(w).Flush() + time.Sleep(80 * time.Millisecond) + _, _ = io.WriteString(w, "second") + _ = http.NewResponseController(w).Flush() + }), 20*time.Millisecond)) + defer srv.Close() + resp, err := srv.Client().Get(srv.URL) + require.NoError(t, err) + defer func() { _ = resp.Body.Close() }() + body, err := io.ReadAll(resp.Body) + require.NoError(t, err) + require.Equal(t, "firstsecond", string(body)) +} + +type deadlineFlushWriter struct { + header http.Header + deadline time.Time +} + +func (w *deadlineFlushWriter) Header() http.Header { return w.header } +func (w *deadlineFlushWriter) Write(p []byte) (int, error) { return len(p), nil } +func (w *deadlineFlushWriter) WriteHeader(int) {} +func (w *deadlineFlushWriter) SetWriteDeadline(deadline time.Time) error { + w.deadline = deadline + return nil +} +func (w *deadlineFlushWriter) FlushError() error { + if w.deadline.IsZero() { + return errors.New("flush has no deadline") + } + <-time.After(time.Until(w.deadline)) + return os.ErrDeadlineExceeded +} + +func TestWriteTimeoutFlushCancelsContextAndRemembersFailure(t *testing.T) { + underlying := &deadlineFlushWriter{header: make(http.Header)} + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + w := &writeTimeoutWriter{ResponseWriter: underlying, timeout: 10 * time.Millisecond, cancel: cancel} + err := w.FlushError() + require.ErrorIs(t, err, os.ErrDeadlineExceeded) + require.ErrorIs(t, ctx.Err(), context.Canceled) + require.True(t, underlying.deadline.IsZero()) + _, err = w.Write([]byte("must not retry after failed flush")) + require.ErrorIs(t, err, os.ErrDeadlineExceeded) +} diff --git a/backend/internal/repository/http_upstream.go b/backend/internal/repository/http_upstream.go index ff19b03d83..e830b43380 100644 --- a/backend/internal/repository/http_upstream.go +++ b/backend/internal/repository/http_upstream.go @@ -27,6 +27,7 @@ import ( "golang.org/x/net/http2" "github.com/Wei-Shaw/sub2api/internal/config" + pkghttputil "github.com/Wei-Shaw/sub2api/internal/pkg/httputil" "github.com/Wei-Shaw/sub2api/internal/pkg/proxyurl" "github.com/Wei-Shaw/sub2api/internal/pkg/proxyutil" "github.com/Wei-Shaw/sub2api/internal/pkg/servertiming" @@ -219,7 +220,7 @@ func (s *httpUpstreamService) Do(req *http.Request, proxyURL string, accountID i // 执行请求 client := s.httpClientForUpstreamRequest(entry.client, req) client = httpClientWithGrokAccessDeniedFallback(client) - resp, err := doUpstreamRequest(client, req) + resp, err := doUpstreamRequest(client, req, s.upstreamDrainTimeout()) if err != nil { s.recordOpenAIHTTP2Failure(profile, entry.protocolMode, entry.proxyKey, err) // 请求失败,立即减少计数 @@ -280,7 +281,7 @@ func (s *httpUpstreamService) DoWithTLS(req *http.Request, proxyURL string, acco client := s.httpClientForUpstreamRequest(entry.client, req) client = httpClientWithGrokAccessDeniedFallback(client) - resp, err := doUpstreamRequest(client, req) + resp, err := doUpstreamRequest(client, req, s.upstreamDrainTimeout()) if err != nil { atomic.AddInt64(&entry.inFlight, -1) atomic.StoreInt64(&entry.lastUsed, time.Now().UnixNano()) @@ -296,10 +297,21 @@ func (s *httpUpstreamService) DoWithTLS(req *http.Request, proxyURL string, acco return resp, nil } +func (s *httpUpstreamService) upstreamDrainTimeout() time.Duration { + if s.cfg != nil && s.cfg.Gateway.StreamDataIntervalTimeout > 0 { + return time.Duration(s.cfg.Gateway.StreamDataIntervalTimeout) * time.Second + } + return pkghttputil.DefaultUpstreamDrainTimeout +} + // doUpstreamRequest owns cancellation for one attempt, without cancelling the // caller's context (which may be detached for billing or reused for retries). -func doUpstreamRequest(client *http.Client, req *http.Request) (*http.Response, error) { - ctx, cancel := context.WithCancel(req.Context()) +func doUpstreamRequest(client *http.Client, req *http.Request, drainTimeouts ...time.Duration) (*http.Response, error) { + var drainTimeout time.Duration + if len(drainTimeouts) > 0 { + drainTimeout = drainTimeouts[0] + } + ctx, cancel := pkghttputil.NewUpstreamAttemptContext(req.Context(), drainTimeout) resp, err := servertiming.Do(client, req.WithContext(ctx)) if err != nil { cancel() diff --git a/backend/internal/repository/http_upstream_drain_test.go b/backend/internal/repository/http_upstream_drain_test.go new file mode 100644 index 0000000000..1d3fbf548b --- /dev/null +++ b/backend/internal/repository/http_upstream_drain_test.go @@ -0,0 +1,67 @@ +package repository + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + pkghttputil "github.com/Wei-Shaw/sub2api/internal/pkg/httputil" + "github.com/stretchr/testify/require" +) + +func TestHTTPUpstreamDrainContinuousPingsCannotExtendBudget(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + _ = http.NewResponseController(w).Flush() + ticker := time.NewTicker(5 * time.Millisecond) + defer ticker.Stop() + for { + select { + case <-r.Context().Done(): + return + case <-ticker.C: + _, _ = io.WriteString(w, ": ping\n\n") + _ = http.NewResponseController(w).Flush() + } + } + })) + defer srv.Close() + client, cancelClient := context.WithCancel(context.Background()) + defer cancelClient() + req, err := http.NewRequestWithContext(pkghttputil.DetachUpstreamContext(client), http.MethodGet, srv.URL, nil) + require.NoError(t, err) + resp, err := doUpstreamRequest(srv.Client(), req, 40*time.Millisecond) + require.NoError(t, err) + defer func() { _ = resp.Body.Close() }() + cancelClient() + started := time.Now() + body, err := io.ReadAll(resp.Body) + require.Error(t, err) + require.Contains(t, string(body), ": ping") + require.Less(t, time.Since(started), time.Second) +} + +func TestHTTPUpstreamDrainPreservesLateTerminalUsage(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + _ = http.NewResponseController(w).Flush() + time.Sleep(20 * time.Millisecond) + _, _ = io.WriteString(w, "data: {\"type\":\"message_delta\",\"usage\":{\"output_tokens\":7}}\n\ndata: {\"type\":\"message_stop\"}\n\n") + })) + defer srv.Close() + client, cancelClient := context.WithCancel(context.Background()) + defer cancelClient() + req, err := http.NewRequestWithContext(pkghttputil.DetachUpstreamContext(client), http.MethodGet, srv.URL, nil) + require.NoError(t, err) + resp, err := doUpstreamRequest(srv.Client(), req, 200*time.Millisecond) + require.NoError(t, err) + defer func() { _ = resp.Body.Close() }() + cancelClient() + body, err := io.ReadAll(resp.Body) + require.NoError(t, err) + require.True(t, strings.Contains(string(body), "output_tokens\":7") && strings.Contains(string(body), "message_stop")) +} diff --git a/backend/internal/server/http.go b/backend/internal/server/http.go index f999b343b2..68db383d1d 100644 --- a/backend/internal/server/http.go +++ b/backend/internal/server/http.go @@ -10,6 +10,7 @@ import ( "github.com/Wei-Shaw/sub2api/internal/config" "github.com/Wei-Shaw/sub2api/internal/handler" + pkghttputil "github.com/Wei-Shaw/sub2api/internal/pkg/httputil" "github.com/Wei-Shaw/sub2api/internal/pkg/websearch" middleware2 "github.com/Wei-Shaw/sub2api/internal/server/middleware" "github.com/Wei-Shaw/sub2api/internal/service" @@ -121,7 +122,7 @@ func ProvideHTTPServer(cfg *config.Config, router *gin.Engine) *http.Server { // IdleTimeout: 空闲连接超时时间,释放不活跃的连接资源 IdleTimeout: time.Duration(cfg.Server.IdleTimeout) * time.Second, // 注意:不设置 WriteTimeout,因为流式响应可能持续十几分钟 - // 不设置 ReadTimeout,因为大请求体可能需要较长时间读取 + // 请求体使用逐次读取的 idle deadline,不设置覆盖整个大请求上传的 ReadTimeout。 } globalMaxSize := cfg.Server.MaxRequestBodySize @@ -159,7 +160,8 @@ func ProvideHTTPServer(cfg *config.Config, router *gin.Engine) *http.Server { } } - server.Handler = httpHandler + httpHandler = pkghttputil.WithBodyReadTimeout(httpHandler, time.Duration(cfg.Gateway.RequestBodyReadTimeoutSeconds)*time.Second) + server.Handler = pkghttputil.WithWriteTimeout(httpHandler, time.Duration(cfg.Gateway.DownstreamWriteTimeoutSeconds)*time.Second) return server } diff --git a/backend/internal/server/middleware/group_model_allowlist.go b/backend/internal/server/middleware/group_model_allowlist.go index 3f5e61e585..3c8c5d0628 100644 --- a/backend/internal/server/middleware/group_model_allowlist.go +++ b/backend/internal/server/middleware/group_model_allowlist.go @@ -113,6 +113,9 @@ func isResponsesWebSocketRoute(c *gin.Context) bool { func groupModelAllowlistModelsFromBody(c *gin.Context) ([]string, bool) { body, err := httputil.ReadRequestBodyWithPrealloc(c.Request) if err != nil { + if RejectRequestBodyReadError(c, err) { + return nil, false + } status := http.StatusBadRequest message := "Failed to read request body" var maxErr *http.MaxBytesError diff --git a/backend/internal/server/middleware/request_body_limit.go b/backend/internal/server/middleware/request_body_limit.go index fce13eea9b..14d3eaa662 100644 --- a/backend/internal/server/middleware/request_body_limit.go +++ b/backend/internal/server/middleware/request_body_limit.go @@ -1,14 +1,20 @@ package middleware import ( + pkghttputil "github.com/Wei-Shaw/sub2api/internal/pkg/httputil" "net/http" "github.com/gin-gonic/gin" ) // RequestBodyLimit 使用 MaxBytesReader 限制请求体大小。 -func RequestBodyLimit(maxBytes int64) gin.HandlerFunc { +func RequestBodyLimit(maxBytes int64, budgets ...*pkghttputil.BodyMemoryBudget) gin.HandlerFunc { return func(c *gin.Context) { + if len(budgets) > 0 { + ctx, release := pkghttputil.WithRequestBodyMemoryBudget(c.Request.Context(), budgets[0]) + defer release() + c.Request = c.Request.WithContext(ctx) + } c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, maxBytes) c.Next() } diff --git a/backend/internal/server/middleware/request_body_memory.go b/backend/internal/server/middleware/request_body_memory.go new file mode 100644 index 0000000000..d66034f996 --- /dev/null +++ b/backend/internal/server/middleware/request_body_memory.go @@ -0,0 +1,35 @@ +package middleware + +import ( + "errors" + "net/http" + + pkghttputil "github.com/Wei-Shaw/sub2api/internal/pkg/httputil" + "github.com/gin-gonic/gin" +) + +// RejectRequestBodyReadError handles early ingress termination before the route +// handler runs. Cancelled clients have no response body and an uncommitted +// response is marked 499, matching the gateway handler's cancellation path. +func RejectRequestBodyReadError(c *gin.Context, err error) bool { + if err != nil && c != nil && c.Request != nil && c.Request.Context().Err() != nil { + if !c.Writer.Written() { + c.Status(499) + } + c.Abort() + return true + } + return RejectRequestBodyMemoryOverload(c, err) +} + +// RejectRequestBodyMemoryOverload keeps temporary capacity errors distinct +// from invalid JSON and the per-request 413 size limit. +func RejectRequestBodyMemoryOverload(c *gin.Context, err error) bool { + if !errors.Is(err, pkghttputil.ErrRequestBodyMemoryBudget) { + return false + } + c.Header("Retry-After", "1") + groupModelAllowlistErrorWriter(c)(c, http.StatusServiceUnavailable, "Request body buffering capacity is exhausted; retry later") + c.Abort() + return true +} diff --git a/backend/internal/server/middleware/request_body_memory_test.go b/backend/internal/server/middleware/request_body_memory_test.go new file mode 100644 index 0000000000..30cff09a4e --- /dev/null +++ b/backend/internal/server/middleware/request_body_memory_test.go @@ -0,0 +1,98 @@ +package middleware + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + pkghttputil "github.com/Wei-Shaw/sub2api/internal/pkg/httputil" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func TestRequestBodyMemoryRejectsOverloadAndReleasesAfterHandler(t *testing.T) { + router := gin.New() + held := make(chan struct{}) + release := make(chan struct{}) + router.POST("/v1/responses", RequestBodyLimit(2048, pkghttputil.NewBodyMemoryBudget(1024)), func(c *gin.Context) { + _, err := pkghttputil.ReadRequestBodyWithPrealloc(c.Request) + if RejectRequestBodyMemoryOverload(c, err) { + return + } + if err != nil { + c.AbortWithStatus(http.StatusBadRequest) + return + } + if c.Query("hold") == "1" { + close(held) + <-release + } + c.Status(http.StatusNoContent) + }) + request := func(path string) *httptest.ResponseRecorder { + w := httptest.NewRecorder() + router.ServeHTTP(w, httptest.NewRequest(http.MethodPost, path, strings.NewReader(strings.Repeat("x", 700)))) + return w + } + firstDone := make(chan *httptest.ResponseRecorder, 1) + go func() { firstDone <- request("/v1/responses?hold=1") }() + releaseHeld := sync.OnceFunc(func() { close(release) }) + defer releaseHeld() + select { + case <-held: + case <-time.After(5 * time.Second): + t.Fatal("first request did not reach handler") + } + w := request("/v1/responses") + require.Equal(t, http.StatusServiceUnavailable, w.Code) + require.Equal(t, "1", w.Header().Get("Retry-After")) + releaseHeld() + select { + case first := <-firstDone: + require.Equal(t, http.StatusNoContent, first.Code) + case <-time.After(5 * time.Second): + t.Fatal("held request did not finish") + } + require.Equal(t, http.StatusNoContent, request("/v1/responses").Code) +} + +func TestRejectRequestBodyReadErrorCancellation(t *testing.T) { + for _, tc := range []struct { + name string + cancelled bool + committed bool + }{ + {name: "cancelled", cancelled: true}, + {name: "cancelled_after_commit", cancelled: true, committed: true}, + {name: "ordinary_read_error"}, + } { + t.Run(tc.name, func(t *testing.T) { + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + if tc.cancelled { + cancel() + } + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil).WithContext(ctx) + if tc.committed { + _, err := c.Writer.WriteString("already committed") + require.NoError(t, err) + } + bodyBefore := recorder.Body.String() + require.Equal(t, tc.cancelled, RejectRequestBodyReadError(c, io.ErrUnexpectedEOF)) + require.Equal(t, tc.cancelled, c.IsAborted()) + status := http.StatusOK + if tc.cancelled && !tc.committed { + status = 499 + } + require.Equal(t, status, c.Writer.Status()) + require.Equal(t, bodyBefore, recorder.Body.String()) + }) + } +} diff --git a/backend/internal/server/routes/gateway.go b/backend/internal/server/routes/gateway.go index 3f09ebf405..3c1036921d 100644 --- a/backend/internal/server/routes/gateway.go +++ b/backend/internal/server/routes/gateway.go @@ -30,8 +30,9 @@ func RegisterGatewayRoutes( compositeResolver *service.CompositeRouteResolver, cfg *config.Config, ) { - bodyLimit := middleware.RequestBodyLimit(cfg.Gateway.MaxBodySize) - textBodyLimit := middleware.RequestBodyLimit(cfg.Gateway.TextMaxBodySize) + bodyMemoryBudget := pkghttputil.NewBodyMemoryBudget(cfg.Gateway.RequestBodyMemoryBudgetBytes) + bodyLimit := middleware.RequestBodyLimit(cfg.Gateway.MaxBodySize, bodyMemoryBudget) + textBodyLimit := middleware.RequestBodyLimit(cfg.Gateway.TextMaxBodySize, bodyMemoryBudget) clientRequestID := middleware.ClientRequestID() opsErrorLogger := handler.OpsErrorLoggerMiddleware(opsService) endpointNorm := handler.InboundEndpointMiddleware() @@ -563,6 +564,9 @@ func compositeTargetPlatformMiddleware(resolver *service.CompositeRouteResolver) body, err := pkghttputil.ReadRequestBodyWithPrealloc(c.Request) if err != nil { + if middleware.RejectRequestBodyReadError(c, err) { + return + } status := http.StatusBadRequest message := "Failed to read request body" var maxErr *http.MaxBytesError diff --git a/backend/internal/service/account_quota_service_account_test.go b/backend/internal/service/account_quota_service_account_test.go index 6358f32024..a45f23c5d5 100644 --- a/backend/internal/service/account_quota_service_account_test.go +++ b/backend/internal/service/account_quota_service_account_test.go @@ -178,7 +178,7 @@ func TestNotifyAccountQuotaSkipsAccountWithoutLimit(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { settings := &settingGetValueCounter{} - notifyAccountQuota(&postUsageBillingParams{ + notifyAccountQuota(context.Background(), &postUsageBillingParams{ Cost: &CostBreakdown{TotalCost: 2}, Account: tt.account, AccountRateMultiplier: 1, @@ -193,7 +193,7 @@ func TestNotifyAccountQuotaSkipsAccountWithoutLimit(t *testing.T) { // 账号已删除时计数被跳过、无递增后状态,不应回退到快照做阈值判定。 func TestNotifyAccountQuotaSkipsWhenQuotaIncrementSkipped(t *testing.T) { settings := &settingGetValueCounter{} - notifyAccountQuota(&postUsageBillingParams{ + notifyAccountQuota(context.Background(), &postUsageBillingParams{ Cost: &CostBreakdown{TotalCost: 2}, Account: &Account{ID: 9, Platform: PlatformGemini, Type: AccountTypeServiceAccount, Extra: map[string]any{"quota_limit": 100.0}}, AccountRateMultiplier: 1, diff --git a/backend/internal/service/antigravity_gateway_compat_stream.go b/backend/internal/service/antigravity_gateway_compat_stream.go index 140792451d..4dea4c453c 100644 --- a/backend/internal/service/antigravity_gateway_compat_stream.go +++ b/backend/internal/service/antigravity_gateway_compat_stream.go @@ -304,7 +304,7 @@ func (s *AntigravityGatewayService) handleAntigravityCompatStreamWithKeepaliveIn } session := newAntigravityCompatStreamSession(originalModel, startTime, adapter, writer) session.preContentKeepaliveInterval = interval - events, stopScanner, maxLineSize := s.startAntigravityCompatScanner(resp.Body) + events, stopScanner, maxLineSize, queueBudget := s.startAntigravityCompatScanner(resp.Body) defer stopScanner() timeout := s.antigravityCompatStreamTimeout() @@ -340,6 +340,9 @@ func (s *AntigravityGatewayService) handleAntigravityCompatStreamWithKeepaliveIn for { select { case event, open := <-events: + if open { + queueBudget.release(len(event.line)) + } if !session.hasMeaningfulData() && !writer.Disconnected() && !time.Now().Before(preContentDeadline) { return preContentTimeout() } @@ -397,7 +400,7 @@ func handleAntigravityCompatEmptyStream(c *gin.Context, session *antigravityComp func (s *AntigravityGatewayService) startAntigravityCompatScanner( body io.Reader, -) (<-chan antigravityCompatScanEvent, func(), int) { +) (<-chan antigravityCompatScanEvent, func(), int, *sseQueueBudget) { maxLineSize := defaultMaxLineSize if s.settingService != nil && s.settingService.cfg != nil && s.settingService.cfg.Gateway.MaxLineSize > 0 { maxLineSize = s.settingService.cfg.Gateway.MaxLineSize @@ -405,17 +408,23 @@ func (s *AntigravityGatewayService) startAntigravityCompatScanner( scanner := bufio.NewScanner(body) scanBuf := getSSEScannerBuf64K() scanner.Buffer(scanBuf[:0], maxLineSize) + scanner.Split(newBoundedSSESplit(s.antigravitySSEConfig(), maxLineSize, nil)) + queueBudget := newSSEQueueBudget(s.antigravitySSEConfig()) events := make(chan antigravityCompatScanEvent, 16) done := make(chan struct{}) go func() { defer putSSEScannerBuf64K(scanBuf) defer close(events) send := func(event antigravityCompatScanEvent) bool { + if !queueBudget.acquire(len(event.line), done) { + return false + } select { case events <- event: return true case <-done: + queueBudget.release(len(event.line)) return false } } @@ -428,7 +437,7 @@ func (s *AntigravityGatewayService) startAntigravityCompatScanner( send(antigravityCompatScanEvent{err: err}) } }() - return events, func() { close(done) }, maxLineSize + return events, func() { close(done) }, maxLineSize, queueBudget } func (s *AntigravityGatewayService) antigravityCompatStreamTimeout() time.Duration { diff --git a/backend/internal/service/antigravity_gateway_streaming.go b/backend/internal/service/antigravity_gateway_streaming.go index e02541ed0d..2b5be77706 100644 --- a/backend/internal/service/antigravity_gateway_streaming.go +++ b/backend/internal/service/antigravity_gateway_streaming.go @@ -142,6 +142,7 @@ func (s *AntigravityGatewayService) handleGeminiStreamingResponse(c *gin.Context } scanBuf := getSSEScannerBuf64K() scanner.Buffer(scanBuf[:0], maxLineSize) + scanner.Split(newBoundedSSESplit(s.settingService.cfg, maxLineSize, nil)) usage := &ClaudeUsage{} var firstTokenMs *int @@ -152,11 +153,16 @@ func (s *AntigravityGatewayService) handleGeminiStreamingResponse(c *gin.Context // 独立 goroutine 读取上游,避免读取阻塞影响超时处理 events := make(chan scanEvent, 16) done := make(chan struct{}) + queueBudget := newSSEQueueBudget(s.settingService.cfg) sendEvent := func(ev scanEvent) bool { + if !queueBudget.acquire(len(ev.line), done) { + return false + } select { case events <- ev: return true case <-done: + queueBudget.release(len(ev.line)) return false } } @@ -229,6 +235,9 @@ func (s *AntigravityGatewayService) handleGeminiStreamingResponse(c *gin.Context for { select { case ev, ok := <-events: + if ok { + queueBudget.release(len(ev.line)) + } if !ok { return &antigravityStreamResult{usage: usage, firstTokenMs: firstTokenMs, clientDisconnect: cw.Disconnected()}, nil } @@ -345,6 +354,7 @@ func (s *AntigravityGatewayService) handleGeminiStreamToNonStreaming(c *gin.Cont } scanBuf := getSSEScannerBuf64K() scanner.Buffer(scanBuf[:0], maxLineSize) + scanner.Split(newBoundedSSESplit(s.settingService.cfg, maxLineSize, nil)) usage := &ClaudeUsage{} var firstTokenMs *int @@ -360,11 +370,16 @@ func (s *AntigravityGatewayService) handleGeminiStreamToNonStreaming(c *gin.Cont // 独立 goroutine 读取上游,避免读取阻塞影响超时处理 events := make(chan scanEvent, 16) done := make(chan struct{}) + queueBudget := newSSEQueueBudget(s.settingService.cfg) sendEvent := func(ev scanEvent) bool { + if !queueBudget.acquire(len(ev.line), done) { + return false + } select { case events <- ev: return true case <-done: + queueBudget.release(len(ev.line)) return false } } @@ -404,6 +419,9 @@ func (s *AntigravityGatewayService) handleGeminiStreamToNonStreaming(c *gin.Cont for { select { case ev, ok := <-events: + if ok { + queueBudget.release(len(ev.line)) + } if !ok { // 流结束,返回收集的响应 goto returnResponse @@ -756,6 +774,7 @@ func (s *AntigravityGatewayService) collectClaudeStreamResponse(c *gin.Context, } scanBuf := getSSEScannerBuf64K() scanner.Buffer(scanBuf[:0], maxLineSize) + scanner.Split(newBoundedSSESplit(s.settingService.cfg, maxLineSize, nil)) var firstTokenMs *int var last map[string]any @@ -771,11 +790,16 @@ func (s *AntigravityGatewayService) collectClaudeStreamResponse(c *gin.Context, // 独立 goroutine 读取上游,避免读取阻塞影响超时处理 events := make(chan scanEvent, 16) done := make(chan struct{}) + queueBudget := newSSEQueueBudget(s.settingService.cfg) sendEvent := func(ev scanEvent) bool { + if !queueBudget.acquire(len(ev.line), done) { + return false + } select { case events <- ev: return true case <-done: + queueBudget.release(len(ev.line)) return false } } @@ -815,6 +839,9 @@ func (s *AntigravityGatewayService) collectClaudeStreamResponse(c *gin.Context, for { select { case ev, ok := <-events: + if ok { + queueBudget.release(len(ev.line)) + } if !ok { // 流结束,转换并返回响应 goto returnResponse @@ -980,6 +1007,7 @@ func (s *AntigravityGatewayService) handleClaudeStreamingResponse(c *gin.Context } scanBuf := getSSEScannerBuf64K() scanner.Buffer(scanBuf[:0], maxLineSize) + scanner.Split(newBoundedSSESplit(s.settingService.cfg, maxLineSize, nil)) // 辅助函数:转换 antigravity.ClaudeUsage 到 service.ClaudeUsage convertUsage := func(agUsage *antigravity.ClaudeUsage) *ClaudeUsage { @@ -1001,11 +1029,16 @@ func (s *AntigravityGatewayService) handleClaudeStreamingResponse(c *gin.Context // 独立 goroutine 读取上游,避免读取阻塞影响超时处理 events := make(chan scanEvent, 16) done := make(chan struct{}) + queueBudget := newSSEQueueBudget(s.settingService.cfg) sendEvent := func(ev scanEvent) bool { + if !queueBudget.acquire(len(ev.line), done) { + return false + } select { case events <- ev: return true case <-done: + queueBudget.release(len(ev.line)) return false } } @@ -1078,6 +1111,9 @@ func (s *AntigravityGatewayService) handleClaudeStreamingResponse(c *gin.Context for { select { case ev, ok := <-events: + if ok { + queueBudget.release(len(ev.line)) + } if !ok { // 上游完成,发送结束事件 finalEvents, agUsage := processor.Finish() diff --git a/backend/internal/service/antigravity_gateway_upstream.go b/backend/internal/service/antigravity_gateway_upstream.go index e6b9a73fa8..22925c74ff 100644 --- a/backend/internal/service/antigravity_gateway_upstream.go +++ b/backend/internal/service/antigravity_gateway_upstream.go @@ -171,6 +171,7 @@ func (s *AntigravityGatewayService) streamUpstreamResponse(c *gin.Context, resp maxLineSize = s.settingService.cfg.Gateway.MaxLineSize } scanner.Buffer(make([]byte, 64*1024), maxLineSize) + scanner.Split(newBoundedSSESplit(s.settingService.cfg, maxLineSize, nil)) type scanEvent struct { line string @@ -178,11 +179,16 @@ func (s *AntigravityGatewayService) streamUpstreamResponse(c *gin.Context, resp } events := make(chan scanEvent, 16) done := make(chan struct{}) + queueBudget := newSSEQueueBudget(s.settingService.cfg) sendEvent := func(ev scanEvent) bool { + if !queueBudget.acquire(len(ev.line), done) { + return false + } select { case events <- ev: return true case <-done: + queueBudget.release(len(ev.line)) return false } } @@ -238,6 +244,9 @@ func (s *AntigravityGatewayService) streamUpstreamResponse(c *gin.Context, resp for { select { case ev, ok := <-events: + if ok { + queueBudget.release(len(ev.line)) + } if !ok { return &antigravityStreamResult{usage: usage, firstTokenMs: firstTokenMs, clientDisconnect: cw.Disconnected()} } diff --git a/backend/internal/service/balance_notify_check_test.go b/backend/internal/service/balance_notify_check_test.go index 7bb4cf9e7f..9035737fe6 100644 --- a/backend/internal/service/balance_notify_check_test.go +++ b/backend/internal/service/balance_notify_check_test.go @@ -240,8 +240,8 @@ func TestCheckQuotaDimCrossings_NoDimensions(t *testing.T) { s, _ := newBalanceNotifyServiceForTest() account := &Account{ID: 1, Name: "test", Platform: PlatformAnthropic} // Empty dims → no crossing, no panic. - s.checkQuotaDimCrossings(account, nil, 10, []string{"admin@example.com"}, "TestSite") - s.checkQuotaDimCrossings(account, []quotaDim{}, 10, []string{"admin@example.com"}, "TestSite") + s.checkQuotaDimCrossings(context.Background(), account, nil, 10, []string{"admin@example.com"}, "TestSite") + s.checkQuotaDimCrossings(context.Background(), account, []quotaDim{}, 10, []string{"admin@example.com"}, "TestSite") } func TestCheckQuotaDimCrossings_DisabledDimension(t *testing.T) { @@ -258,7 +258,7 @@ func TestCheckQuotaDimCrossings_DisabledDimension(t *testing.T) { }, } // Disabled dimension should be skipped even if crossing would occur. - s.checkQuotaDimCrossings(account, dims, 50, []string{"admin@example.com"}, "TestSite") + s.checkQuotaDimCrossings(context.Background(), account, dims, 50, []string{"admin@example.com"}, "TestSite") } func TestCheckQuotaDimCrossings_ZeroThresholdSkipped(t *testing.T) { @@ -275,7 +275,7 @@ func TestCheckQuotaDimCrossings_ZeroThresholdSkipped(t *testing.T) { }, } // Zero threshold → skipped. - s.checkQuotaDimCrossings(account, dims, 50, []string{"admin@example.com"}, "TestSite") + s.checkQuotaDimCrossings(context.Background(), account, dims, 50, []string{"admin@example.com"}, "TestSite") } func TestCheckQuotaDimCrossings_NoCrossing_BothBelowThreshold(t *testing.T) { @@ -293,7 +293,7 @@ func TestCheckQuotaDimCrossings_NoCrossing_BothBelowThreshold(t *testing.T) { limit: 1000, }, } - s.checkQuotaDimCrossings(account, dims, 50, []string{"admin@example.com"}, "TestSite") + s.checkQuotaDimCrossings(context.Background(), account, dims, 50, []string{"admin@example.com"}, "TestSite") } func TestCheckQuotaDimCrossings_NoCrossing_BothAboveThreshold(t *testing.T) { @@ -311,7 +311,7 @@ func TestCheckQuotaDimCrossings_NoCrossing_BothAboveThreshold(t *testing.T) { limit: 1000, }, } - s.checkQuotaDimCrossings(account, dims, 50, []string{"admin@example.com"}, "TestSite") + s.checkQuotaDimCrossings(context.Background(), account, dims, 50, []string{"admin@example.com"}, "TestSite") } func TestCheckQuotaDimCrossings_NegativeResolvedThreshold_Skipped(t *testing.T) { @@ -329,7 +329,7 @@ func TestCheckQuotaDimCrossings_NegativeResolvedThreshold_Skipped(t *testing.T) limit: 1000, }, } - s.checkQuotaDimCrossings(account, dims, 50, []string{"admin@example.com"}, "TestSite") + s.checkQuotaDimCrossings(context.Background(), account, dims, 50, []string{"admin@example.com"}, "TestSite") } func TestCheckQuotaDimCrossings_PercentageThreshold_NoCrossing(t *testing.T) { @@ -347,7 +347,7 @@ func TestCheckQuotaDimCrossings_PercentageThreshold_NoCrossing(t *testing.T) { limit: 1000, }, } - s.checkQuotaDimCrossings(account, dims, 50, []string{"admin@example.com"}, "TestSite") + s.checkQuotaDimCrossings(context.Background(), account, dims, 50, []string{"admin@example.com"}, "TestSite") } func TestCheckQuotaDimCrossings_ZeroLimit_Skipped(t *testing.T) { @@ -364,7 +364,7 @@ func TestCheckQuotaDimCrossings_ZeroLimit_Skipped(t *testing.T) { limit: 0, }, } - s.checkQuotaDimCrossings(account, dims, 50, []string{"admin@example.com"}, "TestSite") + s.checkQuotaDimCrossings(context.Background(), account, dims, 50, []string{"admin@example.com"}, "TestSite") } func TestCheckQuotaDimCrossings_MultipleDims_MixedResults(t *testing.T) { @@ -400,5 +400,5 @@ func TestCheckQuotaDimCrossings_MultipleDims_MixedResults(t *testing.T) { }, } // None should trigger. No panic expected. - s.checkQuotaDimCrossings(account, dims, 50, []string{"admin@example.com"}, "TestSite") + s.checkQuotaDimCrossings(context.Background(), account, dims, 50, []string{"admin@example.com"}, "TestSite") } diff --git a/backend/internal/service/balance_notify_service.go b/backend/internal/service/balance_notify_service.go index 268032750a..b7c43f84b9 100644 --- a/backend/internal/service/balance_notify_service.go +++ b/backend/internal/service/balance_notify_service.go @@ -43,14 +43,16 @@ type BalanceNotifyService struct { settingRepo SettingRepository accountRepo AccountQuotaReader notificationEmailService *NotificationEmailService + usageNotifications *usageNotificationWorker } // NewBalanceNotifyService creates a new BalanceNotifyService. func NewBalanceNotifyService(emailService *EmailService, settingRepo SettingRepository, accountRepo AccountQuotaReader) *BalanceNotifyService { return &BalanceNotifyService{ - emailService: emailService, - settingRepo: settingRepo, - accountRepo: accountRepo, + emailService: emailService, + settingRepo: settingRepo, + accountRepo: accountRepo, + usageNotifications: newUsageNotificationWorker(), } } @@ -118,20 +120,13 @@ func crossedDownward(oldV, newV, threshold float64) bool { return oldV >= threshold && newV < threshold } -// dispatchBalanceLowEmail collects recipients and sends the alert in a goroutine. +// dispatchBalanceLowEmail sends within the bounded notification task. func (s *BalanceNotifyService) dispatchBalanceLowEmail(ctx context.Context, user *User, newBalance, threshold float64, rechargeURL string) { siteName := s.getSiteName(ctx) recipients := s.collectBalanceNotifyRecipients(user) slog.Info("CheckBalanceAfterDeduction: sending notification", "user_id", user.ID, "recipients", recipients, "new_balance", newBalance, "threshold", threshold) - go func() { - defer func() { - if r := recover(); r != nil { - slog.Error("panic in balance notification", "recover", r) - } - }() - s.sendBalanceLowEmails(recipients, user.ID, user.Username, user.Email, newBalance, threshold, siteName, rechargeURL) - }() + s.sendBalanceLowEmails(ctx, recipients, user.ID, user.Username, user.Email, newBalance, threshold, siteName, rechargeURL) } // quotaDim describes one quota dimension for notification checking. @@ -201,7 +196,7 @@ func (s *BalanceNotifyService) CheckAccountQuotaAfterIncrement(ctx context.Conte dims = buildQuotaDims(freshAccount) account = freshAccount // use fresh data for alert metadata } - s.checkQuotaDimCrossings(account, dims, cost, adminEmails, siteName) + s.checkQuotaDimCrossings(ctx, account, dims, cost, adminEmails, siteName) } // fetchFreshAccount loads the latest account from DB; falls back to the snapshot on error. @@ -220,7 +215,7 @@ func (s *BalanceNotifyService) fetchFreshAccount(ctx context.Context, snapshot * // checkQuotaDimCrossings iterates pre-built quota dimensions and sends alerts for threshold crossings. // Pre-increment value is reconstructed as currentUsed - cost to detect the crossing moment. -func (s *BalanceNotifyService) checkQuotaDimCrossings(account *Account, dims []quotaDim, cost float64, adminEmails []string, siteName string) { +func (s *BalanceNotifyService) checkQuotaDimCrossings(ctx context.Context, account *Account, dims []quotaDim, cost float64, adminEmails []string, siteName string) { for _, dim := range dims { if !dim.enabled || dim.threshold <= 0 { continue @@ -232,23 +227,11 @@ func (s *BalanceNotifyService) checkQuotaDimCrossings(account *Account, dims []q newUsed := dim.currentUsed oldUsed := dim.currentUsed - cost if oldUsed < effectiveThreshold && newUsed >= effectiveThreshold { - s.asyncSendQuotaAlert(adminEmails, account.ID, account.Name, account.Platform, dim, newUsed, effectiveThreshold, siteName) + s.sendQuotaAlertEmails(ctx, adminEmails, account.ID, account.Name, account.Platform, dim, newUsed, siteName) } } } -// asyncSendQuotaAlert sends quota alert email in a goroutine with panic recovery. -func (s *BalanceNotifyService) asyncSendQuotaAlert(adminEmails []string, accountID int64, accountName, platform string, dim quotaDim, newUsed, effectiveThreshold float64, siteName string) { - go func() { - defer func() { - if r := recover(); r != nil { - slog.Error("panic in quota notification", "recover", r) - } - }() - s.sendQuotaAlertEmails(adminEmails, accountID, accountName, platform, dim, newUsed, siteName) - }() -} - // getBalanceNotifyConfig reads global balance notification settings. func (s *BalanceNotifyService) getBalanceNotifyConfig(ctx context.Context) (enabled bool, threshold float64, rechargeURL string) { keys := []string{SettingKeyBalanceLowNotifyEnabled, SettingKeyBalanceLowNotifyThreshold, SettingKeyBalanceLowNotifyRechargeURL} @@ -329,13 +312,16 @@ func (s *BalanceNotifyService) collectBalanceNotifyRecipients(user *User) []stri } // sendEmails sends an email to all recipients with shared timeout and error logging. -func (s *BalanceNotifyService) sendEmails(recipients []string, subject, body string, logAttrs ...any) { +func (s *BalanceNotifyService) sendEmails(parent context.Context, recipients []string, subject, body string, logAttrs ...any) { if len(recipients) == 0 { slog.Warn("sendEmails: no recipients", "subject", subject) return } for _, to := range recipients { - ctx, cancel := context.WithTimeout(context.Background(), emailSendTimeout) + if parent.Err() != nil { + return + } + ctx, cancel := context.WithTimeout(parent, emailSendTimeout) if err := s.emailService.SendEmail(ctx, to, subject, body); err != nil { attrs := append([]any{"to", to, "error", err}, logAttrs...) slog.Error("failed to send notification", attrs...) @@ -347,7 +333,7 @@ func (s *BalanceNotifyService) sendEmails(recipients []string, subject, body str } // sendBalanceLowEmails sends balance low notification to all recipients. -func (s *BalanceNotifyService) sendBalanceLowEmails(recipients []string, userID int64, userName, userEmail string, balance, threshold float64, siteName, rechargeURL string) { +func (s *BalanceNotifyService) sendBalanceLowEmails(parent context.Context, recipients []string, userID int64, userName, userEmail string, balance, threshold float64, siteName, rechargeURL string) { displayName := userName if displayName == "" { displayName = userEmail @@ -355,7 +341,10 @@ func (s *BalanceNotifyService) sendBalanceLowEmails(recipients []string, userID if s.notificationEmailService != nil { fallbackRecipients := make([]string, 0, len(recipients)) for _, to := range recipients { - ctx, cancel := context.WithTimeout(context.Background(), emailSendTimeout) + if parent.Err() != nil { + return + } + ctx, cancel := context.WithTimeout(parent, emailSendTimeout) err := s.notificationEmailService.Send(ctx, NotificationEmailSendInput{ Event: NotificationEmailEventBalanceLow, RecipientEmail: to, @@ -387,11 +376,11 @@ func (s *BalanceNotifyService) sendBalanceLowEmails(recipients []string, userID } subject := fmt.Sprintf("[%s] 余额不足提醒 / Balance Low Alert", sanitizeEmailHeader(siteName)) body := s.buildBalanceLowEmailBody(html.EscapeString(displayName), balance, threshold, html.EscapeString(siteName), rechargeURL) - s.sendEmails(recipients, subject, body, "user_email", userEmail, "balance", balance) + s.sendEmails(parent, recipients, subject, body, "user_email", userEmail, "balance", balance) } // sendQuotaAlertEmails sends quota alert notification to admin emails. -func (s *BalanceNotifyService) sendQuotaAlertEmails(adminEmails []string, accountID int64, accountName, platform string, dim quotaDim, used float64, siteName string) { +func (s *BalanceNotifyService) sendQuotaAlertEmails(parent context.Context, adminEmails []string, accountID int64, accountName, platform string, dim quotaDim, used float64, siteName string) { dimLabel := quotaDimLabels[dim.name] if dimLabel == "" { dimLabel = dim.name @@ -410,7 +399,10 @@ func (s *BalanceNotifyService) sendQuotaAlertEmails(adminEmails []string, accoun if s.notificationEmailService != nil { fallbackRecipients := make([]string, 0, len(adminEmails)) for _, to := range adminEmails { - ctx, cancel := context.WithTimeout(context.Background(), emailSendTimeout) + if parent.Err() != nil { + return + } + ctx, cancel := context.WithTimeout(parent, emailSendTimeout) err := s.notificationEmailService.Send(ctx, NotificationEmailSendInput{ Event: NotificationEmailEventAccountQuotaAlert, RecipientEmail: to, @@ -447,7 +439,7 @@ func (s *BalanceNotifyService) sendQuotaAlertEmails(adminEmails []string, accoun subject := fmt.Sprintf("[%s] 账号限额告警 / Account Quota Alert - %s", sanitizeEmailHeader(siteName), sanitizeEmailHeader(accountName)) body := s.buildQuotaAlertEmailBody(accountID, html.EscapeString(accountName), html.EscapeString(platform), html.EscapeString(dimLabel), used, dim.limit, remaining, thresholdDisplay, html.EscapeString(siteName)) - s.sendEmails(adminEmails, subject, body, "account", accountName, "dimension", dim.name) + s.sendEmails(parent, adminEmails, subject, body, "account", accountName, "dimension", dim.name) } // sanitizeEmailHeader removes CR/LF characters to prevent SMTP header injection. diff --git a/backend/internal/service/bedrock_stream.go b/backend/internal/service/bedrock_stream.go index 9ce6b87e24..3656628c22 100644 --- a/backend/internal/service/bedrock_stream.go +++ b/backend/internal/service/bedrock_stream.go @@ -60,11 +60,16 @@ func (s *GatewayService) handleBedrockStreamingResponse( } events := make(chan decodeEvent, 16) done := make(chan struct{}) + queueBudget := newSSEQueueBudget(s.cfg) sendEvent := func(ev decodeEvent) bool { + if !queueBudget.acquire(len(ev.payload), done) { + return false + } select { case events <- ev: return true case <-done: + queueBudget.release(len(ev.payload)) return false } } @@ -107,6 +112,9 @@ func (s *GatewayService) handleBedrockStreamingResponse( for { select { case ev, ok := <-events: + if ok { + queueBudget.release(len(ev.payload)) + } if !ok { if !clientDisconnected { flusher.Flush() diff --git a/backend/internal/service/billing_cache_service.go b/backend/internal/service/billing_cache_service.go index ea22efe2eb..b4734f1e17 100644 --- a/backend/internal/service/billing_cache_service.go +++ b/backend/internal/service/billing_cache_service.go @@ -714,7 +714,7 @@ func (s *BillingCacheService) QueueUpdateAPIKeyRateLimitUsage(apiKeyID int64, co // 把 TOCTOU 超支窗口限制在并发 in-flight 请求数量内(而非随时间无限累积)。 // 写延迟通常 < 1ms(本地 Redis),换取 quota 视图实时性的取舍合理。 // -// Redis 写失败用 ALERT 级 log;DB 持久化由 caller 单独 goroutine 兜底(gateway_service.go)。 +// Redis 写失败用 ALERT 级 log;DB 持久化由计费 worker 内同步执行或批量 flusher 处理。 func (s *BillingCacheService) IncrementUserPlatformQuotaUsage(userID int64, platform string, cost float64) { if s.cache == nil { return diff --git a/backend/internal/service/billing_notification_worker.go b/backend/internal/service/billing_notification_worker.go new file mode 100644 index 0000000000..c82eca212e --- /dev/null +++ b/backend/internal/service/billing_notification_worker.go @@ -0,0 +1,103 @@ +package service + +import ( + "context" + "log/slog" + "sync" + "sync/atomic" + "time" + + "github.com/alitto/pond/v2" +) + +const ( + usageNotificationWorkers = 4 + usageNotificationQueueSize = 128 + usageNotificationTimeout = 30 * time.Second +) + +// Notification work is best effort and must not create an unbounded queue or +// compete with committed-charge persistence for usage workers. A task includes +// both settings reads and email delivery, including all quota dimensions. +type usageNotificationWorker struct { + pool pond.Pool + ctx context.Context + cancel context.CancelFunc + stopOnce sync.Once + dropped atomic.Uint64 + lastDropLog atomic.Int64 +} + +func newUsageNotificationWorker() *usageNotificationWorker { + ctx, cancel := context.WithCancel(context.Background()) + return &usageNotificationWorker{ + pool: pond.NewPool(usageNotificationWorkers, pond.WithQueueSize(usageNotificationQueueSize)), + ctx: ctx, + cancel: cancel, + } +} + +func (w *usageNotificationWorker) submit(task func(context.Context)) bool { + if w == nil || task == nil { + return false + } + _, accepted := w.pool.TrySubmit(func() { + if w.ctx.Err() != nil { + return + } + ctx, cancel := context.WithTimeout(w.ctx, usageNotificationTimeout) + defer cancel() + defer func() { + if recovered := recover(); recovered != nil { + slog.Error("panic in usage notification", "recover", recovered) + } + }() + task(ctx) + }) + if !accepted { + count := w.dropped.Add(1) + now := time.Now().UnixNano() + last := w.lastDropLog.Load() + if now-last >= int64(5*time.Second) && w.lastDropLog.CompareAndSwap(last, now) { + slog.Warn("usage notification queue unavailable; notification skipped", "dropped_total", count) + } + } + return accepted +} + +func (w *usageNotificationWorker) stop() { + if w == nil { + return + } + w.stopOnce.Do(func() { + // Cancel settings reads and discard queued notifications during shutdown. + // Active SMTP calls also have their own dial and I/O deadlines. + w.cancel() + w.pool.StopAndWait() + }) +} + +func (s *BalanceNotifyService) submitUsageNotifications(p *postUsageBillingParams, deps *billingDeps, result *UsageBillingApplyResult) { + if s == nil || s.usageNotifications == nil || p == nil || p.Cost == nil { + return + } + balanceEnabled := !p.IsSubscriptionBill && p.Cost.ActualCost > 0 && s.canNotifyBalance(p.User) + quotaEnabled := p.Cost.TotalCost > 0 && p.Account != nil && p.Account.SupportsAccountQuota() && p.Account.HasAnyQuotaLimit() + if !balanceEnabled && !quotaEnabled { + return + } + s.usageNotifications.submit(func(ctx context.Context) { + notifyBalanceLow(ctx, p, deps, result) + if ctx.Err() == nil { + notifyAccountQuota(ctx, p, deps, result) + } + }) +} + +// Stop cancels notification work and waits for the bounded workers to exit. +// Billing persistence belongs to usage tasks and is never dropped here. +func (s *BalanceNotifyService) Stop() { + if s != nil { + s.usageNotifications.stop() + } +} diff --git a/backend/internal/service/billing_notification_worker_test.go b/backend/internal/service/billing_notification_worker_test.go new file mode 100644 index 0000000000..cc0c6b7f9c --- /dev/null +++ b/backend/internal/service/billing_notification_worker_test.go @@ -0,0 +1,76 @@ +package service + +import ( + "context" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestUsageNotificationsBoundWorkAndCancelOnStop(t *testing.T) { + w := newUsageNotificationWorker() + t.Cleanup(w.stop) + started := make(chan context.Context, usageNotificationWorkers) + var running, queuedRan atomic.Int64 + for range usageNotificationWorkers { + require.True(t, w.submit(func(ctx context.Context) { + running.Add(1) + defer running.Add(-1) + started <- ctx + <-ctx.Done() + })) + } + for range usageNotificationWorkers { + select { + case ctx := <-started: + deadline, ok := ctx.Deadline() + require.True(t, ok) + require.InDelta(t, usageNotificationTimeout.Seconds(), time.Until(deadline).Seconds(), 2) + case <-time.After(2 * time.Second): + t.Fatal("notification worker did not start") + } + } + for range usageNotificationQueueSize { + require.True(t, w.submit(func(context.Context) { queuedRan.Add(1) })) + } + require.False(t, w.submit(func(context.Context) { queuedRan.Add(1) })) + require.Equal(t, int64(usageNotificationWorkers), running.Load()) + require.Equal(t, uint64(1), w.dropped.Load()) + + w.stop() + w.stop() + require.Zero(t, running.Load()) + require.Zero(t, queuedRan.Load(), "shutdown must not start queued settings reads or email deliveries") + require.False(t, w.submit(func(context.Context) { t.Error("stopped worker accepted work") })) +} + +type notificationCancellationSettings struct { + SettingRepository + started chan context.Context +} + +func (s *notificationCancellationSettings) GetMultiple(ctx context.Context, _ []string) (map[string]string, error) { + s.started <- ctx + <-ctx.Done() + return nil, ctx.Err() +} + +func TestBalanceNotifyStopCancelsSettingsReads(t *testing.T) { + settings := ¬ificationCancellationSettings{started: make(chan context.Context, 1)} + s := NewBalanceNotifyService(NewEmailService(settings, nil), settings, nil) + t.Cleanup(s.Stop) + s.submitUsageNotifications(&postUsageBillingParams{ + Cost: &CostBreakdown{ActualCost: 1}, + User: &User{ID: 1, BalanceNotifyEnabled: true}, + }, &billingDeps{balanceNotifyService: s}, nil) + select { + case ctx := <-settings.started: + _, ok := ctx.Deadline() + require.True(t, ok) + case <-time.After(2 * time.Second): + t.Fatal("notification settings read did not start") + } + s.Stop() +} diff --git a/backend/internal/service/digest_session_store.go b/backend/internal/service/digest_session_store.go index 3ac0893689..30a1c7f626 100644 --- a/backend/internal/service/digest_session_store.go +++ b/backend/internal/service/digest_session_store.go @@ -4,8 +4,6 @@ import ( "strconv" "strings" "time" - - gocache "github.com/patrickmn/go-cache" ) // digestSessionTTL 摘要会话默认 TTL @@ -15,52 +13,61 @@ const digestSessionTTL = 5 * time.Minute type sessionEntry struct { uuid string accountID int64 + expiresAt time.Time } -// DigestSessionStore 内存摘要会话存储(flat cache 实现) +func (e *sessionEntry) sessionExpiresAt() time.Time { return e.expiresAt } +func (e *sessionEntry) sessionCost() int { return len(e.uuid) } +func (e *sessionEntry) cloneSessionValue() sessionMemoryValue { + cloned := *e + cloned.uuid = strings.Clone(e.uuid) + return &cloned +} + +// DigestSessionStore 内存摘要会话存储(有界 TTL 缓存,增量摘要索引) // key: "{groupID}:{prefixHash}|{digestChain}" → *sessionEntry type DigestSessionStore struct { - cache *gocache.Cache + cache sessionMemoryCache + ttl time.Duration } // NewDigestSessionStore 创建内存摘要会话存储 func NewDigestSessionStore() *DigestSessionStore { return &DigestSessionStore{ - cache: gocache.New(digestSessionTTL, time.Minute), + ttl: digestSessionTTL, } } +func (s *DigestSessionStore) Close() { s.cache.Close() } + // Save 保存摘要会话。oldDigestChain 为 Find 返回的 matchedChain,用于删旧 key。 func (s *DigestSessionStore) Save(groupID int64, prefixHash, digestChain, uuid string, accountID int64, oldDigestChain string) { if digestChain == "" { return } ns := buildNS(groupID, prefixHash) - s.cache.Set(ns+digestChain, &sessionEntry{uuid: uuid, accountID: accountID}, gocache.DefaultExpiration) + ttl := s.ttl + if ttl <= 0 { + ttl = digestSessionTTL + } + s.cache.Store(ns+digestChain, &sessionEntry{uuid: uuid, accountID: accountID, expiresAt: time.Now().Add(ttl)}) if oldDigestChain != "" && oldDigestChain != digestChain { s.cache.Delete(ns + oldDigestChain) } } -// Find 查找摘要会话,从完整 chain 逐段截断,返回最长匹配及对应 matchedChain。 +// Find 查找摘要会话,在消息边界上返回最长匹配及对应 matchedChain。 func (s *DigestSessionStore) Find(groupID int64, prefixHash, digestChain string) (uuid string, accountID int64, matchedChain string, found bool) { if digestChain == "" { return "", 0, "", false } ns := buildNS(groupID, prefixHash) - chain := digestChain - for { - if val, ok := s.cache.Get(ns + chain); ok { - if e, ok := val.(*sessionEntry); ok { - return e.uuid, e.accountID, chain, true - } + if val, chain, ok := s.cache.longestDigestPrefix(ns, digestChain); ok { + if e, ok := val.(*sessionEntry); ok { + return e.uuid, e.accountID, chain, true } - i := strings.LastIndex(chain, "-") - if i < 0 { - return "", 0, "", false - } - chain = chain[:i] } + return "", 0, "", false } // buildNS 构建 namespace 前缀 diff --git a/backend/internal/service/digest_session_store_test.go b/backend/internal/service/digest_session_store_test.go index e505bf30be..f1d5b96a4c 100644 --- a/backend/internal/service/digest_session_store_test.go +++ b/backend/internal/service/digest_session_store_test.go @@ -8,13 +8,13 @@ import ( "testing" "time" - gocache "github.com/patrickmn/go-cache" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestDigestSessionStore_SaveAndFind(t *testing.T) { store := NewDigestSessionStore() + t.Cleanup(store.Close) store.Save(1, "prefix", "s:a1-u:b2-m:c3", "uuid-1", 100, "") @@ -26,6 +26,7 @@ func TestDigestSessionStore_SaveAndFind(t *testing.T) { func TestDigestSessionStore_PrefixMatch(t *testing.T) { store := NewDigestSessionStore() + t.Cleanup(store.Close) // 保存短链 store.Save(1, "prefix", "u:a-m:b", "uuid-short", 10, "") @@ -40,6 +41,7 @@ func TestDigestSessionStore_PrefixMatch(t *testing.T) { func TestDigestSessionStore_LongestPrefixMatch(t *testing.T) { store := NewDigestSessionStore() + t.Cleanup(store.Close) store.Save(1, "prefix", "u:a", "uuid-1", 1, "") store.Save(1, "prefix", "u:a-m:b", "uuid-2", 2, "") @@ -60,6 +62,7 @@ func TestDigestSessionStore_LongestPrefixMatch(t *testing.T) { func TestDigestSessionStore_SaveDeletesOldChain(t *testing.T) { store := NewDigestSessionStore() + t.Cleanup(store.Close) // 第一轮:保存 "u:a-m:b" store.Save(1, "prefix", "u:a-m:b", "uuid-1", 100, "") @@ -80,6 +83,7 @@ func TestDigestSessionStore_SaveDeletesOldChain(t *testing.T) { func TestDigestSessionStore_DifferentSessionsNoInterference(t *testing.T) { store := NewDigestSessionStore() + t.Cleanup(store.Close) // 相同系统提示词,不同用户提示词 store.Save(1, "prefix", "s:sys-u:user1", "uuid-1", 100, "") @@ -98,6 +102,7 @@ func TestDigestSessionStore_DifferentSessionsNoInterference(t *testing.T) { func TestDigestSessionStore_NoMatch(t *testing.T) { store := NewDigestSessionStore() + t.Cleanup(store.Close) store.Save(1, "prefix", "u:a-m:b", "uuid-1", 100, "") @@ -108,6 +113,7 @@ func TestDigestSessionStore_NoMatch(t *testing.T) { func TestDigestSessionStore_DifferentPrefixHash(t *testing.T) { store := NewDigestSessionStore() + t.Cleanup(store.Close) store.Save(1, "prefix1", "u:a-m:b", "uuid-1", 100, "") @@ -118,6 +124,7 @@ func TestDigestSessionStore_DifferentPrefixHash(t *testing.T) { func TestDigestSessionStore_DifferentGroupID(t *testing.T) { store := NewDigestSessionStore() + t.Cleanup(store.Close) store.Save(1, "prefix", "u:a-m:b", "uuid-1", 100, "") @@ -128,6 +135,7 @@ func TestDigestSessionStore_DifferentGroupID(t *testing.T) { func TestDigestSessionStore_EmptyDigestChain(t *testing.T) { store := NewDigestSessionStore() + t.Cleanup(store.Close) // 空链不应保存 store.Save(1, "prefix", "", "uuid-1", 100, "") @@ -137,8 +145,10 @@ func TestDigestSessionStore_EmptyDigestChain(t *testing.T) { func TestDigestSessionStore_TTLExpiration(t *testing.T) { store := &DigestSessionStore{ - cache: gocache.New(100*time.Millisecond, 50*time.Millisecond), + cache: sessionMemoryCache{sweep: 50 * time.Millisecond}, + ttl: 100 * time.Millisecond, } + t.Cleanup(store.Close) store.Save(1, "prefix", "u:a-m:b", "uuid-1", 100, "") @@ -156,6 +166,7 @@ func TestDigestSessionStore_TTLExpiration(t *testing.T) { func TestDigestSessionStore_ConcurrentSafety(t *testing.T) { store := NewDigestSessionStore() + t.Cleanup(store.Close) var wg sync.WaitGroup const goroutines = 50 @@ -179,6 +190,7 @@ func TestDigestSessionStore_ConcurrentSafety(t *testing.T) { func TestDigestSessionStore_MultipleSessions(t *testing.T) { store := NewDigestSessionStore() + t.Cleanup(store.Close) sessions := []struct { chain string @@ -211,6 +223,7 @@ func TestDigestSessionStore_MultipleSessions(t *testing.T) { func TestDigestSessionStore_Performance1000Sessions(t *testing.T) { store := NewDigestSessionStore() + t.Cleanup(store.Close) // 插入 1000 个会话 for i := 0; i < 1000; i++ { @@ -233,6 +246,7 @@ func TestDigestSessionStore_Performance1000Sessions(t *testing.T) { func TestDigestSessionStore_FindReturnsMatchedChain(t *testing.T) { store := NewDigestSessionStore() + t.Cleanup(store.Close) store.Save(1, "prefix", "u:a-m:b-u:c", "uuid-1", 100, "") @@ -249,6 +263,7 @@ func TestDigestSessionStore_FindReturnsMatchedChain(t *testing.T) { func TestDigestSessionStore_CacheItemCountStable(t *testing.T) { store := NewDigestSessionStore() + t.Cleanup(store.Close) // 模拟 100 个独立会话,每个进行 10 轮对话 // 正确传递 oldDigestChain 时,每个会话始终只保留 1 个 key @@ -278,8 +293,10 @@ func TestDigestSessionStore_CacheItemCountStable(t *testing.T) { func TestDigestSessionStore_TTLPreventsUnboundedGrowth(t *testing.T) { // 使用极短 TTL 验证大量写入后 cache 能被清理 store := &DigestSessionStore{ - cache: gocache.New(100*time.Millisecond, 50*time.Millisecond), + cache: sessionMemoryCache{sweep: 50 * time.Millisecond}, + ttl: 100 * time.Millisecond, } + t.Cleanup(store.Close) // 插入 500 个不同的 key(无 oldDigestChain,模拟最坏场景:全是新会话首轮) for i := 0; i < 500; i++ { @@ -297,6 +314,7 @@ func TestDigestSessionStore_TTLPreventsUnboundedGrowth(t *testing.T) { func TestDigestSessionStore_SaveSameChainNoDelete(t *testing.T) { store := NewDigestSessionStore() + t.Cleanup(store.Close) // 保存 chain store.Save(1, "prefix", "u:a-m:b", "uuid-1", 100, "") diff --git a/backend/internal/service/gateway_anthropic_passthrough.go b/backend/internal/service/gateway_anthropic_passthrough.go index 889e2faa36..faca0a12c7 100644 --- a/backend/internal/service/gateway_anthropic_passthrough.go +++ b/backend/internal/service/gateway_anthropic_passthrough.go @@ -422,6 +422,7 @@ func (s *GatewayService) handleStreamingResponseAnthropicAPIKeyPassthrough( } scanBuf := getSSEScannerBuf64K() scanner.Buffer(scanBuf[:0], maxLineSize) + scanner.Split(newBoundedSSESplit(s.cfg, maxLineSize, nil)) type scanEvent struct { line string @@ -429,11 +430,16 @@ func (s *GatewayService) handleStreamingResponseAnthropicAPIKeyPassthrough( } events := make(chan scanEvent, 16) done := make(chan struct{}) + queueBudget := newSSEQueueBudget(s.cfg) sendEvent := func(ev scanEvent) bool { + if !queueBudget.acquire(len(ev.line), done) { + return false + } select { case events <- ev: return true case <-done: + queueBudget.release(len(ev.line)) return false } } @@ -499,6 +505,9 @@ func (s *GatewayService) handleStreamingResponseAnthropicAPIKeyPassthrough( for { select { case ev, ok := <-events: + if ok { + queueBudget.release(len(ev.line)) + } if !ok { if !clientDisconnected { // 兜底补刷,确保最后一个未以空行结尾的事件也能及时送达客户端。 diff --git a/backend/internal/service/gateway_forward_as_chat_completions.go b/backend/internal/service/gateway_forward_as_chat_completions.go index 24a281d612..f2e3f0027e 100644 --- a/backend/internal/service/gateway_forward_as_chat_completions.go +++ b/backend/internal/service/gateway_forward_as_chat_completions.go @@ -243,9 +243,11 @@ func (s *GatewayService) handleCCBufferedFromAnthropic( maxLineSize = s.cfg.Gateway.MaxLineSize } scanner.Buffer(make([]byte, 0, 64*1024), maxLineSize) + scanner.Split(newBoundedSSESplit(s.cfg, maxLineSize, nil)) var finalResp *apicompat.AnthropicResponse var usage ClaudeUsage + streamStatus := &anthropicCompatStream{body: resp.Body} for scanner.Scan() { line := scanner.Text() @@ -268,6 +270,11 @@ func (s *GatewayService) handleCCBufferedFromAnthropic( continue } + streamStatus.observe(&event, payload) + if streamStatus.upstreamErrType != "" { + break + } + // message_start carries the initial response structure and cache usage if event.Type == "message_start" && event.Message != nil { finalResp = event.Message @@ -310,6 +317,17 @@ func (s *GatewayService) handleCCBufferedFromAnthropic( } } + streamStatus.readErr = scanner.Err() + if failure := streamStatus.failure(); failure != nil { + _ = resp.Body.Close() + writeGatewayCCError(c, http.StatusBadGateway, "server_error", failure.message) + return &ForwardResult{ + RequestID: requestID, UpstreamHeaders: resp.Header, Usage: usage, + Model: originalModel, UpstreamModel: mappedModel, ReasoningEffort: reasoningEffort, + Duration: time.Since(startTime), + }, failure.err + } + if finalResp == nil { writeGatewayCCError(c, http.StatusBadGateway, "server_error", "Upstream stream ended without a response") return nil, fmt.Errorf("upstream stream ended without response") diff --git a/backend/internal/service/gateway_forward_as_responses.go b/backend/internal/service/gateway_forward_as_responses.go index f7f4897d5a..802d090457 100644 --- a/backend/internal/service/gateway_forward_as_responses.go +++ b/backend/internal/service/gateway_forward_as_responses.go @@ -392,10 +392,12 @@ func (s *GatewayService) handleResponsesBufferedStreamingResponse( maxLineSize = s.cfg.Gateway.MaxLineSize } scanner.Buffer(make([]byte, 0, 64*1024), maxLineSize) + scanner.Split(newBoundedSSESplit(s.cfg, maxLineSize, nil)) // Accumulate the final Anthropic response from streaming events var finalResp *apicompat.AnthropicResponse var usage ClaudeUsage + streamStatus := &anthropicCompatStream{body: resp.Body} for scanner.Scan() { line := scanner.Text() @@ -424,6 +426,11 @@ func (s *GatewayService) handleResponsesBufferedStreamingResponse( continue } + streamStatus.observe(&event, payload) + if streamStatus.upstreamErrType != "" { + break + } + // message_start carries the initial response structure if event.Type == "message_start" && event.Message != nil { finalResp = event.Message @@ -470,6 +477,17 @@ func (s *GatewayService) handleResponsesBufferedStreamingResponse( } } + streamStatus.readErr = scanner.Err() + if failure := streamStatus.failure(); failure != nil { + _ = resp.Body.Close() + writeResponsesError(c, http.StatusBadGateway, "server_error", failure.message) + return &ForwardResult{ + RequestID: requestID, UpstreamHeaders: resp.Header, Usage: usage, + Model: originalModel, UpstreamModel: mappedModel, ReasoningEffort: reasoningEffort, + Duration: time.Since(startTime), + }, failure.err + } + if finalResp == nil { writeResponsesError(c, http.StatusBadGateway, "server_error", "Upstream stream ended without a response") return nil, fmt.Errorf("upstream stream ended without response") diff --git a/backend/internal/service/gateway_forward_compat_stream.go b/backend/internal/service/gateway_forward_compat_stream.go index 7be3e85c35..0f9c43d1ca 100644 --- a/backend/internal/service/gateway_forward_compat_stream.go +++ b/backend/internal/service/gateway_forward_compat_stream.go @@ -65,8 +65,9 @@ func newAnthropicCompatStream(cfg *config.Config, c *gin.Context, resp *http.Res maxLineSize = cfg.Gateway.MaxLineSize } scanner.Buffer(make([]byte, 0, 64*1024), maxLineSize) + scanner.Split(newBoundedSSESplit(cfg, maxLineSize, nil)) stream := &anthropicCompatStream{ - pump: newAnthropicNativeLinePump(scanner, anthropicNativeStreamInterval(cfg)), + pump: newAnthropicNativeLinePump(scanner, anthropicNativeStreamInterval(cfg), cfg), body: resp.Body, maxLineSize: maxLineSize, logPrefix: logPrefix, diff --git a/backend/internal/service/gateway_request.go b/backend/internal/service/gateway_request.go index b77fac3187..0e52e00ecb 100644 --- a/backend/internal/service/gateway_request.go +++ b/backend/internal/service/gateway_request.go @@ -186,7 +186,9 @@ func parseGatewayRequestCurrentBody(parsed *ParsedRequest, protocol string) erro return DescribeInvalidJSON(bodyBytes) } - // 只在当前函数内零拷贝读取 JSON 字段;ReplaceBody 后必须重新进入本函数刷新派生状态。 + // Zero-copy JSON reads stay local to parsing. Persisted scalar strings must + // own their storage: an unescaped gjson string otherwise retains the complete + // request buffer when copied into queued billing work. Raw ranges stay zero-copy. jsonStr := *(*string)(unsafe.Pointer(&bodyBytes)) clearGatewayRequestDerivedState(parsed) parsed.protocol = protocol @@ -196,7 +198,7 @@ func parseGatewayRequestCurrentBody(parsed *ParsedRequest, protocol string) erro if modelResult.Type != gjson.String { return fmt.Errorf("invalid model field type") } - parsed.Model = modelResult.String() + parsed.Model = strings.Clone(modelResult.String()) if protocol == domain.PlatformAnthropic { normalizedModel := normalizeClaudeCodeLongContextModel(parsed.Model) if normalizedModel != parsed.Model { @@ -220,15 +222,15 @@ func parseGatewayRequestCurrentBody(parsed *ParsedRequest, protocol string) erro parsed.Stream = streamResult.Bool() } - parsed.MetadataUserID = gjson.Get(jsonStr, "metadata.user_id").String() + parsed.MetadataUserID = strings.Clone(gjson.Get(jsonStr, "metadata.user_id").String()) thinkingType := gjson.Get(jsonStr, "thinking.type").String() parsed.ThinkingEnabled = thinkingType == "enabled" || thinkingType == "adaptive" || thinkingType == "between_tools" || (protocol == domain.PlatformAnthropic && isClaude55SignedThinkingModel(parsed.Model)) - parsed.OutputEffort = strings.TrimSpace(gjson.Get(jsonStr, "output_config.effort").String()) + parsed.OutputEffort = strings.Clone(strings.TrimSpace(gjson.Get(jsonStr, "output_config.effort").String())) if protocol == domain.PlatformAnthropic { - parsed.Speed = strings.ToLower(strings.TrimSpace(gjson.Get(jsonStr, "speed").String())) + parsed.Speed = strings.Clone(strings.ToLower(strings.TrimSpace(gjson.Get(jsonStr, "speed").String()))) } maxTokensResult := gjson.Get(jsonStr, "max_tokens") diff --git a/backend/internal/service/gateway_request_scalar_memory_test.go b/backend/internal/service/gateway_request_scalar_memory_test.go new file mode 100644 index 0000000000..b0aeada1a4 --- /dev/null +++ b/backend/internal/service/gateway_request_scalar_memory_test.go @@ -0,0 +1,52 @@ +package service + +import ( + "fmt" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/domain" + "github.com/stretchr/testify/require" +) + +func TestParsedRequestScalarsDoNotAliasRequestBody(t *testing.T) { + for _, replace := range []bool{false, true} { + for _, suffix := range []string{"", "[1m]"} { + t.Run(fmt.Sprintf("replace=%t/suffix=%s", replace, suffix), func(t *testing.T) { + body := []byte(fmt.Sprintf(`{"model":"claude-sonnet-4%s","metadata":{"user_id":"session-123"},"output_config":{"effort":" high "},"speed":"fast","system":"instructions","messages":[{"role":"user","content":"%s"}]}`, suffix, strings.Repeat("x", 64<<10))) + var parsed *ParsedRequest + var err error + if replace { + parsed, err = ParseGatewayRequest(NewRequestBodyRef([]byte(`{}`)), domain.PlatformAnthropic) + require.NoError(t, err) + err = parsed.ReplaceBody(body) + } else { + parsed, err = ParseGatewayRequest(NewRequestBodyRef(body), domain.PlatformAnthropic) + } + require.NoError(t, err) + + // Large payload sections must still refer directly to the current + // body; only persistent scalar strings should get their own storage. + currentBody := parsed.Body.Bytes() + require.True(t, &parsed.SystemRaw()[0] == ¤tBody[parsed.systemRange.start]) + require.True(t, &parsed.MessagesRaw()[0] == ¤tBody[parsed.messagesRange.start]) + model, userID, effort, speed := parsed.Model, parsed.MetadataUserID, parsed.OutputEffort, parsed.Speed + parsed.Body.Replace(nil) + + // Reusing the source storage must not change metadata retained by + // queued billing work. Also overwrite the pre-normalization body: + // stripping [1m] must not leave Model pointing into that old buffer. + for i := range body { + body[i] = '!' + } + for i := range currentBody { + currentBody[i] = '!' + } + require.Equal(t, "claude-sonnet-4", model) + require.Equal(t, "session-123", userID) + require.Equal(t, "high", effort) + require.Equal(t, "fast", speed) + }) + } + } +} diff --git a/backend/internal/service/gateway_upstream_response.go b/backend/internal/service/gateway_upstream_response.go index fb9368b6c0..85b415e5cf 100644 --- a/backend/internal/service/gateway_upstream_response.go +++ b/backend/internal/service/gateway_upstream_response.go @@ -745,6 +745,7 @@ func (s *GatewayService) handleStreamingResponse(ctx context.Context, resp *http } scanBuf := getSSEScannerBuf64K() scanner.Buffer(scanBuf[:0], maxLineSize) + scanner.Split(newBoundedSSESplit(s.cfg, maxLineSize, nil)) type scanEvent struct { line string @@ -753,11 +754,16 @@ func (s *GatewayService) handleStreamingResponse(ctx context.Context, resp *http // 独立 goroutine 读取上游,避免读取阻塞导致超时/keepalive无法处理 events := make(chan scanEvent, 16) done := make(chan struct{}) + queueBudget := newSSEQueueBudget(s.cfg) sendEvent := func(ev scanEvent) bool { + if !queueBudget.acquire(len(ev.line), done) { + return false + } select { case events <- ev: return true case <-done: + queueBudget.release(len(ev.line)) return false } } @@ -1022,6 +1028,9 @@ func (s *GatewayService) handleStreamingResponse(ctx context.Context, resp *http for { select { case ev, ok := <-events: + if ok { + queueBudget.release(len(ev.line)) + } if !ok { // 上游完成,返回结果 if !sawTerminalEvent { @@ -1081,6 +1090,7 @@ func (s *GatewayService) handleStreamingResponse(ctx context.Context, resp *http } outputBlocks, data, usagePatch, err := processSSEEvent(pendingEventLines) + clear(pendingEventLines) pendingEventLines = pendingEventLines[:0] if err != nil { if clientDisconnected { diff --git a/backend/internal/service/gateway_usage_billing.go b/backend/internal/service/gateway_usage_billing.go index 0ece86cd3b..10e0992c9c 100644 --- a/backend/internal/service/gateway_usage_billing.go +++ b/backend/internal/service/gateway_usage_billing.go @@ -9,6 +9,7 @@ import ( "github.com/Wei-Shaw/sub2api/internal/config" "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" + pkghttputil "github.com/Wei-Shaw/sub2api/internal/pkg/httputil" "github.com/Wei-Shaw/sub2api/internal/pkg/logger" "github.com/Wei-Shaw/sub2api/internal/pkg/timezone" ) @@ -425,44 +426,44 @@ func finalizePostUsageBilling(ctx context.Context, p *postUsageBillingParams, de deps.deferredService.ScheduleLastUsedUpdate(p.Account.ID) - // Platform quota 累加:仅在 standard(余额)模式生效;订阅模式豁免;仅对有 limit 的用户写 - // Redis 同步写 + DB 异步持久化(flag=false 降级)或 flusher 异步刷(flag=true): - // - HasUserPlatformQuotaLimit 守卫:无 limit 的公司跳过,避免无效写入 + 浪费 Redis 容量 - // - Redis 同步:确保下次 preflight 立即看到最新 usage,把 TOCTOU 超支窗口 - // 限制在并发 in-flight 请求数量内(旧实现的异步入队会让超支无限累积直到 worker 处理) - // - DB 异步(flusher_enabled=false):在独立 goroutine 中走 detached context,失败用 ALERT log 触发 oncall 对账 - // - flusher_enabled=true:不直写 DB,由 flusher 异步批量刷(markDirty 已在 IncrementUserPlatformQuotaUsage 内部完成) + // Redis is updated before returning so subsequent preflight checks observe the + // charge. Without the batch flusher, persist inline with the usage task (in a + // worker or its synchronous overflow caller), without spawning detached work. + // Synchronous overflow remains backpressure, not a global DB concurrency cap. if !p.IsSubscriptionBill && p.Platform != "" && p.Cost.ActualCost > 0 && p.User != nil && deps.userPlatformQuotaRepo != nil && deps.billingCacheService != nil { if deps.billingCacheService.HasUserPlatformQuotaLimit(ctx, p.User.ID, p.Platform) { deps.billingCacheService.IncrementUserPlatformQuotaUsage(p.User.ID, p.Platform, p.Cost.ActualCost) if deps.cfg == nil || !deps.cfg.Database.UserPlatformQuotaFlusherEnabled { - // 降级路径:flusher 未启用时保留原有异步直写 DB - dbCtx, dbCancel := detachUpstreamContext(ctx) - userID, platform, cost := p.User.ID, p.Platform, p.Cost.ActualCost - go func() { - defer func() { - if r := recover(); r != nil { - logger.LegacyPrintf("service.gateway", "ALERT: panic in user platform quota incr goroutine user=%d platform=%s: %v", userID, platform, r) - } - }() - defer dbCancel() - if err := deps.userPlatformQuotaRepo.IncrementUsageWithReset(dbCtx, userID, platform, cost, time.Now().UTC()); err != nil { - // 失败计数器:暴露给 GatewayUserPlatformQuotaIncrStats(),由 ops 面板做斜率告警。 - userPlatformQuotaDBIncrErrorTotal.Add(1) - // ALERT 级别:DB 持久化失败意味着 Redis cache 失效后该笔 cost 永久丢失, - // 用户配额视图与实际消费会偏差,oncall 需要据此对账或人工补录。 - logger.LegacyPrintf("service.gateway", "ALERT: incr user platform quota DB failed user=%d platform=%s cost=%f: %v", userID, platform, cost, err) - } - }() + persistPostUsagePlatformQuota(ctx, deps.userPlatformQuotaRepo, p.User.ID, p.Platform, p.Cost.ActualCost) } - // flusher_enabled=true:不直写 DB,flusher 异步批量刷 } } - // Notification checks run async — all parameters are already captured, - // no dependency on the request context or upstream connection. - go notifyBalanceLow(p, deps, result) - go notifyAccountQuota(p, deps, result) + if deps.balanceNotifyService != nil { + deps.balanceNotifyService.submitUsageNotifications(p, deps, result) + } +} + +// A committed charge must still attempt quota persistence if the request/worker +// context expired. Bound that independent attempt, and keep failures observable; +// this path has no durable retry queue. +func persistPostUsagePlatformQuota(ctx context.Context, repo UserPlatformQuotaRepository, userID int64, platform string, cost float64) { + base := context.Background() + if ctx != nil { + base = context.WithoutCancel(ctx) + } + dbCtx, cancel := context.WithTimeout(base, 5*time.Second) + defer cancel() + defer func() { + if r := recover(); r != nil { + userPlatformQuotaDBIncrErrorTotal.Add(1) + logger.LegacyPrintf("service.gateway", "ALERT: panic persisting user platform quota user=%d platform=%s: %v", userID, platform, r) + } + }() + if err := repo.IncrementUsageWithReset(dbCtx, userID, platform, cost, time.Now().UTC()); err != nil { + userPlatformQuotaDBIncrErrorTotal.Add(1) + logger.LegacyPrintf("service.gateway", "ALERT: incr user platform quota DB failed user=%d platform=%s cost=%f: %v", userID, platform, cost, err) + } } func syncBalanceCacheAfterDeduction(ctx context.Context, p *postUsageBillingParams, deps *billingDeps, result *UsageBillingApplyResult) { @@ -496,7 +497,7 @@ func syncBalanceCacheAfterDeduction(ctx context.Context, p *postUsageBillingPara // notifyBalanceLow sends balance low notification after deduction. // When result.NewBalance is available (from DB transaction RETURNING), it is used directly // to reconstruct oldBalance, avoiding stale Redis reads and concurrent-deduction races. -func notifyBalanceLow(p *postUsageBillingParams, deps *billingDeps, result *UsageBillingApplyResult) { +func notifyBalanceLow(ctx context.Context, p *postUsageBillingParams, deps *billingDeps, result *UsageBillingApplyResult) { defer func() { if r := recover(); r != nil { slog.Error("panic in notifyBalanceLow", "recover", r) @@ -521,7 +522,7 @@ func notifyBalanceLow(p *postUsageBillingParams, deps *billingDeps, result *Usag "threshold", p.User.BalanceNotifyThreshold, "result_has_new_balance", result != nil && result.NewBalance != nil, ) - deps.balanceNotifyService.CheckBalanceAfterDeduction(context.Background(), p.User, oldBalance, p.Cost.ActualCost) + deps.balanceNotifyService.CheckBalanceAfterDeduction(ctx, p.User, oldBalance, p.Cost.ActualCost) } // resolveOldBalance returns the pre-deduction balance. @@ -537,7 +538,7 @@ func resolveOldBalance(p *postUsageBillingParams, result *UsageBillingApplyResul // notifyAccountQuota sends account quota threshold notification after increment. // When result.QuotaState is available (from DB transaction RETURNING), it is passed directly // to avoid a separate DB read that may see stale or concurrently-modified data. -func notifyAccountQuota(p *postUsageBillingParams, deps *billingDeps, result *UsageBillingApplyResult) { +func notifyAccountQuota(ctx context.Context, p *postUsageBillingParams, deps *billingDeps, result *UsageBillingApplyResult) { defer func() { if r := recover(); r != nil { slog.Error("panic in notifyAccountQuota", "recover", r) @@ -567,7 +568,7 @@ func notifyAccountQuota(p *postUsageBillingParams, deps *billingDeps, result *Us "account_cost", accountCost, "has_quota_state", quotaState != nil, ) - deps.balanceNotifyService.CheckAccountQuotaAfterIncrement(context.Background(), p.Account, accountCost, quotaState) + deps.balanceNotifyService.CheckAccountQuotaAfterIncrement(ctx, p.Account, accountCost, quotaState) } func detachedBillingContext(ctx context.Context) (context.Context, context.CancelFunc) { @@ -585,14 +586,14 @@ func detachStreamUpstreamContext(ctx context.Context, stream bool) (context.Cont if !stream { return ctx, func() {} } - return context.WithoutCancel(ctx), func() {} + return pkghttputil.DetachUpstreamContext(ctx), func() {} } -func detachUpstreamContext(ctx context.Context) (context.Context, context.CancelFunc) { +func detachUpstreamContext(ctx context.Context, drainTimeout ...time.Duration) (context.Context, context.CancelFunc) { if ctx == nil { return context.Background(), func() {} } - return context.WithoutCancel(ctx), func() {} + return pkghttputil.DetachUpstreamContext(ctx, drainTimeout...), func() {} } // billingDeps 扣费逻辑依赖的服务(由各 gateway service 提供) diff --git a/backend/internal/service/gateway_usage_quota_worker_test.go b/backend/internal/service/gateway_usage_quota_worker_test.go new file mode 100644 index 0000000000..11515a0d14 --- /dev/null +++ b/backend/internal/service/gateway_usage_quota_worker_test.go @@ -0,0 +1,86 @@ +package service + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/stretchr/testify/require" +) + +type blockingUsageQuotaRepo struct { + UserPlatformQuotaRepository + entered chan context.Context + release chan struct{} +} + +func (r *blockingUsageQuotaRepo) IncrementUsageWithReset(ctx context.Context, _ int64, _ string, _ float64, _ time.Time) error { + r.entered <- ctx + select { + case <-r.release: + return nil + case <-ctx.Done(): + return ctx.Err() + } +} + +func TestPostUsageQuotaPersistenceStaysInUsageWorker(t *testing.T) { + repo := &blockingUsageQuotaRepo{entered: make(chan context.Context, 1), release: make(chan struct{})} + pool := NewUsageRecordWorkerPoolWithOptions(UsageRecordWorkerPoolOptions{ + WorkerCount: 1, QueueSize: 8, TaskTimeout: time.Second, OverflowPolicy: "sync", + }) + t.Cleanup(pool.Stop) + t.Cleanup(func() { close(repo.release) }) + pool.Submit(func(ctx context.Context) { + finalizePostUsageBilling(ctx, &postUsageBillingParams{ + Cost: &CostBreakdown{ActualCost: 1}, User: &User{ID: 1}, Account: &Account{ID: 2}, Platform: PlatformOpenAI, + }, &billingDeps{ + userPlatformQuotaRepo: repo, + billingCacheService: &BillingCacheService{cfg: &config.Config{}}, + deferredService: &DeferredService{}, + }, nil) + }) + select { + case ctx := <-repo.entered: + deadline, ok := ctx.Deadline() + require.True(t, ok) + require.InDelta(t, 5, time.Until(deadline).Seconds(), 1) + case <-time.After(2 * time.Second): + t.Fatal("quota persistence did not start") + } + next := make(chan struct{}) + pool.Submit(func(context.Context) { close(next) }) + select { + case <-next: + t.Fatal("quota persistence escaped the usage worker and released its concurrency slot") + case <-time.After(20 * time.Millisecond): + } +} + +type failedUsageQuotaRepo struct { + UserPlatformQuotaRepository + ctx context.Context + errAtCall error +} + +func (r *failedUsageQuotaRepo) IncrementUsageWithReset(ctx context.Context, _ int64, _ string, _ float64, _ time.Time) error { + r.ctx = ctx + r.errAtCall = ctx.Err() + return errors.New("database unavailable") +} + +func TestPostUsageQuotaPersistenceHasIndependentDeadlineAndReportsFailure(t *testing.T) { + parent, cancel := context.WithCancel(context.Background()) + cancel() + repo := &failedUsageQuotaRepo{} + before := userPlatformQuotaDBIncrErrorTotal.Load() + persistPostUsagePlatformQuota(parent, repo, 1, PlatformOpenAI, 1) + require.NotNil(t, repo.ctx) + require.NoError(t, repo.errAtCall, "committed charge must attempt persistence after parent cancellation") + deadline, ok := repo.ctx.Deadline() + require.True(t, ok) + require.InDelta(t, 5, time.Until(deadline).Seconds(), 1) + require.Equal(t, before+1, userPlatformQuotaDBIncrErrorTotal.Load()) +} diff --git a/backend/internal/service/grok_sse_transport_config_test.go b/backend/internal/service/grok_sse_transport_config_test.go new file mode 100644 index 0000000000..461b920d25 --- /dev/null +++ b/backend/internal/service/grok_sse_transport_config_test.go @@ -0,0 +1,70 @@ +package service + +import ( + "io" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/apicompat" + "github.com/stretchr/testify/require" +) + +func TestGrokSSEPrefiltersRespectConfiguredEventLimits(t *testing.T) { + filters := []struct { + name string + wrap func(io.ReadCloser, *config.Config) io.ReadCloser + }{ + {"billing_ping", func(source io.ReadCloser, cfg *config.Config) io.ReadCloser { + return newGrokResponsesBillingPingFilterBody(source, &Account{Platform: PlatformGrok}, cfg.Gateway.MaxLineSize, cfg) + }}, + {"client_tools", func(source io.ReadCloser, cfg *config.Config) io.ReadCloser { + return newGrokResponsesClientToolStreamBody(source, apicompat.ResponsesClientToolMapping{}, cfg.Gateway.MaxLineSize, cfg) + }}, + } + for _, filter := range filters { + t.Run(filter.name, func(t *testing.T) { + for _, tc := range []struct { + name string + gateway config.GatewayConfig + wire string + limited bool + }{ + { + name: "byte_limit", + gateway: config.GatewayConfig{MaxLineSize: 1 << 20, SSEEventMaxBytes: 64}, + wire: strings.Repeat(": "+strings.Repeat("x", 30)+"\n", 3) + "\n", + limited: true, + }, + { + name: "line_limit", + gateway: config.GatewayConfig{MaxLineSize: 1 << 20, SSEEventMaxLines: 2}, + wire: strings.Repeat(": keepalive\n", 3) + "\n", + limited: true, + }, + { + name: "event_larger_than_individual_line_limit", + gateway: config.GatewayConfig{MaxLineSize: 128, SSEEventMaxBytes: 1024}, + wire: strings.Repeat(": "+strings.Repeat("x", 30)+"\n", 8) + "\n", + }, + { + name: "line_limit_above_default", + gateway: config.GatewayConfig{MaxLineSize: 1 << 20, SSEEventMaxLines: defaultSSEEventMaxLines + 1}, + wire: strings.Repeat(": keepalive\n", defaultSSEEventMaxLines+1) + "\n", + }, + } { + t.Run(tc.name, func(t *testing.T) { + body := filter.wrap(io.NopCloser(strings.NewReader(tc.wire)), &config.Config{Gateway: tc.gateway}) + defer func() { require.NoError(t, body.Close()) }() + output, err := io.ReadAll(body) + if tc.limited { + require.ErrorIs(t, err, errSSETransportLimit) + return + } + require.NoError(t, err) + require.Equal(t, tc.wire, string(output)) + }) + } + }) + } +} diff --git a/backend/internal/service/openai_first_output_timeout_test.go b/backend/internal/service/openai_first_output_timeout_test.go index fc4b5076ca..ebab68c019 100644 --- a/backend/internal/service/openai_first_output_timeout_test.go +++ b/backend/internal/service/openai_first_output_timeout_test.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "errors" + "fmt" "io" "net/http" "net/http/httptest" @@ -481,10 +482,12 @@ func TestOpenAINativeFirstOutputStageOverflowFailsOverWithoutAttemptBytes(t *tes }} svc := &OpenAIGatewayService{cfg: cfg, responseHeaderFilter: compileResponseHeaderFilter(cfg)} const lineSize = 1024*1024 - 256 - prefix := `data: {"type":"response.output_text.delta","delta":"` - suffix := `"}` + // Complete metadata events stay staged until visible output arrives. Each + // event fits the transport cap; their cumulative size exceeds the stage cap. + prefix := `data: {"type":"response.in_progress","response":{"id":"resp_staged","padding":"` + suffix := `"}}` line := prefix + strings.Repeat("x", lineSize-len(prefix)-len(suffix)) + suffix - body := strings.Repeat(line+"\n", 9) + body := strings.Repeat(line+"\n\n", 9) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) @@ -509,6 +512,45 @@ func TestOpenAINativeFirstOutputStageOverflowFailsOverWithoutAttemptBytes(t *tes require.Empty(t, rec.Header().Values("X-Ratelimit-Remaining-Requests")) } +func TestOpenAINativeFirstOutputEventLimitFailsOverWithoutAttemptBytes(t *testing.T) { + for _, explicitLimit := range []int64{0, 1024} { + t.Run(fmt.Sprintf("event_limit_%d", explicitLimit), func(t *testing.T) { + cfg := &config.Config{Gateway: config.GatewayConfig{ + OpenAIFirstOutputTimeoutSeconds: 30, + MaxLineSize: 2048, + SSEEventMaxBytes: explicitLimit, + }} + svc := &OpenAIGatewayService{cfg: cfg, responseHeaderFilter: compileResponseHeaderFilter(cfg)} + line := `data: {"type":"response.output_text.delta","delta":"` + strings.Repeat("x", 700) + `"}` + // No blank line: several individually legal lines form one oversized + // event, which must fail before the independent 8 MiB stage limit. + body := strings.Repeat(line+"\n", 4) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + resp := &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{ + "X-Request-Id": []string{"request-event-overflow"}, + "X-Ratelimit-Remaining-Requests": []string{"1"}, + }, + Body: io.NopCloser(strings.NewReader(body)), + } + + _, err := svc.handleStreamingResponse(c.Request.Context(), resp, c, &Account{ID: 1, Platform: PlatformOpenAI}, time.Now(), "model", "model") + + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, http.StatusBadGateway, failoverErr.StatusCode) + require.True(t, failoverErr.SafeToFailoverAfterWrite) + require.Contains(t, string(failoverErr.ResponseBody), "event exceeds first-output transport limit") + require.Empty(t, rec.Body.String()) + require.Empty(t, rec.Header().Values("X-Request-Id")) + require.Empty(t, rec.Header().Values("X-Ratelimit-Remaining-Requests")) + }) + } +} + func TestOpenAINativeFirstOutputScannerRejectsOversizedLineWithoutLeak(t *testing.T) { cfg := &config.Config{Gateway: config.GatewayConfig{ OpenAIFirstOutputTimeoutSeconds: 30, diff --git a/backend/internal/service/openai_gateway_anthropic_native_pump.go b/backend/internal/service/openai_gateway_anthropic_native_pump.go index 3b679bc4e8..a5f12fb1be 100644 --- a/backend/internal/service/openai_gateway_anthropic_native_pump.go +++ b/backend/internal/service/openai_gateway_anthropic_native_pump.go @@ -41,18 +41,24 @@ type anthropicNativeLineEvent struct { // anthropicNativeLinePump 以独立 goroutine 泵送 scanner 的行,并对逐行到达 // 间隔施加 interval 上限(<=0 表示禁用,可经 enableInterval 启用)。 type anthropicNativeLinePump struct { - events chan anthropicNativeLineEvent - done chan struct{} - timer *time.Timer - interval time.Duration + events chan anthropicNativeLineEvent + done chan struct{} + timer *time.Timer + interval time.Duration + queueBudget *sseQueueBudget } // newAnthropicNativeLinePump 启动泵 goroutine;调用方 defer pump.stop()。 -func newAnthropicNativeLinePump(scanner *bufio.Scanner, interval time.Duration) *anthropicNativeLinePump { +func newAnthropicNativeLinePump(scanner *bufio.Scanner, interval time.Duration, configs ...*config.Config) *anthropicNativeLinePump { + var cfg *config.Config + if len(configs) > 0 { + cfg = configs[0] + } p := &anthropicNativeLinePump{ - events: make(chan anthropicNativeLineEvent, 16), - done: make(chan struct{}), - interval: interval, + events: make(chan anthropicNativeLineEvent, 16), + done: make(chan struct{}), + interval: interval, + queueBudget: newSSEQueueBudget(cfg), } if interval > 0 { p.timer = time.NewTimer(interval) @@ -60,9 +66,13 @@ func newAnthropicNativeLinePump(scanner *bufio.Scanner, interval time.Duration) go func() { defer close(p.events) for scanner.Scan() { + if !p.queueBudget.acquire(len(scanner.Bytes()), p.done) { + return + } select { case p.events <- anthropicNativeLineEvent{line: scanner.Text()}: case <-p.done: + p.queueBudget.release(len(scanner.Bytes())) return } } @@ -110,6 +120,9 @@ func (p *anthropicNativeLinePump) deliver(ev anthropicNativeLineEvent, ok bool) if !ok { return "", io.EOF } + if p.queueBudget != nil { + p.queueBudget.release(len(ev.line)) + } p.resetTimer() return ev.line, ev.err } diff --git a/backend/internal/service/openai_gateway_cc_pipeline.go b/backend/internal/service/openai_gateway_cc_pipeline.go index 4d65374a45..b7eadf7b4b 100644 --- a/backend/internal/service/openai_gateway_cc_pipeline.go +++ b/backend/internal/service/openai_gateway_cc_pipeline.go @@ -39,6 +39,7 @@ func (s *OpenAIGatewayService) newUpstreamSSEScanner(r io.Reader) *bufio.Scanner maxLineSize = s.cfg.Gateway.MaxLineSize } scanner.Buffer(make([]byte, 0, 64*1024), maxLineSize) + scanner.Split(newBoundedSSESplit(s.cfg, maxLineSize, nil)) return scanner } diff --git a/backend/internal/service/openai_gateway_chat_completions.go b/backend/internal/service/openai_gateway_chat_completions.go index 6c727da0cc..ed8433d97f 100644 --- a/backend/internal/service/openai_gateway_chat_completions.go +++ b/backend/internal/service/openai_gateway_chat_completions.go @@ -1211,11 +1211,16 @@ func (s *OpenAIGatewayService) handleChatStreamingResponse( done := make(chan struct{}) var lastReadAt int64 atomic.StoreInt64(&lastReadAt, time.Now().UnixNano()) + queueBudget := newSSEQueueBudget(s.cfg) sendEvent := func(ev scanEvent) bool { + if !queueBudget.acquire(len(ev.line), done) { + return false + } select { case events <- ev: return true case <-done: + queueBudget.release(len(ev.line)) return false } } @@ -1248,6 +1253,9 @@ func (s *OpenAIGatewayService) handleChatStreamingResponse( for { select { case ev, ok := <-events: + if ok { + queueBudget.release(len(ev.line)) + } if !ok { if frame, ok := parser.Finish(); ok { if strings.TrimSpace(frame.Data) == "[DONE]" { diff --git a/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go b/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go index f6333661f5..5c2d86b87d 100644 --- a/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go +++ b/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go @@ -164,13 +164,15 @@ func (s *OpenAIGatewayService) handleCCBufferedFromNativeAnthropic( maxLineSize = s.cfg.Gateway.MaxLineSize } scanner.Buffer(make([]byte, 0, 64*1024), maxLineSize) + scanner.Split(newBoundedSSESplit(s.cfg, maxLineSize, nil)) var finalResp *apicompat.AnthropicResponse var usage ClaudeUsage // 读间隔上限:上游挂住 SSE 时中止组装(缓冲路径尚未提交响应头,可回 502)。 streamInterval := anthropicNativeStreamInterval(s.cfg) - pump := newAnthropicNativeLinePump(scanner, streamInterval) + pump := newAnthropicNativeLinePump(scanner, streamInterval, s.cfg) + streamStatus := &anthropicCompatStream{body: resp.Body} defer pump.stop() logReadErr := func(err error) { @@ -198,6 +200,7 @@ func (s *OpenAIGatewayService) handleCCBufferedFromNativeAnthropic( return onIdle() } logReadErr(rerr) + streamStatus.readErr = rerr break } // SSE 规范允许 `event:xxx`(冒号后无空格):Kimi 等 Anthropic 兼容上游 @@ -212,6 +215,7 @@ func (s *OpenAIGatewayService) handleCCBufferedFromNativeAnthropic( return onIdle() } logReadErr(rerr) + streamStatus.readErr = rerr break } payload, ok := extractOpenAISSEDataLine(dataLine) @@ -224,6 +228,11 @@ func (s *OpenAIGatewayService) handleCCBufferedFromNativeAnthropic( continue } + streamStatus.observe(&event, payload) + if streamStatus.upstreamErrType != "" { + break + } + if event.Type == "message_start" && event.Message != nil { finalResp = event.Message mergeAnthropicUsage(&usage, event.Message.Usage) @@ -254,6 +263,16 @@ func (s *OpenAIGatewayService) handleCCBufferedFromNativeAnthropic( } } + if failure := streamStatus.failure(); failure != nil { + _ = resp.Body.Close() + writeChatCompletionsError(c, http.StatusBadGateway, "server_error", failure.message) + return &OpenAIForwardResult{ + RequestID: requestID, UpstreamHeaders: resp.Header, Usage: claudeUsageToOpenAIUsage(&usage), + Model: originalModel, BillingModel: billingModel, UpstreamModel: upstreamModel, + UpstreamEndpoint: "/v1/messages", ReasoningEffort: reasoningEffort, Duration: time.Since(startTime), + }, failure.err + } + if finalResp == nil { writeChatCompletionsError(c, http.StatusBadGateway, "server_error", "Upstream stream ended without a response") return nil, fmt.Errorf("upstream stream ended without response") @@ -335,6 +354,7 @@ func (s *OpenAIGatewayService) handleCCStreamingFromNativeAnthropic( maxLineSize = s.cfg.Gateway.MaxLineSize } scanner.Buffer(make([]byte, 0, 64*1024), maxLineSize) + scanner.Split(newBoundedSSESplit(s.cfg, maxLineSize, nil)) resultWithUsage := func() *OpenAIForwardResult { return &OpenAIForwardResult{ @@ -357,7 +377,8 @@ func (s *OpenAIGatewayService) handleCCStreamingFromNativeAnthropic( // WithoutCancel 且 http.Client 无整体 Timeout,无此界限则客户端断开后 // scanner.Scan() 永久阻塞(见 anthropic native pump 文件注释)。 streamInterval := anthropicNativeStreamInterval(s.cfg) - pump := newAnthropicNativeLinePump(scanner, streamInterval) + pump := newAnthropicNativeLinePump(scanner, streamInterval, s.cfg) + streamStatus := &anthropicCompatStream{body: resp.Body} defer pump.stop() logReadErr := func(err error) { @@ -443,6 +464,7 @@ func (s *OpenAIGatewayService) handleCCStreamingFromNativeAnthropic( return onIdle() } logReadErr(rerr) + streamStatus.readErr = rerr break } if _, ok := extractOpenAISSEEventLine(line); !ok { @@ -456,6 +478,7 @@ func (s *OpenAIGatewayService) handleCCStreamingFromNativeAnthropic( } // EOF / 读错误:事件行后流终止,进入 finalize。 logReadErr(rerr) + streamStatus.readErr = rerr break } payload, ok := extractOpenAISSEDataLine(dataLine) @@ -468,6 +491,11 @@ func (s *OpenAIGatewayService) handleCCStreamingFromNativeAnthropic( continue } + streamStatus.observe(&event, payload) + if streamStatus.upstreamErrType != "" { + break + } + // Forward received usage regardless of the client stream_options. // The intermediate Responses converter synthesizes usage even when absent. ccState.IncludeUsage = ccState.IncludeUsage || anthropicChatStreamHasUsage(&event, payload) @@ -477,7 +505,19 @@ func (s *OpenAIGatewayService) handleCCStreamingFromNativeAnthropic( } } - // Finalize both state machines(客户端已断开时仍执行,保证 usage 汇总完整)。 + if failure := streamStatus.failure(); failure != nil { + _ = resp.Body.Close() + if !clientDisconnected { + writeAnthropicCompatCCStreamFailure(c, failure) + } + return resultWithUsage(), failure.err + } + + if clientDisconnected { + return resultWithUsage(), nil + } + + // Finalize only after the upstream has supplied a terminal event. finalResEvents := apicompat.FinalizeAnthropicResponsesStream(anthState) for _, resEvt := range finalResEvents { ccChunks := apicompat.ResponsesEventToChatChunks(&resEvt, ccState) diff --git a/backend/internal/service/openai_gateway_forward.go b/backend/internal/service/openai_gateway_forward.go index 04f4e77078..b8bee593b1 100644 --- a/backend/internal/service/openai_gateway_forward.go +++ b/backend/internal/service/openai_gateway_forward.go @@ -1209,7 +1209,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco if s.cfg != nil && s.cfg.Gateway.MaxLineSize > 0 { maxLineSize = s.cfg.Gateway.MaxLineSize } - resp.Body = newResponsesClientToolStreamBody(resp.Body, mapping, maxLineSize) + resp.Body = newResponsesClientToolStreamBody(resp.Body, mapping, maxLineSize, s.cfg) } serviceTier := extractOpenAIServiceTierFromBody(body) diff --git a/backend/internal/service/openai_gateway_grok.go b/backend/internal/service/openai_gateway_grok.go index aea1e3c964..ad40eac7db 100644 --- a/backend/internal/service/openai_gateway_grok.go +++ b/backend/internal/service/openai_gateway_grok.go @@ -218,9 +218,9 @@ func (s *OpenAIGatewayService) forwardGrokResponses( if s.cfg != nil && s.cfg.Gateway.MaxLineSize > 0 { maxLineSize = s.cfg.Gateway.MaxLineSize } - resp.Body = newGrokResponsesBillingPingFilterBody(resp.Body, account, maxLineSize) + resp.Body = newGrokResponsesBillingPingFilterBody(resp.Body, account, maxLineSize, s.cfg) if hasGrokResponsesClientToolMapping(clientToolMapping) { - resp.Body = newGrokResponsesClientToolStreamBody(resp.Body, clientToolMapping, maxLineSize) + resp.Body = newGrokResponsesClientToolStreamBody(resp.Body, clientToolMapping, maxLineSize, s.cfg) } streamResult, err := s.handleStreamingResponse(ctx, resp, c, account, startTime, originalModel, upstreamModel) if err != nil { diff --git a/backend/internal/service/openai_gateway_grok_sse_filter.go b/backend/internal/service/openai_gateway_grok_sse_filter.go index 78159144d5..109ca50473 100644 --- a/backend/internal/service/openai_gateway_grok_sse_filter.go +++ b/backend/internal/service/openai_gateway_grok_sse_filter.go @@ -8,6 +8,8 @@ import ( "io" "strings" "sync" + + "github.com/Wei-Shaw/sub2api/internal/config" ) // OpenAI Responses SSE event types are a closed enum for strict clients @@ -46,13 +48,13 @@ func (b *grokResponsesBillingPingFilterBody) closeSource() error { return b.closeErr } -func newGrokResponsesBillingPingFilterBody(source io.ReadCloser, account *Account, maxLineSize int) io.ReadCloser { +func newGrokResponsesBillingPingFilterBody(source io.ReadCloser, account *Account, maxLineSize int, cfg *config.Config) io.ReadCloser { if account == nil || account.Platform != PlatformGrok { return source } reader, writer := io.Pipe() body := &grokResponsesBillingPingFilterBody{PipeReader: reader, source: source} - go filterGrokResponsesBillingPings(source, writer, body.closeSource, maxLineSize) + go filterGrokResponsesBillingPings(source, writer, body.closeSource, maxLineSize, cfg) return body } @@ -61,6 +63,7 @@ func filterGrokResponsesBillingPings( destination *io.PipeWriter, closeSource func() error, maxLineSize int, + cfg *config.Config, ) { defer func() { _ = closeSource() }() if maxLineSize <= 0 { @@ -75,7 +78,7 @@ func filterGrokResponsesBillingPings( initialBufferSize = maxLineSize } scanner.Buffer(scanBuf[:0:initialBufferSize], maxLineSize) - scanner.Split(scanSSELinesPreservingEndings) + scanner.Split(newBoundedSSESplit(cfg, maxLineSize, scanSSELinesPreservingEndings)) // Only frames opened by an `event: ping` line are buffered (pingFrame); // every other frame streams through line by line without copying. diff --git a/backend/internal/service/openai_gateway_grok_sse_filter_test.go b/backend/internal/service/openai_gateway_grok_sse_filter_test.go index 1dce65e95a..236f799541 100644 --- a/backend/internal/service/openai_gateway_grok_sse_filter_test.go +++ b/backend/internal/service/openai_gateway_grok_sse_filter_test.go @@ -22,6 +22,7 @@ func filterGrokPingTestInput(t *testing.T, input string) string { io.NopCloser(strings.NewReader(input)), &Account{Platform: PlatformGrok}, defaultMaxLineSize, + nil, ) output, err := io.ReadAll(body) require.NoError(t, err) @@ -157,7 +158,7 @@ func TestGrokResponsesBillingPingFilterConvertsPartialPingFrameAtEOF(t *testing. func TestGrokResponsesBillingPingFilterDoesNotFilterNonGrokAccounts(t *testing.T) { input := "event: ping\ndata: {\"type\":\"ping\",\"cost\":\"0\"}\n\n" source := io.NopCloser(strings.NewReader(input)) - body := newGrokResponsesBillingPingFilterBody(source, &Account{Platform: PlatformOpenAI}, defaultMaxLineSize) + body := newGrokResponsesBillingPingFilterBody(source, &Account{Platform: PlatformOpenAI}, defaultMaxLineSize, nil) output, err := io.ReadAll(body) require.NoError(t, err) @@ -180,7 +181,7 @@ func TestGrokResponsesBillingPingFilterPreservesUsageAndTerminalEvent(t *testing StatusCode: http.StatusOK, Header: http.Header{}, Body: newGrokResponsesBillingPingFilterBody( - io.NopCloser(strings.NewReader(input)), account, defaultMaxLineSize, + io.NopCloser(strings.NewReader(input)), account, defaultMaxLineSize, nil, ), } recorder := httptest.NewRecorder() @@ -215,7 +216,7 @@ func (r *grokPingFilterTestReadCloser) Close() error { func TestGrokResponsesBillingPingFilterCloseCancelsSourceOnce(t *testing.T) { upstreamReader, upstreamWriter := io.Pipe() source := &grokPingFilterTestReadCloser{reader: upstreamReader} - body := newGrokResponsesBillingPingFilterBody(source, &Account{Platform: PlatformGrok}, defaultMaxLineSize) + body := newGrokResponsesBillingPingFilterBody(source, &Account{Platform: PlatformGrok}, defaultMaxLineSize, nil) require.NoError(t, body.Close()) require.Eventually(t, func() bool { return source.closeCount.Load() == 1 }, time.Second, time.Millisecond) @@ -226,7 +227,7 @@ func TestGrokResponsesBillingPingFilterCloseCancelsSourceOnce(t *testing.T) { func TestGrokResponsesBillingPingFilterFlushesCompletedFrames(t *testing.T) { upstreamReader, upstreamWriter := io.Pipe() - body := newGrokResponsesBillingPingFilterBody(upstreamReader, &Account{Platform: PlatformGrok}, defaultMaxLineSize) + body := newGrokResponsesBillingPingFilterBody(upstreamReader, &Account{Platform: PlatformGrok}, defaultMaxLineSize, nil) t.Cleanup(func() { require.NoError(t, body.Close()) }) go func() { @@ -255,6 +256,7 @@ func TestGrokResponsesBillingPingFilterReportsOversizedLine(t *testing.T) { io.NopCloser(strings.NewReader("data: 123456789\n\n")), &Account{Platform: PlatformGrok}, 8, + nil, ) _, err := io.ReadAll(body) require.ErrorContains(t, err, "filter Grok Responses billing ping") diff --git a/backend/internal/service/openai_gateway_grok_tool_protocol.go b/backend/internal/service/openai_gateway_grok_tool_protocol.go index 9f876a1a6e..f62db8960d 100644 --- a/backend/internal/service/openai_gateway_grok_tool_protocol.go +++ b/backend/internal/service/openai_gateway_grok_tool_protocol.go @@ -8,6 +8,7 @@ import ( "io" "strings" + "github.com/Wei-Shaw/sub2api/internal/config" "github.com/Wei-Shaw/sub2api/internal/pkg/apicompat" "github.com/gin-gonic/gin" "github.com/tidwall/gjson" @@ -122,10 +123,11 @@ func newResponsesClientToolStreamBody( source io.ReadCloser, mapping apicompat.ResponsesClientToolMapping, maxLineSize int, + cfg *config.Config, ) io.ReadCloser { reader, writer := io.Pipe() body := &responsesClientToolStreamBody{PipeReader: reader, source: source} - go transformResponsesClientToolStream(source, writer, mapping, maxLineSize) + go transformResponsesClientToolStream(source, writer, mapping, maxLineSize, cfg) return body } @@ -133,8 +135,9 @@ func newGrokResponsesClientToolStreamBody( source io.ReadCloser, mapping apicompat.ResponsesClientToolMapping, maxLineSize int, + cfg *config.Config, ) io.ReadCloser { - return newResponsesClientToolStreamBody(source, mapping, maxLineSize) + return newResponsesClientToolStreamBody(source, mapping, maxLineSize, cfg) } func transformResponsesClientToolStream( @@ -142,6 +145,7 @@ func transformResponsesClientToolStream( destination *io.PipeWriter, mapping apicompat.ResponsesClientToolMapping, maxLineSize int, + cfg *config.Config, ) { defer func() { _ = source.Close() }() if maxLineSize <= 0 { @@ -152,6 +156,7 @@ func transformResponsesClientToolStream( scanBuf := getSSEScannerBuf64K() defer putSSEScannerBuf64K(scanBuf) scanner.Buffer(scanBuf[:0], maxLineSize) + scanner.Split(newBoundedSSESplit(cfg, maxLineSize, nil)) documents := newOpenAISSEJSONDocumentScanner(scanner) restorer := apicompat.NewResponsesClientToolStreamRestorer(mapping) buffered := bufio.NewWriterSize(destination, 4*1024) diff --git a/backend/internal/service/openai_gateway_grok_tool_protocol_test.go b/backend/internal/service/openai_gateway_grok_tool_protocol_test.go index dd2cd5bb66..32dc6c3856 100644 --- a/backend/internal/service/openai_gateway_grok_tool_protocol_test.go +++ b/backend/internal/service/openai_gateway_grok_tool_protocol_test.go @@ -429,7 +429,7 @@ func TestGrokResponsesClientToolStreamBodyFlushesFrameBeforeEOF(t *testing.T) { sourceReader, sourceWriter := io.Pipe() body := newGrokResponsesClientToolStreamBody(sourceReader, apicompat.ResponsesClientToolMapping{ CustomTools: map[string]bool{"apply_patch": true}, - }, defaultMaxLineSize) + }, defaultMaxLineSize, nil) defer func() { _ = body.Close() }() defer func() { _ = sourceWriter.Close() }() diff --git a/backend/internal/service/openai_gateway_messages.go b/backend/internal/service/openai_gateway_messages.go index dfe326e847..39a8ecedc8 100644 --- a/backend/internal/service/openai_gateway_messages.go +++ b/backend/internal/service/openai_gateway_messages.go @@ -880,12 +880,17 @@ func (s *OpenAIGatewayService) readOpenAICompatBufferedTerminal( } events := make(chan scanEvent, 16) done := make(chan struct{}) + queueBudget := newSSEQueueBudget(s.cfg) go func() { defer close(events) for scanner.Scan() { + if !queueBudget.acquire(len(scanner.Bytes()), done) { + return + } select { case events <- scanEvent{line: scanner.Text()}: case <-done: + queueBudget.release(len(scanner.Bytes())) return } } @@ -902,6 +907,9 @@ func (s *OpenAIGatewayService) readOpenAICompatBufferedTerminal( for { select { case ev, ok := <-events: + if ok { + queueBudget.release(len(ev.line)) + } if !ok { if frame, ok := parser.Finish(); ok { payload := openAICompatPayloadWithEventType(frame.Data, frame.EventType) @@ -1300,11 +1308,16 @@ func (s *OpenAIGatewayService) handleAnthropicStreamingResponse( done := make(chan struct{}) var lastReadAt int64 atomic.StoreInt64(&lastReadAt, time.Now().UnixNano()) + queueBudget := newSSEQueueBudget(s.cfg) sendEvent := func(ev scanEvent) bool { + if !queueBudget.acquire(len(ev.line), done) { + return false + } select { case events <- ev: return true case <-done: + queueBudget.release(len(ev.line)) return false } } @@ -1337,6 +1350,9 @@ func (s *OpenAIGatewayService) handleAnthropicStreamingResponse( for { select { case ev, ok := <-events: + if ok { + queueBudget.release(len(ev.line)) + } if !ok { // Upstream closed if frame, ok := parser.Finish(); ok { diff --git a/backend/internal/service/openai_gateway_messages_anthropic_native.go b/backend/internal/service/openai_gateway_messages_anthropic_native.go index 12a3344068..3156aa8546 100644 --- a/backend/internal/service/openai_gateway_messages_anthropic_native.go +++ b/backend/internal/service/openai_gateway_messages_anthropic_native.go @@ -347,6 +347,7 @@ func (s *OpenAIGatewayService) handleNativeAnthropicStreamingResponse( } scanBuf := getSSEScannerBuf64K() scanner.Buffer(scanBuf[:0], maxLineSize) + scanner.Split(newBoundedSSESplit(s.cfg, maxLineSize, nil)) type scanEvent struct { line string @@ -354,11 +355,16 @@ func (s *OpenAIGatewayService) handleNativeAnthropicStreamingResponse( } events := make(chan scanEvent, 16) done := make(chan struct{}) + queueBudget := newSSEQueueBudget(s.cfg) sendEvent := func(ev scanEvent) bool { + if !queueBudget.acquire(len(ev.line), done) { + return false + } select { case events <- ev: return true case <-done: + queueBudget.release(len(ev.line)) return false } } @@ -424,6 +430,9 @@ func (s *OpenAIGatewayService) handleNativeAnthropicStreamingResponse( for { select { case ev, ok := <-events: + if ok { + queueBudget.release(len(ev.line)) + } if !ok { if !clientDisconnected { flusher.Flush() diff --git a/backend/internal/service/openai_gateway_passthrough.go b/backend/internal/service/openai_gateway_passthrough.go index 05bab10c64..af55cc0900 100644 --- a/backend/internal/service/openai_gateway_passthrough.go +++ b/backend/internal/service/openai_gateway_passthrough.go @@ -432,7 +432,7 @@ func (s *OpenAIGatewayService) forwardOpenAIPassthrough( if s.cfg != nil && s.cfg.Gateway.MaxLineSize > 0 { maxLineSize = s.cfg.Gateway.MaxLineSize } - resp.Body = newGrokResponsesClientToolStreamBody(resp.Body, mapping, maxLineSize) + resp.Body = newGrokResponsesClientToolStreamBody(resp.Body, mapping, maxLineSize, s.cfg) } // x-codex-turn-state 溯源:下游回传由 writeOpenAIPassthroughResponseHeaders @@ -1973,6 +1973,7 @@ func (s *OpenAIGatewayService) handleStreamingResponsePassthrough( } scanBuf := getSSEScannerBuf64K() scanner.Buffer(scanBuf[:0], maxLineSize) + scanner.Split(newBoundedSSESplit(s.cfg, maxLineSize, nil)) defer putSSEScannerBuf64K(scanBuf) documentScanner := newOpenAISSEJSONDocumentScanner(scanner) diff --git a/backend/internal/service/openai_gateway_response_handling.go b/backend/internal/service/openai_gateway_response_handling.go index eddf8a8f5b..a2b0fae6a2 100644 --- a/backend/internal/service/openai_gateway_response_handling.go +++ b/backend/internal/service/openai_gateway_response_handling.go @@ -165,8 +165,9 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context. scanner := bufio.NewScanner(resp.Body) scanBuf := getSSEScannerBuf64K() scanner.Buffer(scanBuf[:0], maxLineSize) + scanner.Split(newBoundedSSESplit(s.cfg, maxLineSize, nil)) if stageFirstOutput { - scanner.Split(openAIFirstOutputDynamicScanLines(&firstOutputScanGuard)) + scanner.Split(newBoundedSSESplit(s.cfg, maxLineSize, openAIFirstOutputDynamicScanLines(&firstOutputScanGuard))) } documentScanner := newOpenAISSEJSONDocumentScanner(scanner) @@ -428,6 +429,15 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context. failoverErr.SafeToFailoverAfterWrite = true return resultWithUsage(), failoverErr, true } + if errors.Is(scanErr, errSSETransportLimit) && stageFirstOutput && !firstOutputProgressObserved { + logger.LegacyPrintf("service.openai_gateway", "SSE event exceeded transport limit before first output: account=%d error=%v", account.ID, scanErr) + failoverErr := s.newOpenAIStreamFailoverError( + c, account, false, upstreamRequestID, nil, + "OpenAI SSE event exceeds first-output transport limit: "+scanErr.Error(), + ) + failoverErr.SafeToFailoverAfterWrite = true + return resultWithUsage(), failoverErr, true + } if errors.Is(scanErr, bufio.ErrTooLong) && stageFirstOutput && !firstOutputProgressObserved { logger.LegacyPrintf("service.openai_gateway", "SSE line too long before first output: account=%d max_size=%d error=%v", account.ID, maxLineSize, scanErr) failoverErr := s.newOpenAIStreamFailoverError( @@ -843,13 +853,18 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context. // the timeout-disabled path preserves the legacy depth of 16. events := make(chan scanEvent, openAIFirstOutputEventQueueSize(guardFirstOutput)) done := make(chan struct{}) + queueBudget := newSSEQueueBudget(s.cfg) sendEvent := func(ev scanEvent) bool { + if !queueBudget.acquire(len(ev.line), done) { + return false + } if firstOutputScanGuard.Load() { ev.processed = make(chan struct{}) } select { case events <- ev: case <-done: + queueBudget.release(len(ev.line)) return false } if ev.processed == nil { @@ -887,6 +902,9 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context. for { select { case ev, ok := <-events: + if ok { + queueBudget.release(len(ev.line)) + } if !ok { if stageFirstOutput && eventInProgress { // EOF dispatches the final SSE event even without a trailing blank diff --git a/backend/internal/service/openai_gateway_responses_anthropic_native.go b/backend/internal/service/openai_gateway_responses_anthropic_native.go index ec4fada790..d4ed554a71 100644 --- a/backend/internal/service/openai_gateway_responses_anthropic_native.go +++ b/backend/internal/service/openai_gateway_responses_anthropic_native.go @@ -166,13 +166,15 @@ func (s *OpenAIGatewayService) handleResponsesBufferedFromNativeAnthropic( maxLineSize = s.cfg.Gateway.MaxLineSize } scanner.Buffer(make([]byte, 0, 64*1024), maxLineSize) + scanner.Split(newBoundedSSESplit(s.cfg, maxLineSize, nil)) var finalResp *apicompat.AnthropicResponse var usage ClaudeUsage // 读间隔上限:上游挂住 SSE 时中止组装(缓冲路径尚未提交响应头,可回 502)。 streamInterval := anthropicNativeStreamInterval(s.cfg) - pump := newAnthropicNativeLinePump(scanner, streamInterval) + pump := newAnthropicNativeLinePump(scanner, streamInterval, s.cfg) + streamStatus := &anthropicCompatStream{body: resp.Body} defer pump.stop() logReadErr := func(err error) { @@ -200,6 +202,7 @@ func (s *OpenAIGatewayService) handleResponsesBufferedFromNativeAnthropic( return onIdle() } logReadErr(rerr) + streamStatus.readErr = rerr break } // SSE 规范允许 `event:xxx`(冒号后无空格):Kimi 等上游返回紧凑格式。 @@ -213,6 +216,7 @@ func (s *OpenAIGatewayService) handleResponsesBufferedFromNativeAnthropic( return onIdle() } logReadErr(rerr) + streamStatus.readErr = rerr break } payload, ok := extractOpenAISSEDataLine(dataLine) @@ -225,6 +229,11 @@ func (s *OpenAIGatewayService) handleResponsesBufferedFromNativeAnthropic( continue } + streamStatus.observe(&event, payload) + if streamStatus.upstreamErrType != "" { + break + } + if event.Type == "message_start" && event.Message != nil { finalResp = event.Message mergeAnthropicUsage(&usage, event.Message.Usage) @@ -257,6 +266,16 @@ func (s *OpenAIGatewayService) handleResponsesBufferedFromNativeAnthropic( } } + if failure := streamStatus.failure(); failure != nil { + _ = resp.Body.Close() + writeResponsesError(c, http.StatusBadGateway, "server_error", failure.message) + return &OpenAIForwardResult{ + RequestID: requestID, UpstreamHeaders: resp.Header, Usage: claudeUsageToOpenAIUsage(&usage), + Model: originalModel, BillingModel: billingModel, UpstreamModel: upstreamModel, + UpstreamEndpoint: "/v1/messages", ReasoningEffort: reasoningEffort, Duration: time.Since(startTime), + }, failure.err + } + if finalResp == nil { writeResponsesError(c, http.StatusBadGateway, "server_error", "Upstream stream ended without a response") return nil, fmt.Errorf("upstream stream ended without response") @@ -346,6 +365,7 @@ func (s *OpenAIGatewayService) handleResponsesStreamingFromNativeAnthropic( maxLineSize = s.cfg.Gateway.MaxLineSize } scanner.Buffer(make([]byte, 0, 64*1024), maxLineSize) + scanner.Split(newBoundedSSESplit(s.cfg, maxLineSize, nil)) resultWithUsage := func() *OpenAIForwardResult { return &OpenAIForwardResult{ @@ -368,7 +388,8 @@ func (s *OpenAIGatewayService) handleResponsesStreamingFromNativeAnthropic( // WithoutCancel 且 http.Client 无整体 Timeout,无此界限则 scanner.Scan() // 永久阻塞(见 anthropic native pump 文件注释)。 streamInterval := anthropicNativeStreamInterval(s.cfg) - pump := newAnthropicNativeLinePump(scanner, streamInterval) + pump := newAnthropicNativeLinePump(scanner, streamInterval, s.cfg) + streamStatus := &anthropicCompatStream{body: resp.Body} defer pump.stop() logReadErr := func(err error) { @@ -391,7 +412,7 @@ func (s *OpenAIGatewayService) handleResponsesStreamingFromNativeAnthropic( // 与 CC 姊妹路径(handleCCStreamingFromNativeAnthropic.writeChunk)同语义: // 客户端断开后不再写出,但继续排水上游至流自然结束——Anthropic 的最终 // output_tokens 只在末尾 message_delta 携带,提前退出会把整段生成记成 ~1 - // token,payg 上游照常计费而平台漏记。状态机照常推进以保证 finalize 一致。 + // token,payg 上游照常计费而平台漏记。断连后只采集 usage,避免继续累积转换输出。 processAnthropicEvent := func(event *apicompat.AnthropicStreamEvent) { if firstChunk { firstChunk = false @@ -412,10 +433,10 @@ func (s *OpenAIGatewayService) handleResponsesStreamingFromNativeAnthropic( syncAnthropicResponsesUsage(state, usage) normalizeAnthropicEventUsageForResponses(event, usage) - events := apicompat.AnthropicEventToResponsesEvents(event, state) if clientDisconnected { return } + events := apicompat.AnthropicEventToResponsesEvents(event, state) for _, evt := range events { payload, err := json.Marshal(evt) if err != nil { @@ -446,6 +467,7 @@ func (s *OpenAIGatewayService) handleResponsesStreamingFromNativeAnthropic( return onIdle() } logReadErr(rerr) + streamStatus.readErr = rerr break } if _, ok := extractOpenAISSEEventLine(line); !ok { @@ -458,6 +480,7 @@ func (s *OpenAIGatewayService) handleResponsesStreamingFromNativeAnthropic( return onIdle() } logReadErr(rerr) + streamStatus.readErr = rerr break } payload, ok := extractOpenAISSEDataLine(dataLine) @@ -470,11 +493,28 @@ func (s *OpenAIGatewayService) handleResponsesStreamingFromNativeAnthropic( continue } + streamStatus.observe(&event, payload) + if streamStatus.upstreamErrType != "" { + break + } + processAnthropicEvent(&event) } - // Finalize state machine(客户端已断开时仍推进,保证 usage 汇总完整;仅在 - // 客户端仍连接时写出)。终态帧与逐事件路径一致过工具名反转与客户端工具还原, + if failure := streamStatus.failure(); failure != nil { + _ = resp.Body.Close() + if !clientDisconnected { + writeAnthropicCompatResponsesStreamFailure(c, state, clientToolRestorer, failure) + } + return resultWithUsage(), failure.err + } + + if clientDisconnected { + return resultWithUsage(), nil + } + + // Finalize only after the upstream has supplied a terminal event. + // 终态帧与逐事件路径一致过工具名反转与客户端工具还原, // 避免流截断时终态帧携带改写后的工具名。 if finalEvents := apicompat.FinalizeAnthropicResponsesStream(state); len(finalEvents) > 0 && !clientDisconnected { wrote := false diff --git a/backend/internal/service/openai_gateway_service.go b/backend/internal/service/openai_gateway_service.go index 1084c824a2..e929ce22b0 100644 --- a/backend/internal/service/openai_gateway_service.go +++ b/backend/internal/service/openai_gateway_service.go @@ -504,8 +504,8 @@ type OpenAIGatewayService struct { responseHeaderFilter *responseheaders.CompiledHeaderFilter codexSnapshotThrottle *accountWriteThrottle openAIModelsCache openAIModelsCache - openaiCompatSessionResponses sync.Map - openaiCompatAnthropicDigestSessions sync.Map + openaiCompatSessionResponses sessionMemoryCache + openaiCompatAnthropicDigestSessions sessionMemoryCache // openaiCodexTurnStateOrigins: 下游会话 seed → openAICodexTurnStateOrigin, // 记录最近一次向该会话下发 x-codex-turn-state 的铸造账号,供出站守卫 // 剥离跨账号回带(openai_codex_turn_state.go)。 @@ -704,10 +704,15 @@ func (s *OpenAIGatewayService) billingDeps() *billingDeps { } } -// CloseOpenAIWSPool 关闭 OpenAI WebSocket 连接池的后台 worker 和空闲连接。 +// CloseOpenAIWSPool 关闭 OpenAI WebSocket 连接池、后台 worker 和会话缓存清理 timer。 // 应在应用优雅关闭时调用。 func (s *OpenAIGatewayService) CloseOpenAIWSPool() { - if s != nil && s.openaiWSPool != nil { + if s == nil { + return + } + s.openaiCompatSessionResponses.Close() + s.openaiCompatAnthropicDigestSessions.Close() + if s.openaiWSPool != nil { s.openaiWSPool.Close() } } diff --git a/backend/internal/service/openai_images.go b/backend/internal/service/openai_images.go index 12042b0e58..bd5b85aa0d 100644 --- a/backend/internal/service/openai_images.go +++ b/backend/internal/service/openai_images.go @@ -1,13 +1,13 @@ package service import ( - "bufio" "bytes" "context" "crypto/sha256" "encoding/base64" "encoding/hex" "encoding/json" + "errors" "fmt" "io" "mime" @@ -660,7 +660,7 @@ func (s *OpenAIGatewayService) forwardOpenAIImagesAPIKey( // 就把已经在出图的上游调用打断成 context canceled,网关记 502、不扣费,而上游那边 // 图已经生成并计费。同一端点的 OAuth 分支 forwardOpenAIImagesOAuth 以及 Grok 媒体 // 路径本来就无条件脱钩,这里对齐;上游侧仍由 ResponseHeaderTimeout 兜底。 - upstreamCtx, releaseUpstreamCtx := detachUpstreamContext(ctx) + upstreamCtx, releaseUpstreamCtx := detachUpstreamContext(ctx, s.openAIImageDrainTimeout()) defer releaseUpstreamCtx() token, _, err := s.GetAccessToken(upstreamCtx, account) @@ -1018,6 +1018,30 @@ func (s *OpenAIGatewayService) handleOpenAIImagesStreamingResponse( seenSSEData := false fallbackTooLarge := false var sseData openAISSEDataAccumulator + // Keep raw passthrough frames until their delimiter so a rejected event is + // never completed downstream by the gateway's own error frame. These strings + // share storage with sseData and are bounded by the same SSE event limits. + var pendingRawLines []string + discardRawEvent := func() { + clear(pendingRawLines) + pendingRawLines = pendingRawLines[:0] + } + flushRawEvent := func() { + defer discardRawEvent() + if clientDisconnected || len(pendingRawLines) == 0 { + return + } + for _, line := range pendingRawLines { + if _, writeErr := io.WriteString(c.Writer, line); writeErr != nil { + clientDisconnected = true + logger.LegacyPrintf("service.openai_gateway", "[OpenAI] Images stream client disconnected, continue draining upstream for billing") + return + } + } + flusher.Flush() + lastDownstreamWriteAt = time.Now() + } + defer discardRawEvent() var streamErr error finish := func() error { if direct == nil { @@ -1096,6 +1120,7 @@ func (s *OpenAIGatewayService) handleOpenAIImagesStreamingResponse( } flushSSEEvent := func() { + flushRawEvent() sseData.Flush(processSSEData) } @@ -1107,17 +1132,14 @@ func (s *OpenAIGatewayService) handleOpenAIImagesStreamingResponse( ms := int(time.Since(startTime).Milliseconds()) firstTokenMs = &ms } + rawLine := string(line) + trimmedLine := strings.TrimRight(rawLine, "\r\n") if !clientDisconnected && direct == nil { - if _, writeErr := c.Writer.Write(line); writeErr != nil { - clientDisconnected = true - logger.LegacyPrintf("service.openai_gateway", "[OpenAI] Images stream client disconnected, continue draining upstream for billing") - } else { - flusher.Flush() - lastDownstreamWriteAt = time.Now() + pendingRawLines = append(pendingRawLines, rawLine) + if trimmedLine == "" { + flushRawEvent() } } - - trimmedLine := strings.TrimRight(string(line), "\r\n") if _, ok := extractOpenAISSEDataLine(trimmedLine); ok || strings.TrimSpace(trimmedLine) == "" { sseData.AddLine(trimmedLine, processSSEData) return @@ -1151,9 +1173,15 @@ func (s *OpenAIGatewayService) handleOpenAIImagesStreamingResponse( streamInterval := s.openAIImageStreamDataInterval() keepaliveInterval := s.openAIImageStreamKeepaliveInterval() if streamInterval <= 0 && keepaliveInterval <= 0 { - reader := bufio.NewReader(resp.Body) + reader := newBoundedSSELineReader(resp.Body, s.cfg) for { - line, err := reader.ReadBytes('\n') + line, err := reader.ReadLine() + if errors.Is(err, errSSETransportLimit) { + discardRawEvent() + s.tryWriteOpenAIImagesStreamLimitError(c, flusher, &clientDisconnected, &lastDownstreamWriteAt) + _ = resp.Body.Close() + return usage, imageCounter.Count(), imageCounter.Sizes(), firstTokenMs, err + } processLine(line) if err == io.EOF { break @@ -1174,11 +1202,16 @@ func (s *OpenAIGatewayService) handleOpenAIImagesStreamingResponse( } events := make(chan readEvent, 16) done := make(chan struct{}) + queueBudget := newSSEQueueBudget(s.cfg) sendEvent := func(ev readEvent) bool { + if !queueBudget.acquire(len(ev.line), done) { + return false + } select { case events <- ev: return true case <-done: + queueBudget.release(len(ev.line)) return false } } @@ -1186,9 +1219,9 @@ func (s *OpenAIGatewayService) handleOpenAIImagesStreamingResponse( atomic.StoreInt64(&lastReadAt, time.Now().UnixNano()) go func() { defer close(events) - reader := bufio.NewReader(resp.Body) + reader := newBoundedSSELineReader(resp.Body, s.cfg) for { - line, err := reader.ReadBytes('\n') + line, err := reader.ReadLine() if len(line) > 0 { atomic.StoreInt64(&lastReadAt, time.Now().UnixNano()) } @@ -1229,12 +1262,21 @@ func (s *OpenAIGatewayService) handleOpenAIImagesStreamingResponse( for { select { case ev, ok := <-events: + if ok { + queueBudget.release(len(ev.line)) + } if !ok { flushSSEEvent() finalizeFallbackBody() return usage, imageCounter.Count(), imageCounter.Sizes(), firstTokenMs, finish() } if ev.err != nil { + if errors.Is(ev.err, errSSETransportLimit) { + discardRawEvent() + s.tryWriteOpenAIImagesStreamLimitError(c, flusher, &clientDisconnected, &lastDownstreamWriteAt) + _ = resp.Body.Close() + return usage, imageCounter.Count(), imageCounter.Sizes(), firstTokenMs, ev.err + } flushSSEEvent() return usage, imageCounter.Count(), imageCounter.Sizes(), firstTokenMs, ev.err } @@ -1805,3 +1847,13 @@ func dedupeStrings(values []string) []string { } return out } + +// Image generation may continue long enough to incur upstream costs after the +// client disconnects. Keep its bounded billing drain aligned with image idle +// configuration, while preserving a safety limit if idle checks are disabled. +func (s *OpenAIGatewayService) openAIImageDrainTimeout() time.Duration { + if timeout := s.openAIImageStreamDataInterval(); timeout > 0 { + return timeout + } + return 900 * time.Second +} diff --git a/backend/internal/service/openai_images_responses.go b/backend/internal/service/openai_images_responses.go index 36995437fd..63db0668ac 100644 --- a/backend/internal/service/openai_images_responses.go +++ b/backend/internal/service/openai_images_responses.go @@ -1,7 +1,6 @@ package service import ( - "bufio" "bytes" "context" "encoding/base64" @@ -1169,6 +1168,17 @@ func (s *OpenAIGatewayService) tryWriteOpenAIImagesStreamEvent( return true } +func (s *OpenAIGatewayService) tryWriteOpenAIImagesStreamLimitError(c *gin.Context, flusher http.Flusher, clientDisconnected *bool, lastWriteAt *time.Time) { + if c.Request != nil && c.Request.Context().Err() != nil { + return + } + payload := buildOpenAIImagesStreamErrorBodyFromUpstream(&OpenAIImagesUpstreamError{ + Code: "response_too_large", + Message: "upstream image stream exceeded transport limits", + }) + s.tryWriteOpenAIImagesStreamEvent(c, flusher, clientDisconnected, lastWriteAt, "error", payload) +} + func (s *OpenAIGatewayService) parseOpenAIImagesSSEUsageBytes(data []byte, usage *OpenAIUsage) { s.parseSSEUsageBytes(data, usage) if usage == nil || !gjson.ValidBytes(data) || gjson.GetBytes(data, "type").String() != "response.completed" { @@ -1629,9 +1639,14 @@ func (s *OpenAIGatewayService) handleOpenAIImagesOAuthStreamingResponse( streamInterval := s.openAIImageStreamDataInterval() keepaliveInterval := s.openAIImageStreamKeepaliveInterval() if streamInterval <= 0 && keepaliveInterval <= 0 { - reader := bufio.NewReader(resp.Body) + reader := newBoundedSSELineReader(resp.Body, s.cfg) for { - line, err := reader.ReadBytes('\n') + line, err := reader.ReadLine() + if errors.Is(err, errSSETransportLimit) { + s.tryWriteOpenAIImagesStreamLimitError(c, flusher, &clientDisconnected, &lastDownstreamWriteAt) + _ = resp.Body.Close() + return usage, imageCount, imageOutputSizes, firstTokenMs, err + } done, processErr := processLine(line) if processErr != nil { return usage, imageCount, imageOutputSizes, firstTokenMs, processErr @@ -1671,11 +1686,16 @@ func (s *OpenAIGatewayService) handleOpenAIImagesOAuthStreamingResponse( } events := make(chan readEvent, 16) done := make(chan struct{}) + queueBudget := newSSEQueueBudget(s.cfg) sendEvent := func(ev readEvent) bool { + if !queueBudget.acquire(len(ev.line), done) { + return false + } select { case events <- ev: return true case <-done: + queueBudget.release(len(ev.line)) return false } } @@ -1683,9 +1703,9 @@ func (s *OpenAIGatewayService) handleOpenAIImagesOAuthStreamingResponse( atomic.StoreInt64(&lastReadAt, time.Now().UnixNano()) go func() { defer close(events) - reader := bufio.NewReader(resp.Body) + reader := newBoundedSSELineReader(resp.Body, s.cfg) for { - line, err := reader.ReadBytes('\n') + line, err := reader.ReadLine() if len(line) > 0 { atomic.StoreInt64(&lastReadAt, time.Now().UnixNano()) } @@ -1726,6 +1746,9 @@ func (s *OpenAIGatewayService) handleOpenAIImagesOAuthStreamingResponse( for { select { case ev, ok := <-events: + if ok { + queueBudget.release(len(ev.line)) + } if !ok { if done, processErr := flushData(); processErr != nil { return usage, imageCount, imageOutputSizes, firstTokenMs, processErr @@ -1738,6 +1761,11 @@ func (s *OpenAIGatewayService) handleOpenAIImagesOAuthStreamingResponse( return usage, imageCount, imageOutputSizes, firstTokenMs, nil } if ev.err != nil { + if errors.Is(ev.err, errSSETransportLimit) { + s.tryWriteOpenAIImagesStreamLimitError(c, flusher, &clientDisconnected, &lastDownstreamWriteAt) + _ = resp.Body.Close() + return usage, imageCount, imageOutputSizes, firstTokenMs, ev.err + } if done, processErr := flushData(); processErr != nil { return usage, imageCount, imageOutputSizes, firstTokenMs, processErr } else if done { @@ -1819,7 +1847,7 @@ func (s *OpenAIGatewayService) forwardOpenAIImagesOAuth( len(parsed.Uploads), uploadParts, ) - upstreamCtx, releaseUpstreamCtx := detachUpstreamContext(ctx) + upstreamCtx, releaseUpstreamCtx := detachUpstreamContext(ctx, s.openAIImageDrainTimeout()) defer releaseUpstreamCtx() token, _, err := s.GetAccessToken(upstreamCtx, account) diff --git a/backend/internal/service/openai_images_stream_limit_error_test.go b/backend/internal/service/openai_images_stream_limit_error_test.go new file mode 100644 index 0000000000..a563227faf --- /dev/null +++ b/backend/internal/service/openai_images_stream_limit_error_test.go @@ -0,0 +1,243 @@ +package service + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type imageLimitTestBody struct { + *strings.Reader + closed atomic.Bool +} + +func (b *imageLimitTestBody) Close() error { + b.closed.Store(true) + return nil +} + +type imageLimitDisconnectedWriter struct { + gin.ResponseWriter + attempts int +} + +func (w *imageLimitDisconnectedWriter) Write([]byte) (int, error) { + w.attempts++ + return 0, io.ErrClosedPipe +} + +func (w *imageLimitDisconnectedWriter) WriteString(string) (int, error) { + w.attempts++ + return 0, io.ErrClosedPipe +} + +func TestImageStreamTransportLimitEmitsErrorAndPreservesUsage(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, route := range []string{"direct", "responses", "passthrough"} { + for _, async := range []bool{false, true} { + for _, limit := range []string{"line", "event_bytes", "event_lines"} { + t.Run(fmt.Sprintf("%s/async_%t/%s", route, async, limit), func(t *testing.T) { + cfg := &config.Config{Gateway: config.GatewayConfig{MaxLineSize: 1024, SSEEventMaxBytes: 4096, SSEQueueMaxBytes: 128}} + if async { + cfg.Gateway.ImageStreamDataIntervalTimeout = 1 + } + wire := "data: {\"type\":\"image_generation.partial_image\",\"b64_json\":\"AA==\",\"usage\":{\"input_tokens\":11,\"output_tokens\":7}}\n\n" + pendingTerminal := "data: {\"type\":\"image_generation.completed\",\"b64_json\":\"AA==\",\"usage\":{\"input_tokens\":999}}\n" + if route == "responses" { + wire = "data: {\"type\":\"response.in_progress\",\"response\":{\"usage\":{\"input_tokens\":11,\"output_tokens\":7}}}\n\n" + + "data: {\"type\":\"response.output_item.done\",\"item\":{\"type\":\"image_generation_call\",\"id\":\"image-pending\",\"result\":\"AA==\"}}\n\n" + pendingTerminal = "data: {\"type\":\"response.completed\",\"response\":{\"usage\":{\"input_tokens\":999},\"output\":[{\"type\":\"image_generation_call\",\"result\":\"AA==\"}]}}\n" + } + wire += pendingTerminal + switch limit { + case "line": + cfg.Gateway.MaxLineSize = 256 + wire += ":" + strings.Repeat("x", 512) + case "event_bytes": + cfg.Gateway.SSEEventMaxBytes = 256 + wire += ":" + strings.Repeat("x", 150) + "\n:" + strings.Repeat("x", 150) + case "event_lines": + cfg.Gateway.SSEEventMaxLines = 2 + wire += ":first\n:second\n" + } + wire += "\n\ndata: [DONE]\n\n" + body := &imageLimitTestBody{Reader: strings.NewReader(wire)} + resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{}, Body: body} + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/images/generations", nil) + svc := &OpenAIGatewayService{cfg: cfg} + var usage OpenAIUsage + var count int + var err error + if route == "responses" { + usage, count, _, _, err = svc.handleOpenAIImagesOAuthStreamingResponse(resp, c, time.Now(), "b64_json", "image_generation", "gpt-image-2") + } else { + var direct *OpenAIImagesRequest + if route == "direct" { + direct = &OpenAIImagesRequest{Model: "gpt-image-2", ResponseFormat: "b64_json"} + } + usage, count, _, _, err = svc.handleOpenAIImagesStreamingResponse(resp, c, time.Now(), direct) + } + require.ErrorIs(t, err, errSSETransportLimit) + require.True(t, body.closed.Load(), "transport-limit failures must release the upstream body") + wantUsage := OpenAIUsage{InputTokens: 11, OutputTokens: 7} + if route == "direct" { + wantUsage.ImageOutputTokens = 7 + } + require.Equal(t, wantUsage, usage) + require.Zero(t, count, "pending image output must not be finalized on a failed stream") + require.NotContains(t, rec.Body.String(), ".completed") + require.NotContains(t, rec.Body.String(), "[DONE]") + requireImageTransportLimitError(t, rec.Body.String()) + }) + } + } + } +} + +func TestImageStreamPassthroughPreservesRawFrames(t *testing.T) { + completed := `{"type":"image_generation.completed","b64_json":"AA==","usage":{"input_tokens":11,"output_tokens":7},"unknown":{"keep":true}}` + for _, async := range []bool{false, true} { + for _, wire := range []string{ + ": heartbeat\r\nevent: image_generation.completed\r\nid: opaque\r\ndata: " + completed + "\r\n\r\n: final comment", + "event: image_generation.completed\ndata: " + completed, + } { + t.Run(fmt.Sprintf("async_%t/bytes_%d", async, len(wire)), func(t *testing.T) { + cfg := &config.Config{Gateway: config.GatewayConfig{MaxLineSize: 1024}} + if async { + cfg.Gateway.ImageStreamDataIntervalTimeout = 1 + } + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/images/generations", nil) + body := &imageLimitTestBody{Reader: strings.NewReader(wire)} + resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{}, Body: body} + svc := &OpenAIGatewayService{cfg: cfg} + usage, count, _, _, err := svc.handleOpenAIImagesStreamingResponse(resp, c, time.Now(), nil) + require.NoError(t, err) + require.Equal(t, wire, rec.Body.String(), "passthrough must retain CRLF, comments, unknown fields and unterminated EOF bytes") + require.Equal(t, OpenAIUsage{InputTokens: 11, OutputTokens: 7}, usage) + require.Equal(t, 1, count) + }) + } + } +} + +func TestImageStreamTransportLimitSkipsDisconnectedClient(t *testing.T) { + for _, oauth := range []bool{false, true} { + for _, async := range []bool{false, true} { + t.Run(fmt.Sprintf("oauth_%t/async_%t", oauth, async), func(t *testing.T) { + cfg := &config.Config{Gateway: config.GatewayConfig{MaxLineSize: 32}} + if async { + cfg.Gateway.ImageStreamDataIntervalTimeout = 1 + } + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + c.Request = httptest.NewRequest(http.MethodPost, "/v1/images/generations", nil).WithContext(ctx) + body := &imageLimitTestBody{Reader: strings.NewReader(":" + strings.Repeat("x", 64))} + resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{}, Body: body} + svc := &OpenAIGatewayService{cfg: cfg} + var err error + if oauth { + _, _, _, _, err = svc.handleOpenAIImagesOAuthStreamingResponse(resp, c, time.Now(), "b64_json", "image_generation", "gpt-image-2") + } else { + _, _, _, _, err = svc.handleOpenAIImagesStreamingResponse(resp, c, time.Now(), nil) + } + require.ErrorIs(t, err, errSSETransportLimit) + require.True(t, body.closed.Load()) + require.Empty(t, rec.Body.String()) + }) + } + } +} + +func TestImageStreamTransportLimitDoesNotRetryFailedClientWriter(t *testing.T) { + for _, route := range []string{"direct", "responses", "passthrough"} { + for _, async := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/async_%t", route, async), func(t *testing.T) { + cfg := &config.Config{Gateway: config.GatewayConfig{MaxLineSize: 512}} + if async { + cfg.Gateway.ImageStreamDataIntervalTimeout = 1 + } + wire := "data: {\"type\":\"image_generation.partial_image\",\"b64_json\":\"AA==\",\"usage\":{\"input_tokens\":11,\"output_tokens\":7}}\n\n" + if route == "responses" { + wire = "data: {\"type\":\"response.image_generation_call.partial_image\",\"partial_image_b64\":\"AA==\",\"usage\":{\"input_tokens\":11,\"output_tokens\":7}}\n\n" + } + wire += ":" + strings.Repeat("x", 1024) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + writer := &imageLimitDisconnectedWriter{ResponseWriter: c.Writer} + c.Writer = writer + c.Request = httptest.NewRequest(http.MethodPost, "/v1/images/generations", nil) + body := &imageLimitTestBody{Reader: strings.NewReader(wire)} + resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{}, Body: body} + svc := &OpenAIGatewayService{cfg: cfg} + var usage OpenAIUsage + var err error + if route == "responses" { + usage, _, _, _, err = svc.handleOpenAIImagesOAuthStreamingResponse(resp, c, time.Now(), "b64_json", "image_generation", "gpt-image-2") + } else { + var direct *OpenAIImagesRequest + if route == "direct" { + direct = &OpenAIImagesRequest{Model: "gpt-image-2"} + } + usage, _, _, _, err = svc.handleOpenAIImagesStreamingResponse(resp, c, time.Now(), direct) + } + require.ErrorIs(t, err, errSSETransportLimit) + require.True(t, body.closed.Load()) + require.Equal(t, 11, usage.InputTokens) + require.Equal(t, 7, usage.OutputTokens) + require.Equal(t, 1, writer.attempts, "do not write a transport-limit error after the client writer has failed") + }) + } + } +} + +func requireImageTransportLimitError(t *testing.T, wire string) { + t.Helper() + errorEvents := 0 + for _, frame := range strings.Split(strings.ReplaceAll(wire, "\r\n", "\n"), "\n\n") { + var eventName string + var data []string + for _, line := range strings.Split(frame, "\n") { + if value, ok := strings.CutPrefix(line, "event:"); ok { + eventName = strings.TrimSpace(value) + } + if value, ok := strings.CutPrefix(line, "data:"); ok { + data = append(data, strings.TrimPrefix(value, " ")) + } + } + if eventName != "error" { + continue + } + errorEvents++ + var payload struct { + Type string `json:"type"` + Error struct { + Type string `json:"type"` + Code string `json:"code"` + Message string `json:"message"` + } `json:"error"` + } + require.NoError(t, json.Unmarshal([]byte(strings.Join(data, "\n")), &payload), "the error must be a standalone, parseable SSE event") + require.Equal(t, "error", payload.Type) + require.Equal(t, "upstream_error", payload.Error.Type) + require.Equal(t, "response_too_large", payload.Error.Code) + require.NotEmpty(t, payload.Error.Message) + } + require.Equal(t, 1, errorEvents) +} diff --git a/backend/internal/service/openai_messages_continuation.go b/backend/internal/service/openai_messages_continuation.go index 65bafbd544..601922c226 100644 --- a/backend/internal/service/openai_messages_continuation.go +++ b/backend/internal/service/openai_messages_continuation.go @@ -20,6 +20,16 @@ type openAICompatSessionResponseBinding struct { ExpiresAt time.Time } +func (b openAICompatSessionResponseBinding) sessionExpiresAt() time.Time { return b.ExpiresAt } +func (b openAICompatSessionResponseBinding) sessionCost() int { + return len(b.ResponseID) + len(b.TurnState) +} +func (b openAICompatSessionResponseBinding) cloneSessionValue() sessionMemoryValue { + b.ResponseID = strings.Clone(b.ResponseID) + b.TurnState = strings.Clone(b.TurnState) + return b +} + func openAICompatContinuationEnabled(account *Account, model string) bool { if account == nil || account.Type != AccountTypeAPIKey { return false diff --git a/backend/internal/service/openai_messages_digest_session.go b/backend/internal/service/openai_messages_digest_session.go index 44a49d1e39..b00697c43e 100644 --- a/backend/internal/service/openai_messages_digest_session.go +++ b/backend/internal/service/openai_messages_digest_session.go @@ -14,6 +14,13 @@ type openAICompatAnthropicDigestBinding struct { ExpiresAt time.Time } +func (b openAICompatAnthropicDigestBinding) sessionExpiresAt() time.Time { return b.ExpiresAt } +func (b openAICompatAnthropicDigestBinding) sessionCost() int { return len(b.PromptCacheKey) } +func (b openAICompatAnthropicDigestBinding) cloneSessionValue() sessionMemoryValue { + b.PromptCacheKey = strings.Clone(b.PromptCacheKey) + return b +} + func buildOpenAICompatAnthropicDigestChain(req *apicompat.AnthropicRequest) string { if req == nil { return "" @@ -52,24 +59,12 @@ func (s *OpenAIGatewayService) findOpenAICompatAnthropicDigestPromptCacheKey(acc if ns == "" { return "", "" } - chain := digestChain - for { - if raw, ok := s.openaiCompatAnthropicDigestSessions.Load(ns + chain); ok { - if binding, ok := raw.(openAICompatAnthropicDigestBinding); ok { - if binding.ExpiresAt.IsZero() || time.Now().Before(binding.ExpiresAt) { - if key := strings.TrimSpace(binding.PromptCacheKey); key != "" { - return key, chain - } - } - } - s.openaiCompatAnthropicDigestSessions.Delete(ns + chain) + if raw, chain, ok := s.openaiCompatAnthropicDigestSessions.longestDigestPrefix(ns, digestChain); ok { + if binding, ok := raw.(openAICompatAnthropicDigestBinding); ok { + return binding.PromptCacheKey, chain } - i := strings.LastIndex(chain, "-") - if i < 0 { - return "", "" - } - chain = chain[:i] } + return "", "" } func (s *OpenAIGatewayService) bindOpenAICompatAnthropicDigestPromptCacheKey(account *Account, cAPIKeyID int64, digestChain, promptCacheKey, oldDigestChain string) { diff --git a/backend/internal/service/openai_sse_data.go b/backend/internal/service/openai_sse_data.go index 3fdb70f8f4..7b14ece1ac 100644 --- a/backend/internal/service/openai_sse_data.go +++ b/backend/internal/service/openai_sse_data.go @@ -29,6 +29,7 @@ func (a *openAISSEDataAccumulator) Flush(fn func([]byte)) { return } emitOpenAISSEDataPayloads(a.lines, fn) + clear(a.lines) a.lines = a.lines[:0] } diff --git a/backend/internal/service/openai_ws_http_bridge.go b/backend/internal/service/openai_ws_http_bridge.go index 066c769c20..fa7c62e04a 100644 --- a/backend/internal/service/openai_ws_http_bridge.go +++ b/backend/internal/service/openai_ws_http_bridge.go @@ -704,11 +704,12 @@ func (s *OpenAIGatewayService) proxyOpenAIWSHTTPBridgeTurn( maxLineSize = s.cfg.Gateway.MaxLineSize } if hasResponsesClientToolMapping(clientToolMapping) { - resp.Body = newResponsesClientToolStreamBody(resp.Body, clientToolMapping, maxLineSize) + resp.Body = newResponsesClientToolStreamBody(resp.Body, clientToolMapping, maxLineSize, s.cfg) } scanner := bufio.NewScanner(resp.Body) scanBuf := getSSEScannerBuf64K() scanner.Buffer(scanBuf[:0], maxLineSize) + scanner.Split(newBoundedSSESplit(s.cfg, maxLineSize, nil)) defer putSSEScannerBuf64K(scanBuf) pendingSSEEventType := "" diff --git a/backend/internal/service/session_memory_cache.go b/backend/internal/service/session_memory_cache.go new file mode 100644 index 0000000000..857a72e6d3 --- /dev/null +++ b/backend/internal/service/session_memory_cache.go @@ -0,0 +1,244 @@ +package service + +import ( + "container/list" + "hash/maphash" + "strings" + "sync" + "time" +) + +const ( + sessionMemoryCacheMaxEntries = 16_384 + sessionMemoryCacheMaxBytes = 32 << 20 + sessionMemoryCacheSweep = time.Minute + // Includes the map/list/index entries and interface/string headers. The + // entry cap separately bounds bookkeeping even for very small values. + sessionMemoryCacheEntryCost = 512 +) + +type sessionMemoryValue interface { + sessionExpiresAt() time.Time + sessionCost() int + cloneSessionValue() sessionMemoryValue +} + +type sessionMemoryEntry struct { + key string + hash uint64 + value sessionMemoryValue + expiresAt time.Time + cost int +} + +// sessionMemoryCache keeps the original string keys and bounds both their +// count and retained bytes. Cleanup stops when a sweep finds the cache empty; +// there is no goroutine waiting for the lifetime of a service or test instance. +// The zero value is ready for use. +type sessionMemoryCache struct { + mu sync.Mutex + entries map[string]*list.Element + prefixes map[uint64][]*list.Element + lru list.List + seed maphash.Seed + bytes int + maxEntries int + maxBytes int + sweep time.Duration + timer *time.Timer + closed bool +} + +func (c *sessionMemoryCache) initLocked() { + if c.entries != nil { + return + } + c.entries = make(map[string]*list.Element) + c.prefixes = make(map[uint64][]*list.Element) + c.seed = maphash.MakeSeed() + if c.maxEntries <= 0 { + c.maxEntries = sessionMemoryCacheMaxEntries + } + if c.maxBytes <= 0 { + c.maxBytes = sessionMemoryCacheMaxBytes + } + if c.sweep <= 0 { + c.sweep = sessionMemoryCacheSweep + } +} + +func (c *sessionMemoryCache) Store(key string, value sessionMemoryValue) { + c.mu.Lock() + defer c.mu.Unlock() + if c.closed { + return + } + c.initLocked() + if current := c.entries[key]; current != nil { + c.removeLocked(current) + } + cost := sessionMemoryCacheEntryCost + len(key) + value.sessionCost() + expiresAt := value.sessionExpiresAt() + if cost > c.maxBytes || !expiresAt.After(time.Now()) { + return + } + for len(c.entries) >= c.maxEntries || c.bytes+cost > c.maxBytes { + c.removeLocked(c.lru.Back()) + } + // Never let a short slice of a request or response pin its backing body. + key = strings.Clone(key) + entry := &sessionMemoryEntry{ + key: key, hash: maphash.String(c.seed, key), value: value.cloneSessionValue(), + expiresAt: expiresAt, cost: cost, + } + element := c.lru.PushFront(entry) + c.entries[key] = element + c.prefixes[entry.hash] = append(c.prefixes[entry.hash], element) + c.bytes += cost + if c.timer == nil { + c.timer = time.AfterFunc(c.sweep, c.sweepExpired) + } +} + +func (c *sessionMemoryCache) Load(key string) (sessionMemoryValue, bool) { + c.mu.Lock() + defer c.mu.Unlock() + element := c.entries[key] + if element == nil { + return nil, false + } + entry, _ := element.Value.(*sessionMemoryEntry) + if !entry.expiresAt.After(time.Now()) { + c.removeLocked(element) + return nil, false + } + c.lru.MoveToFront(element) + return entry.value, true +} + +func (c *sessionMemoryCache) Delete(key string) { + c.mu.Lock() + defer c.mu.Unlock() + if element := c.entries[key]; element != nil { + c.removeLocked(element) + } +} + +func (c *sessionMemoryCache) removeLocked(element *list.Element) { + entry, _ := element.Value.(*sessionMemoryEntry) + delete(c.entries, entry.key) + indexed := c.prefixes[entry.hash] + for i, candidate := range indexed { + if candidate == element { + indexed[i] = indexed[len(indexed)-1] + indexed[len(indexed)-1] = nil + indexed = indexed[:len(indexed)-1] + break + } + } + if len(indexed) == 0 { + delete(c.prefixes, entry.hash) + } else { + c.prefixes[entry.hash] = indexed + } + c.bytes -= entry.cost + c.lru.Remove(element) +} + +func (c *sessionMemoryCache) sweepExpired() { + c.mu.Lock() + defer c.mu.Unlock() + c.timer = nil + if c.closed { + return + } + now := time.Now() + for element := c.lru.Back(); element != nil; { + previous := element.Prev() + entry, _ := element.Value.(*sessionMemoryEntry) + if !entry.expiresAt.After(now) { + c.removeLocked(element) + } + element = previous + } + if len(c.entries) > 0 { + c.timer = time.AfterFunc(c.sweep, c.sweepExpired) + } +} + +func (c *sessionMemoryCache) Close() { + c.mu.Lock() + defer c.mu.Unlock() + c.closed = true + if c.timer != nil { + c.timer.Stop() + c.timer = nil + } + c.entries = nil + c.prefixes = nil + c.lru.Init() + c.bytes = 0 +} + +func (c *sessionMemoryCache) ItemCount() int { + c.mu.Lock() + defer c.mu.Unlock() + return len(c.entries) +} + +// longestDigestPrefix uses incrementally hashed prefixes to avoid allocating +// and hashing ns+chain[:end] for every message. Keys remain unchanged, and a +// hash hit is checked against the full original key, including its namespace. +// Hashing and temporary storage are O(len(chain)); map lookups are O(messages). +func (c *sessionMemoryCache) longestDigestPrefix(ns, chain string) (sessionMemoryValue, string, bool) { + c.mu.Lock() + if len(c.entries) == 0 { + c.mu.Unlock() + return nil, "", false + } + seed := c.seed + c.mu.Unlock() + + type prefix struct { + hash uint64 + end int + } + prefixes := make([]prefix, 0, strings.Count(chain, "-")+1) + var hash maphash.Hash + hash.SetSeed(seed) + _, _ = hash.WriteString(ns) + start := 0 + for i := 0; i < len(chain); i++ { + if chain[i] != '-' { + continue + } + _, _ = hash.WriteString(chain[start:i]) + prefixes = append(prefixes, prefix{hash: hash.Sum64(), end: i}) + // Include the separator only in subsequent, longer prefixes. + _, _ = hash.WriteString("-") + start = i + 1 + } + _, _ = hash.WriteString(chain[start:]) + prefixes = append(prefixes, prefix{hash: hash.Sum64(), end: len(chain)}) + + c.mu.Lock() + defer c.mu.Unlock() + now := time.Now() + for i := len(prefixes) - 1; i >= 0; i-- { + candidate := prefixes[i] + for _, element := range c.prefixes[candidate.hash] { + entry, _ := element.Value.(*sessionMemoryEntry) + if !entry.expiresAt.After(now) { + // The active timer reclaims this entry. Avoid editing the + // collision bucket while it is being iterated. + continue + } + if len(entry.key) != len(ns)+candidate.end || !strings.HasPrefix(entry.key, ns) || entry.key[len(ns):] != chain[:candidate.end] { + continue + } + c.lru.MoveToFront(element) + return entry.value, chain[:candidate.end], true + } + } + return nil, "", false +} diff --git a/backend/internal/service/session_memory_cache_test.go b/backend/internal/service/session_memory_cache_test.go new file mode 100644 index 0000000000..e33bfadfe5 --- /dev/null +++ b/backend/internal/service/session_memory_cache_test.go @@ -0,0 +1,223 @@ +package service + +import ( + "context" + "fmt" + "math/rand" + "strings" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/stretchr/testify/require" +) + +func TestSessionMemoryCacheExpiresWithoutReads(t *testing.T) { + cache := &sessionMemoryCache{sweep: 5 * time.Millisecond} + t.Cleanup(cache.Close) + for i := 0; i < 100; i++ { + cache.Store(fmt.Sprintf("session-%d", i), &sessionEntry{uuid: "session", expiresAt: time.Now().Add(30 * time.Millisecond)}) + } + require.Equal(t, 100, cache.ItemCount()) + // ItemCount only observes the map; it does not trigger lazy expiration. + require.Eventually(t, func() bool { return cache.ItemCount() == 0 }, time.Second, 5*time.Millisecond) + cache.mu.Lock() + defer cache.mu.Unlock() + require.Zero(t, cache.bytes) + require.Empty(t, cache.prefixes) + require.Nil(t, cache.timer, "the last expiry must stop scheduling cleanup") +} + +func TestOpenAICompatSessionCachesExpireWithoutRevisit(t *testing.T) { + cfg := &config.Config{} + cfg.Gateway.OpenAIWS.StickyResponseIDTTLSeconds = 1 + s := &OpenAIGatewayService{cfg: cfg} + s.openaiCompatAnthropicDigestSessions.sweep = 5 * time.Millisecond + s.openaiCompatSessionResponses.sweep = 5 * time.Millisecond + t.Cleanup(s.CloseOpenAIWSPool) + account := &Account{ID: 1} + for i := 0; i < 100; i++ { + key := fmt.Sprintf("session-%d", i) + s.bindOpenAICompatAnthropicDigestPromptCacheKey(account, 1, "u:"+key, key, "") + s.bindOpenAICompatSessionResponseID(context.Background(), nil, account, key, "resp-test") + } + require.Equal(t, 100, s.openaiCompatAnthropicDigestSessions.ItemCount()) + require.Equal(t, 100, s.openaiCompatSessionResponses.ItemCount()) + require.Eventually(t, func() bool { + return s.openaiCompatAnthropicDigestSessions.ItemCount() == 0 && s.openaiCompatSessionResponses.ItemCount() == 0 + }, 2*time.Second, 10*time.Millisecond) +} + +func TestSessionMemoryCacheBoundsAndLRU(t *testing.T) { + cache := &sessionMemoryCache{maxEntries: 2, maxBytes: 2048} + t.Cleanup(cache.Close) + value := &sessionEntry{uuid: "value", expiresAt: time.Now().Add(time.Hour)} + cache.Store("first", value) + cache.Store("second", value) + _, ok := cache.Load("first") + require.True(t, ok) + cache.Store("third", value) + _, ok = cache.Load("second") + require.False(t, ok) + require.Equal(t, 2, cache.ItemCount()) + _, _, ok = cache.longestDigestPrefix("", "second-u:next") + require.False(t, ok, "eviction must also remove the prefix index") + + // An individually oversized key or value must never enter the cache. + cache.Store(strings.Repeat("x", 2048), value) + cache.Store("large-value", &sessionEntry{uuid: strings.Repeat("x", 2048), expiresAt: value.expiresAt}) + require.Equal(t, 2, cache.ItemCount()) + cache.Store("third", &sessionEntry{uuid: strings.Repeat("x", 1400), expiresAt: value.expiresAt}) + require.Equal(t, 1, cache.ItemCount(), "byte pressure must evict independently of the entry cap") + _, ok = cache.Load("third") + require.True(t, ok) + cache.mu.Lock() + require.LessOrEqual(t, cache.bytes, cache.maxBytes) + cache.mu.Unlock() +} + +func TestSessionMemoryCacheLongestPrefixKeepsRawKeySemantics(t *testing.T) { + cache := &sessionMemoryCache{} + t.Cleanup(cache.Close) + deadline := time.Now().Add(time.Hour) + // Use the historical raw namespace+chain format, without a rewritten key. + for _, chain := range []string{"u:a", "u:ab", "u:a-a:b", "u:a-a:b-u:c"} { + cache.Store("account|key|"+chain, &sessionEntry{uuid: chain, expiresAt: deadline}) + } + cache.Store("other|key|u:a-a:b-u:c-a:d", &sessionEntry{uuid: "wrong tenant", expiresAt: deadline}) + for _, tc := range []struct{ query, matched string }{ + {"u:a", "u:a"}, + {"u:ab-u:next", "u:ab"}, + {"u:abc-u:next", ""}, + {"u:a-a:b-u:c-a:d", "u:a-a:b-u:c"}, + {"u:a-a:b-u:changed", "u:a-a:b"}, + } { + value, matched, found := cache.longestDigestPrefix("account|key|", tc.query) + require.Equal(t, tc.matched != "", found, tc.query) + require.Equal(t, tc.matched, matched, tc.query) + if found { + entry, ok := value.(*sessionEntry) + require.True(t, ok) + require.Equal(t, matched, entry.uuid) + } + } + cache.Delete("account|key|u:a-a:b-u:c") + _, matched, found := cache.longestDigestPrefix("account|key|", "u:a-a:b-u:c-a:d") + require.True(t, found) + require.Equal(t, "u:a-a:b", matched) +} + +func TestSessionMemoryCacheExpiredLongestPrefixFallsBack(t *testing.T) { + cache := &sessionMemoryCache{} + t.Cleanup(cache.Close) + cache.Store("ns|u:a", &sessionEntry{uuid: "short", expiresAt: time.Now().Add(time.Hour)}) + cache.Store("ns|u:a-a:b", &sessionEntry{uuid: "long", expiresAt: time.Now().Add(time.Hour)}) + cache.mu.Lock() + entry, ok := cache.entries["ns|u:a-a:b"].Value.(*sessionMemoryEntry) + if ok { + entry.expiresAt = time.Now().Add(-time.Second) + } + cache.mu.Unlock() + require.True(t, ok) + value, matched, found := cache.longestDigestPrefix("ns|", "u:a-a:b-u:c") + require.True(t, found) + require.Equal(t, "u:a", matched) + session, ok := value.(*sessionEntry) + require.True(t, ok) + require.Equal(t, "short", session.uuid) +} + +func TestSessionMemoryCacheDigestIndexMatchesLegacyLookup(t *testing.T) { + cache := &sessionMemoryCache{} + t.Cleanup(cache.Close) + rng := rand.New(rand.NewSource(42)) + legacy := make(map[string]bool) + for i := 0; i < 500; i++ { + ns := fmt.Sprintf("%d|", rng.Intn(3)) + var parts []string + for j := 0; j <= rng.Intn(12); j++ { + parts = append(parts, fmt.Sprintf("u:%d", rng.Intn(4))) + } + chain := strings.Join(parts, "-") + cache.Store(ns+chain, &sessionEntry{uuid: chain, expiresAt: time.Now().Add(time.Hour)}) + legacy[ns+chain] = true + query := chain + "-a:next-u:later" + if rng.Intn(3) == 0 { + cache.Delete(ns + chain) + delete(legacy, ns+chain) + } + want := query + for !legacy[ns+want] { + end := strings.LastIndexByte(want, '-') + if end < 0 { + want = "" + break + } + want = want[:end] + } + _, got, found := cache.longestDigestPrefix(ns, query) + require.Equal(t, want != "", found) + require.Equal(t, want, got) + } +} + +func TestSessionMemoryCacheConcurrentClose(t *testing.T) { + cache := &sessionMemoryCache{maxEntries: 32, maxBytes: 8192, sweep: time.Millisecond} + var wg sync.WaitGroup + started := make(chan struct{}, 8) + for g := 0; g < 8; g++ { + wg.Add(1) + go func(id int) { + defer wg.Done() + for i := 0; i < 100; i++ { + key := fmt.Sprintf("ns|u:%d-a:%d", id, i) + cache.Store(key, &sessionEntry{uuid: key, expiresAt: time.Now().Add(2 * time.Millisecond)}) + if i == 0 { + started <- struct{}{} + } + cache.Load(key) + cache.longestDigestPrefix("ns|", key[3:]+"-u:next") + cache.Delete(key) + } + }(g) + } + for g := 0; g < 8; g++ { + <-started + } + cache.Close() + wg.Wait() + cache.Close() + require.Zero(t, cache.ItemCount()) + cache.mu.Lock() + defer cache.mu.Unlock() + require.Nil(t, cache.timer) + require.Zero(t, cache.bytes) +} + +func BenchmarkDigestSessionLookupMiss(b *testing.B) { + for _, n := range []int{100, 1000, 5000} { + chain := strings.TrimSuffix(strings.Repeat("u:0123456789abc-", n), "-") + b.Run(fmt.Sprintf("OpenAICompat/messages_%d", n), func(b *testing.B) { + s := &OpenAIGatewayService{} + b.Cleanup(s.CloseOpenAIWSPool) + account := &Account{ID: 1} + s.bindOpenAICompatAnthropicDigestPromptCacheKey(account, 1, "u:unrelated", "cache-key", "") + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.findOpenAICompatAnthropicDigestPromptCacheKey(account, 1, chain) + } + }) + b.Run(fmt.Sprintf("SharedStore/messages_%d", n), func(b *testing.B) { + s := NewDigestSessionStore() + b.Cleanup(s.Close) + s.Save(1, "prefix", "u:unrelated", "uuid", 1, "") + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.Find(1, "prefix", chain) + } + }) + } +} diff --git a/backend/internal/service/sse_large_image_compat_test.go b/backend/internal/service/sse_large_image_compat_test.go new file mode 100644 index 0000000000..78c86b6610 --- /dev/null +++ b/backend/internal/service/sse_large_image_compat_test.go @@ -0,0 +1,45 @@ +package service + +import ( + "bytes" + "io" + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +type largeImageBase64Reader struct{} + +func (largeImageBase64Reader) Read(p []byte) (int, error) { + for i := range p { + p[i] = 'A' + } + return len(p), nil +} + +func TestDefaultSSELimitPreservesImageFrameAbove40MiB(t *testing.T) { + // High-resolution image frames can carry more than 40 MiB of base64 data. + // Generate the input lazily so this test retains only the reader's result. + const imageBytes = 41 << 20 + const prefix = "data: {\"b64_json\":\"" + const suffix = "\"}\r\n" + wire := io.MultiReader( + strings.NewReader(prefix), + io.LimitReader(largeImageBase64Reader{}, imageBytes), + strings.NewReader(suffix+"\r\ndata: [DONE]"), + ) + reader := newBoundedSSELineReader(wire, nil) + line, err := reader.ReadLine() + require.NoError(t, err) + require.Len(t, line, len(prefix)+imageBytes+len(suffix)) + require.True(t, bytes.HasPrefix(line, []byte(prefix))) + require.True(t, bytes.HasSuffix(line, []byte(suffix))) + require.Equal(t, imageBytes, bytes.Count(line, []byte{'A'})) + line, err = reader.ReadLine() + require.NoError(t, err) + require.Equal(t, "\r\n", string(line)) + line, err = reader.ReadLine() + require.ErrorIs(t, err, io.EOF) + require.Equal(t, "data: [DONE]", string(line)) +} diff --git a/backend/internal/service/sse_transport_limits.go b/backend/internal/service/sse_transport_limits.go new file mode 100644 index 0000000000..f9c5352342 --- /dev/null +++ b/backend/internal/service/sse_transport_limits.go @@ -0,0 +1,187 @@ +package service + +import ( + "bufio" + "bytes" + "errors" + "fmt" + "io" + "sync/atomic" + + "github.com/Wei-Shaw/sub2api/internal/config" +) + +const ( + defaultSSEQueueMaxBytes = 8 << 20 + defaultSSEEventMaxLines = 4096 +) + +// sseQueueBudget bounds queued payload bytes, in addition to the channel's +// event count. A single line larger than the budget reserves the whole budget: +// legitimate image frames still pass, but cannot fill all 16 queue slots. The +// consumer's current line and the producer's next line/scanner buffer are not +// queue storage and remain subject to the line/event limits. +// +// There is one producer and one consumer. Release on dequeue, not on shutdown, +// so cancellation never depends on draining an abandoned queue. +type sseQueueBudget struct { + limit int64 + used atomic.Int64 + available chan struct{} +} + +func newSSEQueueBudget(cfg *config.Config) *sseQueueBudget { + limit := int64(defaultSSEQueueMaxBytes) + if cfg != nil && cfg.Gateway.SSEQueueMaxBytes > 0 { + limit = cfg.Gateway.SSEQueueMaxBytes + } + return &sseQueueBudget{limit: limit, available: make(chan struct{}, 1)} +} + +func (b *sseQueueBudget) weight(size int) int64 { + return min(int64(size), b.limit) +} + +func (b *sseQueueBudget) acquire(size int, done <-chan struct{}) bool { + weight := b.weight(size) + for { + select { + case <-done: + return false + default: + } + used := b.used.Load() + if weight <= b.limit-used && b.used.CompareAndSwap(used, used+weight) { + return true + } + select { + case <-done: + return false + case <-b.available: + } + } +} + +func (b *sseQueueBudget) release(size int) { + if size == 0 { + return + } + b.used.Add(-b.weight(size)) + select { + case b.available <- struct{}{}: + default: + } +} + +var errSSETransportLimit = errors.New("upstream SSE transport limit exceeded") + +type sseEventLimits struct { + maxBytes int64 + maxLines int + bytes int64 + lines int +} + +func newSSEEventLimits(cfg *config.Config, maxLineSize int) *sseEventLimits { + if maxLineSize <= 0 { + maxLineSize = defaultMaxLineSize + } + limits := &sseEventLimits{maxBytes: int64(maxLineSize), maxLines: defaultSSEEventMaxLines} + if cfg != nil { + if cfg.Gateway.SSEEventMaxBytes > 0 { + limits.maxBytes = cfg.Gateway.SSEEventMaxBytes + } + if cfg.Gateway.SSEEventMaxLines > 0 { + limits.maxLines = cfg.Gateway.SSEEventMaxLines + } + } + return limits +} + +func (l *sseEventLimits) observe(line []byte, wireBytes int) error { + if len(bytes.TrimRight(line, "\r\n")) == 0 { + l.bytes, l.lines = 0, 0 + return nil + } + if int64(wireBytes) > l.maxBytes-l.bytes || l.lines >= l.maxLines { + return l.exceeded() + } + l.bytes += int64(wireBytes) + l.lines++ + return nil +} + +func (l *sseEventLimits) exceeded() error { + // Preserve the existing upstream response_too_large error paths. This is + // an SSE framing limit, independent of JSON/protocol translation. + return fmt.Errorf("%w: %w: SSE event exceeds %d bytes or %d lines", errSSETransportLimit, bufio.ErrTooLong, l.maxBytes, l.maxLines) +} + +// newBoundedSSESplit limits complete events as well as incomplete lines. Without +// this, an upstream can bypass a single-line cap by never sending a blank line. +// next may preserve line endings or enforce the OpenAI pre-output guard. +func newBoundedSSESplit(cfg *config.Config, maxLineSize int, next bufio.SplitFunc) bufio.SplitFunc { + if next == nil { + next = bufio.ScanLines + } + limits := newSSEEventLimits(cfg, maxLineSize) + return func(data []byte, atEOF bool) (int, []byte, error) { + advance, token, err := next(data, atEOF) + if err != nil { + return advance, token, err + } + if token != nil { + if err := limits.observe(token, advance); err != nil { + return 0, nil, err + } + } else if int64(len(data)) > limits.maxBytes-limits.bytes { + return 0, nil, limits.exceeded() + } + return advance, token, nil + } +} + +// boundedSSELineReader preserves the original bytes (including CRLF and the +// final unterminated line) used by image passthrough. ReadSlice bounds individual +// allocations; oversized/incomplete lines are rejected without forwarding a +// truncated prefix as a successful SSE event. +type boundedSSELineReader struct { + reader *bufio.Reader + maxLineSize int + limits *sseEventLimits +} + +func newBoundedSSELineReader(reader io.Reader, cfg *config.Config) *boundedSSELineReader { + maxLineSize := defaultMaxLineSize + if cfg != nil && cfg.Gateway.MaxLineSize > 0 { + maxLineSize = cfg.Gateway.MaxLineSize + } + return &boundedSSELineReader{reader: bufio.NewReader(reader), maxLineSize: maxLineSize, limits: newSSEEventLimits(cfg, maxLineSize)} +} + +func (r *boundedSSELineReader) ReadLine() ([]byte, error) { + var line []byte + for { + part, err := r.reader.ReadSlice('\n') + if len(part) > r.maxLineSize-len(line) || (len(bytes.TrimRight(part, "\r\n")) != 0 || len(line) != 0) && int64(len(line)+len(part)) > r.limits.maxBytes-r.limits.bytes { + return nil, r.limits.exceeded() + } + line = append(line, part...) + if err == bufio.ErrBufferFull { + continue + } + if len(line) > 0 { + if limitErr := r.limits.observe(line, len(line)); limitErr != nil { + return nil, limitErr + } + } + return line, err + } +} + +func (s *AntigravityGatewayService) antigravitySSEConfig() *config.Config { + if s == nil || s.settingService == nil { + return nil + } + return s.settingService.cfg +} diff --git a/backend/internal/service/sse_transport_limits_test.go b/backend/internal/service/sse_transport_limits_test.go new file mode 100644 index 0000000000..5be85a3d05 --- /dev/null +++ b/backend/internal/service/sse_transport_limits_test.go @@ -0,0 +1,313 @@ +package service + +import ( + "bufio" + "context" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/apicompat" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func TestSSEQueueBudgetBackpressureAndCancellation(t *testing.T) { + cfg := &config.Config{Gateway: config.GatewayConfig{SSEQueueMaxBytes: 64}} + budget := newSSEQueueBudget(cfg) + done := make(chan struct{}) + require.True(t, budget.acquire(48, done)) + acquired := make(chan bool, 1) + go func() { acquired <- budget.acquire(32, done) }() + select { + case <-acquired: + t.Fatal("queue accepted more bytes than its budget") + case <-time.After(20 * time.Millisecond): + } + budget.release(48) + require.True(t, <-acquired) + budget.release(32) + + // Large image frames may occupy the budget alone, without reducing the + // configured per-line limit to the (much smaller) queue budget. + require.True(t, budget.acquire(1024, done)) + require.Equal(t, int64(64), budget.used.Load()) + go func() { acquired <- budget.acquire(1, done) }() + select { + case <-acquired: + t.Fatal("queued another payload alongside an oversized frame") + case <-time.After(20 * time.Millisecond): + } + close(done) + select { + case ok := <-acquired: + require.False(t, ok) + case <-time.After(time.Second): + t.Fatal("cancellation did not release queue producer") + } + budget.release(1024) + require.Zero(t, budget.used.Load()) + require.False(t, budget.acquire(1, done)) +} + +func TestBoundedSSESplitRejectsUndelimitedEvents(t *testing.T) { + for _, tc := range []struct { + name string + gateway config.GatewayConfig + wire string + }{ + {"lines", config.GatewayConfig{SSEEventMaxLines: 4}, strings.Repeat(": keepalive\n", 5)}, + {"bytes", config.GatewayConfig{SSEEventMaxBytes: 20}, strings.Repeat("data: abcd\n", 3)}, + {"incomplete_line", config.GatewayConfig{SSEEventMaxBytes: 20}, "data: " + strings.Repeat("a", 32)}, + } { + t.Run(tc.name, func(t *testing.T) { + scanner := bufio.NewScanner(strings.NewReader(tc.wire)) + scanner.Split(newBoundedSSESplit(&config.Config{Gateway: tc.gateway}, 1<<20, nil)) + for scanner.Scan() { + } + require.ErrorIs(t, scanner.Err(), errSSETransportLimit) + require.ErrorIs(t, scanner.Err(), bufio.ErrTooLong) + }) + } +} + +func TestBoundedSSESplitResetsAtEventBoundaryAndPreservesEOF(t *testing.T) { + cfg := &config.Config{Gateway: config.GatewayConfig{SSEEventMaxBytes: 11, SSEEventMaxLines: 1}} + scanner := bufio.NewScanner(strings.NewReader("data: abcd\n\ndata: last")) + scanner.Split(newBoundedSSESplit(cfg, 1<<20, nil)) + var lines []string + for scanner.Scan() { + lines = append(lines, scanner.Text()) + } + require.NoError(t, scanner.Err()) + require.Equal(t, []string{"data: abcd", "", "data: last"}, lines) +} + +func TestBoundedSSELineReaderPreservesLargeImageFrame(t *testing.T) { + payload := "data: {\"b64_json\":\"" + strings.Repeat("A", 128<<10) + "\"}\r\n" + cfg := &config.Config{Gateway: config.GatewayConfig{MaxLineSize: 256 << 10, SSEQueueMaxBytes: 1024}} + reader := newBoundedSSELineReader(strings.NewReader(payload+"\r\n"+"data: [DONE]"), cfg) + line, err := reader.ReadLine() + require.NoError(t, err) + require.Equal(t, payload, string(line)) + line, err = reader.ReadLine() + require.NoError(t, err) + require.Equal(t, "\r\n", string(line)) + line, err = reader.ReadLine() + require.ErrorIs(t, err, io.EOF) + require.Equal(t, "data: [DONE]", string(line)) +} + +func TestBoundedSSELineReaderRejectsOversizeWithoutTruncatedPrefix(t *testing.T) { + cfg := &config.Config{Gateway: config.GatewayConfig{MaxLineSize: 4096, SSEEventMaxBytes: 8192}} + reader := newBoundedSSELineReader(strings.NewReader("data: "+strings.Repeat("A", 64<<10)), cfg) + line, err := reader.ReadLine() + require.Nil(t, line) + require.ErrorIs(t, err, errSSETransportLimit) +} + +func TestGatewayStreamingUndelimitedEventFailsWithoutSuccessfulTerminal(t *testing.T) { + gin.SetMode(gin.TestMode) + svc := newStreamingResponseTestGatewayService() + svc.cfg.Gateway.SSEEventMaxLines = 4 + svc.cfg.Gateway.SSEQueueMaxBytes = 128 + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) + wire := "data: {\"type\":\"message_start\",\"message\":{\"usage\":{\"input_tokens\":3}}}\n\n" + strings.Repeat(": malformed event\n", 5) + "\ndata: {\"type\":\"message_stop\"}\n\n" + resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(wire))} + defer func() { _ = resp.Body.Close() }() + result, err := svc.handleStreamingResponse(context.Background(), resp, c, &Account{ID: 1}, time.Now(), "model", "model", false) + require.ErrorIs(t, err, errSSETransportLimit) + require.NotNil(t, result) + require.Equal(t, 3, result.usage.InputTokens) + require.Contains(t, rec.Body.String(), "response_too_large") + require.NotContains(t, rec.Body.String(), "message_stop") +} + +func TestAnthropicNativePumpLargeLineBudgetAndStop(t *testing.T) { + cfg := &config.Config{Gateway: config.GatewayConfig{SSEQueueMaxBytes: 64}} + scanner := bufio.NewScanner(strings.NewReader(strings.Repeat(strings.Repeat("x", 1024)+"\n", 32))) + pump := newAnthropicNativeLinePump(scanner, time.Second, cfg) + line, err := pump.next() + require.NoError(t, err) + require.Len(t, line, 1024) + pump.stop() + // The producer must stop even if another oversized payload already occupies + // the entire queue budget. Draining here observes channel closure only. + deadline := time.After(time.Second) + for { + select { + case _, ok := <-pump.events: + if !ok { + return + } + case <-deadline: + t.Fatal("line pump remained blocked after stop") + } + } +} + +func TestSSETransportDefaultsAndFirstOutputGuardCompose(t *testing.T) { + require.Equal(t, int64(defaultSSEQueueMaxBytes), newSSEQueueBudget(&config.Config{}).limit) + limits := newSSEEventLimits(&config.Config{}, 1234) + require.Equal(t, int64(1234), limits.maxBytes) + require.Equal(t, defaultSSEEventMaxLines, limits.maxLines) + innerErr := errors.New("pre-output guard") + scanner := bufio.NewScanner(strings.NewReader("data: test\n")) + scanner.Split(newBoundedSSESplit(nil, 1024, func([]byte, bool) (int, []byte, error) { return 0, nil, innerErr })) + require.False(t, scanner.Scan()) + require.ErrorIs(t, scanner.Err(), innerErr) +} + +func TestSSEConfiguredLargeFrameLimitRemainsAvailable(t *testing.T) { + defaults := newBoundedSSELineReader(strings.NewReader(""), nil) + require.Equal(t, 500<<20, defaults.maxLineSize) + cfg := &config.Config{Gateway: config.GatewayConfig{MaxLineSize: 64 << 20}} + configured := newBoundedSSELineReader(strings.NewReader(""), cfg) + require.Equal(t, 64<<20, configured.maxLineSize) + require.Equal(t, int64(64<<20), configured.limits.maxBytes) +} + +type sseTransportFailureReader struct{ err error } + +func (r sseTransportFailureReader) Read([]byte) (int, error) { return 0, r.err } + +func TestAnthropicCompatTransportFailureNeverFinalizesSuccess(t *testing.T) { + gin.SetMode(gin.TestMode) + cfg := &config.Config{Gateway: config.GatewayConfig{MaxLineSize: 1 << 20, SSEEventMaxLines: 4, SSEQueueMaxBytes: 128}} + gateway := &GatewayService{cfg: cfg} + openai := &OpenAIGatewayService{cfg: cfg} + mapping := apicompat.ResponsesClientToolMapping{} + calls := []struct { + name string + stream bool + call func(*http.Response, *gin.Context) (int, error) + }{ + {"gateway_cc_buffered", false, func(resp *http.Response, c *gin.Context) (int, error) { + r, e := gateway.handleCCBufferedFromAnthropic(resp, c, "m", "m", nil, time.Now()) + if r == nil { + return 0, e + } + return r.Usage.InputTokens, e + }}, + {"gateway_responses_buffered", false, func(resp *http.Response, c *gin.Context) (int, error) { + r, e := gateway.handleResponsesBufferedStreamingResponse(resp, c, "m", "m", nil, time.Now(), mapping) + if r == nil { + return 0, e + } + return r.Usage.InputTokens, e + }}, + {"native_cc_buffered", false, func(resp *http.Response, c *gin.Context) (int, error) { + r, e := openai.handleCCBufferedFromNativeAnthropic(resp, c, "m", "m", "m", nil, time.Now()) + if r == nil { + return 0, e + } + return r.Usage.InputTokens, e + }}, + {"native_responses_buffered", false, func(resp *http.Response, c *gin.Context) (int, error) { + r, e := openai.handleResponsesBufferedFromNativeAnthropic(resp, c, "m", "m", "m", nil, time.Now(), mapping) + if r == nil { + return 0, e + } + return r.Usage.InputTokens, e + }}, + {"native_cc_stream", true, func(resp *http.Response, c *gin.Context) (int, error) { + r, e := openai.handleCCStreamingFromNativeAnthropic(resp, c, "m", "m", "m", nil, time.Now()) + if r == nil { + return 0, e + } + return r.Usage.InputTokens, e + }}, + {"native_responses_stream", true, func(resp *http.Response, c *gin.Context) (int, error) { + r, e := openai.handleResponsesStreamingFromNativeAnthropic(resp, c, "m", "m", "m", nil, time.Now(), mapping) + if r == nil { + return 0, e + } + return r.Usage.InputTokens, e + }}, + } + prefix := "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_test\",\"model\":\"m\",\"usage\":{\"input_tokens\":3}}}\n\n" + for _, call := range calls { + for _, failure := range []string{"event_limit", "cancel", "truncated"} { + t.Run(call.name+"/"+failure, func(t *testing.T) { + var tail io.Reader + switch failure { + case "event_limit": + tail = strings.NewReader(strings.Repeat(": missing delimiter\n", 5)) + case "cancel": + tail = sseTransportFailureReader{context.Canceled} + default: + tail = strings.NewReader("") + } + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/", nil) + resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{}, Body: io.NopCloser(io.MultiReader(strings.NewReader(prefix), tail))} + defer func() { _ = resp.Body.Close() }() + usage, err := call.call(resp, c) + require.Error(t, err) + if failure == "event_limit" { + require.ErrorIs(t, err, errSSETransportLimit) + } + if failure == "cancel" { + require.ErrorIs(t, err, context.Canceled) + } + require.Equal(t, 3, usage) + if !call.stream { + require.Equal(t, http.StatusBadGateway, rec.Code) + } + require.NotContains(t, rec.Body.String(), "response.completed") + require.NotContains(t, rec.Body.String(), "data: [DONE]") + }) + } + } +} + +func TestImageStreamLimitDoesNotFinalizePendingTerminal(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, async := range []bool{false, true} { + for _, oauth := range []bool{false, true} { + name := "direct" + if oauth { + name = "responses" + } + if async { + name += "_async" + } else { + name += "_sync" + } + t.Run(name, func(t *testing.T) { + cfg := &config.Config{Gateway: config.GatewayConfig{MaxLineSize: 1024, SSEQueueMaxBytes: 128}} + if async { + cfg.Gateway.ImageStreamDataIntervalTimeout = 1 + } + svc := &OpenAIGatewayService{cfg: cfg} + wire := "data: {\"type\":\"image_generation.completed\",\"b64_json\":\"AA==\"}\n" + if oauth { + wire = "data: {\"type\":\"response.completed\",\"response\":{\"output\":[{\"type\":\"image_generation_call\",\"result\":\"AA==\"}]}}\n" + } + wire += ":" + strings.Repeat("x", 2048) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/images/generations", nil) + resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(wire))} + defer func() { _ = resp.Body.Close() }() + var err error + if oauth { + _, _, _, _, err = svc.handleOpenAIImagesOAuthStreamingResponse(resp, c, time.Now(), "b64_json", "image_generation", "gpt-image-2") + } else { + _, _, _, _, err = svc.handleOpenAIImagesStreamingResponse(resp, c, time.Now(), &OpenAIImagesRequest{Model: "gpt-image-2", ResponseFormat: "b64_json"}) + } + require.ErrorIs(t, err, errSSETransportLimit) + require.NotContains(t, rec.Body.String(), "image_generation.completed") + require.NotContains(t, rec.Body.String(), "response.completed") + }) + } + } +} diff --git a/deploy/EDGE_SECURITY.md b/deploy/EDGE_SECURITY.md index 5e9ab10fb8..0d4581ecaa 100644 --- a/deploy/EDGE_SECURITY.md +++ b/deploy/EDGE_SECURITY.md @@ -1,8 +1,8 @@ # Edge and HTTP Ingress Security -Sub2API supports long-lived SSE and WebSocket requests. Protect the request -ingress without imposing a response `WriteTimeout`: a write deadline would -terminate healthy long generations and streams. +Sub2API supports long-lived SSE and WebSocket requests. Protect request ingress +and individual socket operations without imposing a fixed timeout on the entire +response. Healthy generations can remain open while an upstream is thinking. ## Application defaults @@ -15,6 +15,50 @@ terminate healthy long generations and streams. image, video, and batch-image endpoints. - `gateway.text_max_body_size: 33554432` limits the known pure-text `/embeddings` and `/alpha/search` endpoints to 32 MiB. +- `gateway.request_body_memory_budget_bytes: 1073741824` shares a 1 GiB + buffering budget across gateway routes and aliases. Chunk allocations, the + contiguous body copy, decompressed output, JSON normalization, and a Zstd + decoder reservation are charged before allocation. Each phase releases the + intermediate allocations it no longer references: chunks after assembly, + compressed input and decoder workspace after decoding, and owned input after + normalization. The final body allocation stays charged until the handler + returns, including throughout a long SSE response. A preread buffer that may + still be referenced by middleware stays charged alongside a normalized copy. + Exhaustion returns 503 with `Retry-After`; a single-request + size violation remains 413. Set this budget to fit the instance's memory, + leaving headroom for connections, conversion state, caches and GC. This is + conservative ingress accounting, not a hard bound on total heap or RSS. +- Compressed request output is capped at 64 MiB, with overflow rejected rather + than truncated. Zstd additionally has an 8 MiB window cap and one decoder + worker per request. +- `gateway.request_body_read_timeout_seconds: 120` bounds a stalled body read; + `gateway.downstream_write_timeout_seconds: 120` bounds each write/flush. + Successful operations clear their deadline, so upstream thinking does not + consume a whole-response time budget. Zero disables the corresponding limit. +- `gateway.max_line_size: 524288000` preserves the 500 MiB SSE line default + required by large base64 4K images, image-generation output and multi-image + responses. Upgrading does not silently lower this compatibility limit. + `sse_event_max_bytes: 0` inherits that cap for each complete event and + `sse_event_max_lines: 4096` also bounds streams of short lines without a blank + delimiter. `sse_queue_max_bytes: 8388608` bounds queued payload bytes; a line + larger than 8 MiB can occupy the queue alone, up to the line/event cap. + The consumer's current line and producer's scanner/read buffer are additional + bounded storage. The 8 MiB queue budget does not reduce the maximum size of + one image frame. Lower line/event limits only when the supported models and + output sizes fit them. Explicit event byte/line settings also apply to Grok + billing-ping and client-tool prefilters. +- Detached HTTP upstream attempts may continue collecting late billing usage + after client cancellation, but only for a finite drain window. The window + follows the stream data interval timeout (180 seconds by default). OpenAI + image API-key/OAuth forwarding uses the image timeout (900 seconds by + default); Grok media retains the general drain timeout. Incoming pings do not + restart the window. + This replaces the previously unlimited post-disconnect drain: when the + window expires, the attempt is cancelled and only usage observed before + cancellation is available for settlement. Final usage arriving later may be + lost even if the provider continues generating and charging. Disabling the + stream idle timeout does not disable this drain safety limit (180 seconds; + OpenAI image API-key/OAuth forwarding retains a 900-second fallback). - H2C defaults to 50 concurrent streams per connection, a 2 MiB connection upload window, and a 512 KiB stream upload window. - Invalid credential abuse is limited in process by trusted client IP (IPv6 @@ -22,10 +66,56 @@ terminate healthy long generations and streams. per-instance safety net; multi-instance enforcement still belongs at the load balancer, CDN, or WAF. -Do not add a single application-wide request semaphore: an SSE request may -legitimately occupy it for many minutes. Apply connection and unauthenticated -request controls at the edge; authenticated user/API-key concurrency remains -the application's responsibility. +Do not replace these controls with a single application-wide request semaphore: +an SSE request may legitimately occupy it for many minutes. Apply connection +and unauthenticated request controls at the edge; authenticated user/API-key +concurrency and buffered request bytes remain the application's responsibility. + +Compatibility session caches (digest sessions, Responses continuation bindings +and Anthropic digest bindings) each have fixed limits of 16,384 entries and +32 MiB of accounted storage, including 512 bytes of bookkeeping per entry. +These limits are not currently configurable. The least recently used entry is +evicted when either limit is reached, even if its TTL has not expired; a TTL is +therefore not a guarantee that a continuation binding remains available. Active +expiry scans run at most once a minute while the cache is nonempty, and shutdown +stops cleanup. Monitor 503 body-budget rejections, response-too-large errors, +allocation rate, retained heap after GC, goroutine counts, usage-worker queues +and database connection waits when tuning capacity. Notification queues may +skip best-effort messages on overload or shutdown and log a dropped count; +committed-charge persistence is not dropped by that notification policy. +When the platform-quota flusher is disabled, its quota mirror update now runs +inside the usage task with a separate five-second database deadline. Failures +remain counted and logged for reconciliation; this path has no durable automatic +retry. The main charge is committed idempotently before this mirror update. +With the default `gateway.usage_record.overflow_policy: sync`, a full usage +queue executes the task in the submitting handler. Database latency can +therefore delay usage submission and handler completion by up to the separate +five-second quota persistence attempt, in addition to the other usage work. +The configured worker count is not a hard global limit on database concurrency. + +## Sizing the request-body budget + +Size `request_body_memory_budget_bytes` for the final body allocations retained +by all active requests, plus peak workspace for requests currently being read, +decoded or normalized. Streaming duration increases the number of retained +bodies even after their upload has finished. The budget is not just the number +of simultaneous uploads, and releasing an allocation's charge does not force Go +to reclaim that unreachable memory immediately. + +For example, 200 long-lived streams retaining 4 MiB each account for about +800 MiB before new uploads and decoding. Another 32 concurrent Zstd decoders +can reserve 256 MiB of window space alone, exceeding the default 1 GiB budget +before their input/output buffers are counted. Increase the budget for such a +workload only with sufficient instance memory, or reduce concurrency/request +sizes. Leave separate memory headroom for SSE frames (which may be larger than +the queue budget), conversion state, caches, connections and GC. Setting the +budget to `0` disables ingress memory admission rather than limiting RSS. + +Legacy Read tool-call completion still validates the growing JSON argument +prefix. Incremental storage removes repeated prefix allocations, but validation +CPU can remain quadratic for large arguments delivered in many small deltas. +Measure this separately from allocation savings; cumulative bytes allocated in +benchmarks are not retained heap or RSS. ## Trusted client IPs diff --git a/deploy/config.example.yaml b/deploy/config.example.yaml index a4a32027bd..fe63434873 100644 --- a/deploy/config.example.yaml +++ b/deploy/config.example.yaml @@ -254,6 +254,15 @@ gateway: # Max request body size in bytes (default: 256MB) # 请求体最大字节数(默认 256MB) max_body_size: 268435456 + # Per-instance ingress allocation budget. Unreferenced intermediates are released after each phase. + # Final bodies (and still-referenced preread buffers) remain charged until the handler returns. + # Include all concurrent long-lived requests and upload/decode workspace; see EDGE_SECURITY.md. + # 实例级请求体分配预算;超出返回 503 + Retry-After,0 禁用。按容器内存预留业务/GC空间。 + request_body_memory_budget_bytes: 1073741824 + # Individual socket read/write idle deadlines, not the entire SSE lifetime; 0 disables. + # 上传单次读取、下游单次写入/flush 超时(秒),不会限制正常长流的总时长;0 禁用。 + request_body_read_timeout_seconds: 120 + downstream_write_timeout_seconds: 120 # Pure-text endpoint body limit (embeddings and alpha/search), default 32 MiB. # 纯文本端点请求体上限(embeddings、alpha/search),默认 32 MiB。 text_max_body_size: 33554432 @@ -539,9 +548,16 @@ gateway: # Max image requests waiting in this process when overflow_mode=wait, 0=unlimited # wait 模式当前进程允许排队等待的图片请求数,0=不限制 max_waiting_requests: 100 - # SSE max line size in bytes (default: 40MB) - # SSE 单行最大字节数(默认 40MB) - max_line_size: 41943040 + # SSE max line size in bytes (default: 500 MiB, including large inline 4K images) + # SSE 单行最大字节数(默认 500 MiB,兼容含大尺寸 4K 图片的响应) + max_line_size: 524288000 + # Queue byte budget. One larger line may be transferred alone, bounded by max_line_size. + # 队列按字节限流;超过预算的单行只能独占传递,仍受 max_line_size 硬上限约束。 + sse_queue_max_bytes: 8388608 + # Accumulated event byte limit (0 inherits max_line_size) and nonempty line limit. + # 事件累计字节上限(0 继承单行上限)与行数上限;持续短行也不能无界积累。 + sse_event_max_bytes: 0 + sse_event_max_lines: 4096 # Log upstream error response body summary (safe/truncated; does not log request content) # 记录上游错误响应体摘要(安全/截断;不记录请求内容) log_upstream_error_body: true diff --git a/docs/agent-resource-safety.md b/docs/agent-resource-safety.md new file mode 100644 index 0000000000..23e4526f58 --- /dev/null +++ b/docs/agent-resource-safety.md @@ -0,0 +1,15 @@ +# Agent rules for concurrency and resource safety + +These rules apply when changing request ingestion, HTTP/SSE transport, protocol conversion, asynchronous usage/billing work, notifications, or in-memory caches. They supplement the repository protocol translation and billing rules. + +- Never capture `*gin.Context`, a response writer, or a pooled/mutable request object in work that can outlive the handler. Compute immutable billing, routing, model, and logging snapshots before enqueueing. `c.Copy()` is not a substitute for explicit ownership of referenced data. +- Request buffering must use the shared ingress memory budget before allocating, including unknown-length uploads, decompression, normalization, and contiguous copies. Per-user concurrency acquired after reading a body does not protect ingress. Distinguish temporary capacity exhaustion (503 with retry guidance) from a per-request size violation (413); never turn either into a successful or truncated request. +- Bound decompressor window/memory and internal concurrency as well as decoded output. Read one byte beyond an output limit to detect overflow. Do not assume `io.LimitReader` outside a decoder bounds its internal allocations. +- Bound streaming data at the line, accumulated event, and queued-byte levels. A channel capacity limits item count, not memory. Document any single-item exception and its hard size cap. A sequence of short lines, comments, or heartbeats must not bypass event bounds or cancellation/drain budgets. +- Use per-operation upload/read and downstream write/flush deadlines for long-lived HTTP streams. Do not impose a short deadline on the entire healthy stream. After client cancellation, any upstream drain for late billing usage must have a finite budget and release its body, timers, goroutines, and concurrency slots. Resource limits and truncated streams must never manufacture a successful terminal event. +- No unbounded per-request background goroutines or queues for persistence, notifications, or retries. Reuse a bounded executor, define overload behavior, give I/O an explicit deadline, and integrate shutdown. `context.WithoutCancel` alone is not an I/O timeout. Financial work must not be silently dropped; notification work may be best effort with observable drops. +- In-memory caches need active expiry and explicit entry/byte bounds. A timestamp checked only on lookup does not reclaim abandoned keys. Avoid one timer/goroutine per key and unbounded scans or network I/O under shared locks; tie background cleanup to service shutdown. +- Keep work proportional to input/output size. Avoid growing-string concatenation per delta, repeated whole-prefix copies/hashes, and repeated full JSON decoding on hot paths. Preserve protocol compatibility through RelayKit under the rules above; performance work does not authorize a local translator or changing billing semantics. +- For an already-active legacy converter, storage-only maintenance must preserve the same mappings, emitted events, state transitions, signatures, usage and public snapshots. Retain all compatibility regressions and verify size-scaling allocations. This does not authorize new translation behavior, restored fallbacks, or expanded legacy coverage; those changes still require RelayKit first. +- Treat zero-copy strings/slices, pooled buffers, and cached objects as immutable while borrowed. Do not return storage to a pool, mutate it, or retain a small slice of a large buffer across asynchronous boundaries without an explicit ownership/copy policy. +- For changes to these boundaries, add focused regression coverage for overload, cancellation, expiry, and shutdown as applicable; run affected tests with `-race`. Use representative size-scaling benchmarks for algorithm changes and report cumulative allocations separately from retained heap/RSS. Keep configuration defaults, validation, and deployment examples consistent, and regenerate Wire after lifecycle/DI changes.