diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go index c42f32d977..60d6962c2c 100644 --- a/backend/internal/config/config.go +++ b/backend/internal/config/config.go @@ -1399,7 +1399,9 @@ type GatewayOpenAIWSConfig struct { ClientReadLimitBytes int64 `mapstructure:"client_read_limit_bytes"` // HTTPBridgeEnabled: 首包过大时,保持客户端 WS,改用 HTTP Responses 上游。 HTTPBridgeEnabled bool `mapstructure:"http_bridge_enabled"` - // HTTPBridgeThresholdBytes: 触发 HTTP bridge 的入站 WS payload 阈值。 + // HTTPBridgeThresholdBytes caps the first-message size from which a WebSocket session is + // bridged to HTTP. Zero (the default) follows the limit announced by the upstream handshake + // (x-codex-websocket-max-message-bytes) and falls back to 15 MiB until one is known. HTTPBridgeThresholdBytes int64 `mapstructure:"http_bridge_threshold_bytes"` // Feature 开关:v2 优先于 v1 @@ -2570,7 +2572,7 @@ func setDefaults() { viper.SetDefault("gateway.openai_ws.prewarm_generate_enabled", false) viper.SetDefault("gateway.openai_ws.client_read_limit_bytes", 64*1024*1024) viper.SetDefault("gateway.openai_ws.http_bridge_enabled", true) - viper.SetDefault("gateway.openai_ws.http_bridge_threshold_bytes", 15*1024*1024) + viper.SetDefault("gateway.openai_ws.http_bridge_threshold_bytes", 0) viper.SetDefault("gateway.openai_ws.responses_websockets", false) viper.SetDefault("gateway.openai_ws.responses_websockets_v2", true) viper.SetDefault("gateway.openai_ws.max_conns_per_account", 128) @@ -3667,9 +3669,6 @@ func (c *Config) Validate() error { if c.Gateway.OpenAIWS.HTTPBridgeThresholdBytes < 0 { return fmt.Errorf("gateway.openai_ws.http_bridge_threshold_bytes must be non-negative") } - if c.Gateway.OpenAIWS.HTTPBridgeEnabled && c.Gateway.OpenAIWS.HTTPBridgeThresholdBytes == 0 { - return fmt.Errorf("gateway.openai_ws.http_bridge_threshold_bytes must be positive when http_bridge_enabled is true") - } if c.Gateway.OpenAIWS.FallbackCooldownSeconds < 0 { return fmt.Errorf("gateway.openai_ws.fallback_cooldown_seconds must be non-negative") } diff --git a/backend/internal/config/config_test.go b/backend/internal/config/config_test.go index 77bc19df0a..a6b393ef04 100644 --- a/backend/internal/config/config_test.go +++ b/backend/internal/config/config_test.go @@ -672,8 +672,8 @@ func TestLoadDefaultOpenAIWSConfig(t *testing.T) { if !cfg.Gateway.OpenAIWS.HTTPBridgeEnabled { t.Fatalf("Gateway.OpenAIWS.HTTPBridgeEnabled = false, want true") } - if cfg.Gateway.OpenAIWS.HTTPBridgeThresholdBytes != 15*1024*1024 { - t.Fatalf("Gateway.OpenAIWS.HTTPBridgeThresholdBytes = %d, want %d", cfg.Gateway.OpenAIWS.HTTPBridgeThresholdBytes, 15*1024*1024) + if cfg.Gateway.OpenAIWS.HTTPBridgeThresholdBytes != 0 { + t.Fatalf("Gateway.OpenAIWS.HTTPBridgeThresholdBytes = %d, want 0 (follow upstream)", cfg.Gateway.OpenAIWS.HTTPBridgeThresholdBytes) } if cfg.Gateway.OpenAIWS.RetryBackoffInitialMS != 120 { t.Fatalf("Gateway.OpenAIWS.RetryBackoffInitialMS = %d, want 120", cfg.Gateway.OpenAIWS.RetryBackoffInitialMS) diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index b714bf6bcd..a00e568ced 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -2554,6 +2554,8 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { c.Request = c.Request.WithContext(ctx) } + clientReadLimit := service.ResolveOpenAIWSClientReadLimitBytes(h.cfg) + service.SetOpenAIWSClientMaxMessageBytesHeader(c.Writer.Header(), clientReadLimit) wsConn, err := coderws.Accept(c.Writer, c.Request, &coderws.AcceptOptions{ CompressionMode: coderws.CompressionContextTakeover, }) @@ -2572,7 +2574,7 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { defer func() { _ = wsConn.CloseNow() }() - wsConn.SetReadLimit(service.ResolveOpenAIWSClientReadLimitBytes(h.cfg)) + wsConn.SetReadLimit(clientReadLimit) firstMessageTimeout := service.ResolveOpenAIWSClientFirstMessageTimeout(h.cfg) msgType, firstMessage, err := service.ReadOpenAIWSClientMessage( diff --git a/backend/internal/handler/openai_gateway_handler_test.go b/backend/internal/handler/openai_gateway_handler_test.go index 5ee7cbde51..b7df2c595e 100644 --- a/backend/internal/handler/openai_gateway_handler_test.go +++ b/backend/internal/handler/openai_gateway_handler_test.go @@ -1132,6 +1132,26 @@ func TestOpenAIResponsesWebSocket_FirstMessageTimeoutUsesConfig(t *testing.T) { }, time.Second, 10*time.Millisecond) } +func TestOpenAIResponsesWebSocket_AnnouncesClientReadLimit(t *testing.T) { + gin.SetMode(gin.TestMode) + + h := newOpenAIHandlerForPreviousResponseIDValidation(t, nil) + h.cfg = &config.Config{} + h.cfg.Gateway.OpenAIWS.ClientReadLimitBytes = 96 * 1024 * 1024 + h.cfg.Gateway.OpenAIWS.ClientFirstMessageTimeoutSeconds = 1 + wsServer := newOpenAIWSHandlerTestServer(t, h, middleware.AuthSubject{UserID: 1, Concurrency: 1}) + defer wsServer.Close() + + dialCtx, cancelDial := context.WithTimeout(context.Background(), 3*time.Second) + clientConn, resp, err := coderws.Dial(dialCtx, "ws"+strings.TrimPrefix(wsServer.URL, "http")+"/openai/v1/responses", nil) + cancelDial() + require.NoError(t, err) + defer func() { _ = clientConn.CloseNow() }() + + require.NotNil(t, resp) + require.Equal(t, "100663296", resp.Header.Get("x-codex-websocket-max-message-bytes")) +} + func TestOpenAIResponsesWebSocket_IngressLeaseReleasedOnEarlyReturn(t *testing.T) { gin.SetMode(gin.TestMode) cache := &concurrencyCacheMock{ diff --git a/backend/internal/service/openai_ws_forwarder_ingress.go b/backend/internal/service/openai_ws_forwarder_ingress.go index 81d4f24dd7..5f30e486a4 100644 --- a/backend/internal/service/openai_ws_forwarder_ingress.go +++ b/backend/internal/service/openai_ws_forwarder_ingress.go @@ -574,12 +574,14 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( refreshIngressRouteState(firstPayload) if useHTTPBridge { + bridgeThreshold, bridgeThresholdSource := s.openAIWSHTTPBridgeThreshold(account) logOpenAIWSModeInfo( - "ingress_ws_http_bridge_start account_id=%d account_type=%s payload_bytes=%d threshold_bytes=%d has_session_hash=%v store_disabled=%v", + "ingress_ws_http_bridge_start account_id=%d account_type=%s payload_bytes=%d threshold_bytes=%d threshold_source=%s has_session_hash=%v store_disabled=%v", account.ID, account.Type, firstPayload.payloadBytes, - s.openAIWSHTTPBridgeThresholdBytes(), + bridgeThreshold, + bridgeThresholdSource, sessionHash != "", storeDisabled, ) diff --git a/backend/internal/service/openai_ws_http_bridge.go b/backend/internal/service/openai_ws_http_bridge.go index 23fc5418dc..ec4a3ce13f 100644 --- a/backend/internal/service/openai_ws_http_bridge.go +++ b/backend/internal/service/openai_ws_http_bridge.go @@ -96,13 +96,6 @@ func (s *OpenAIGatewayService) openAIWSHTTPBridgeEnabled() bool { return s != nil && s.cfg != nil && s.cfg.Gateway.OpenAIWS.HTTPBridgeEnabled } -func (s *OpenAIGatewayService) openAIWSHTTPBridgeThresholdBytes() int64 { - if s == nil || s.cfg == nil || s.cfg.Gateway.OpenAIWS.HTTPBridgeThresholdBytes <= 0 { - return openAIWSHTTPBridgeThresholdBytesDefault - } - return s.cfg.Gateway.OpenAIWS.HTTPBridgeThresholdBytes -} - func (s *OpenAIGatewayService) shouldBridgeOpenAIWSHTTP(account *Account, payloadBytes int, previousResponseID string) bool { if account != nil && account.Platform == PlatformGrok { return true @@ -113,7 +106,7 @@ func (s *OpenAIGatewayService) shouldBridgeOpenAIWSHTTP(account *Account, payloa if strings.TrimSpace(previousResponseID) != "" { return false } - threshold := s.openAIWSHTTPBridgeThresholdBytes() + threshold, _ := s.openAIWSHTTPBridgeThreshold(account) return threshold > 0 && int64(payloadBytes) >= threshold } @@ -121,7 +114,10 @@ func (s *OpenAIGatewayService) shouldBridgeOpenAIWSPassthroughFirstMessage(accou if account != nil && account.Platform == PlatformGrok { return true } - if !s.openAIWSHTTPBridgeEnabled() || int64(len(payload)) < s.openAIWSHTTPBridgeThresholdBytes() { + if !s.openAIWSHTTPBridgeEnabled() { + return false + } + if threshold, _ := s.openAIWSHTTPBridgeThreshold(account); int64(len(payload)) < threshold { return false } if !json.Valid(payload) { diff --git a/backend/internal/service/openai_ws_message_limit.go b/backend/internal/service/openai_ws_message_limit.go new file mode 100644 index 0000000000..7571762e3b --- /dev/null +++ b/backend/internal/service/openai_ws_message_limit.go @@ -0,0 +1,144 @@ +package service + +import ( + "net/http" + "strconv" + "strings" + "sync" + "time" +) + +// openAIWSMaxMessageBytesHeader is the WebSocket handshake response header the +// ChatGPT Codex backend uses to announce the largest message it accepts. The +// official Codex client reads the same header to decide when a request is too +// large for WebSocket. +const openAIWSMaxMessageBytesHeader = "x-codex-websocket-max-message-bytes" + +const ( + // openAIWSUpstreamMessageLimitTTL bounds how long an announced limit is + // trusted without a fresh handshake from the same account. + openAIWSUpstreamMessageLimitTTL = 24 * time.Hour + // openAIWSUpstreamMessageLimitMargin leaves room for fields the gateway adds + // to a client message before forwarding it upstream. + openAIWSUpstreamMessageLimitMargin int64 = 1024 * 1024 + // openAIWSUpstreamMessageLimitMax rejects implausible header values. + openAIWSUpstreamMessageLimitMax int64 = 1 << 30 +) + +// HTTP bridge threshold sources, reported in bridge logs. +const ( + openAIWSBridgeThresholdSourceDefault = "default" + openAIWSBridgeThresholdSourceConfig = "config" + openAIWSBridgeThresholdSourceUpstream = "upstream" +) + +type openAIWSUpstreamMessageLimit struct { + bytes int64 + observedAt time.Time +} + +// openAIWSUpstreamMessageLimitRegistry remembers the message limit announced +// by the most recent upstream handshake of each account. The HTTP bridge +// decision is made before an upstream connection is acquired, so it relies on +// limits observed by earlier handshakes. +type openAIWSUpstreamMessageLimitRegistry struct { + mu sync.RWMutex + limits map[int64]openAIWSUpstreamMessageLimit +} + +var openAIWSUpstreamMessageLimits = &openAIWSUpstreamMessageLimitRegistry{ + limits: make(map[int64]openAIWSUpstreamMessageLimit), +} + +// parseOpenAIWSMaxMessageBytes returns the limit announced in handshake +// response headers, or false when the header is missing or invalid. +func parseOpenAIWSMaxMessageBytes(headers http.Header) (int64, bool) { + if headers == nil { + return 0, false + } + raw := strings.TrimSpace(headers.Get(openAIWSMaxMessageBytesHeader)) + if raw == "" { + return 0, false + } + value, err := strconv.ParseInt(raw, 10, 64) + if err != nil || value <= 0 || value > openAIWSUpstreamMessageLimitMax { + return 0, false + } + return value, true +} + +// record stores the limit announced by a successful handshake. A handshake +// without a valid limit clears the stored value so the account falls back to +// the configured threshold. +func (r *openAIWSUpstreamMessageLimitRegistry) record(accountID int64, headers http.Header, now time.Time) { + if r == nil || accountID <= 0 { + return + } + limit, ok := parseOpenAIWSMaxMessageBytes(headers) + r.mu.Lock() + defer r.mu.Unlock() + if !ok { + delete(r.limits, accountID) + return + } + r.limits[accountID] = openAIWSUpstreamMessageLimit{bytes: limit, observedAt: now} +} + +func (r *openAIWSUpstreamMessageLimitRegistry) lookup(accountID int64, now time.Time) (int64, bool) { + if r == nil || accountID <= 0 { + return 0, false + } + r.mu.RLock() + entry, ok := r.limits[accountID] + r.mu.RUnlock() + if !ok || now.Sub(entry.observedAt) > openAIWSUpstreamMessageLimitTTL { + return 0, false + } + return entry.bytes, true +} + +func recordOpenAIWSUpstreamMessageLimit(accountID int64, headers http.Header) { + openAIWSUpstreamMessageLimits.record(accountID, headers, time.Now()) +} + +// openAIWSHTTPBridgeThreshold returns the first-message size from which an +// account's WebSocket session is bridged to HTTP, and where the value came +// from. A limit announced by the upstream handshake raises the threshold to +// just below that limit; an explicit http_bridge_threshold_bytes setting caps +// it. Without either, the historical default applies. +func (s *OpenAIGatewayService) openAIWSHTTPBridgeThreshold(account *Account) (int64, string) { + configured := int64(0) + if s != nil && s.cfg != nil { + configured = s.cfg.Gateway.OpenAIWS.HTTPBridgeThresholdBytes + } + + upstream := int64(0) + if account != nil { + if limit, ok := openAIWSUpstreamMessageLimits.lookup(account.ID, time.Now()); ok { + upstream = limit - openAIWSUpstreamMessageLimitMargin + if upstream <= 0 { + upstream = limit + } + } + } + + switch { + case upstream > 0 && (configured <= 0 || upstream < configured): + return upstream, openAIWSBridgeThresholdSourceUpstream + case configured > 0: + return configured, openAIWSBridgeThresholdSourceConfig + default: + return openAIWSHTTPBridgeThresholdBytesDefault, openAIWSBridgeThresholdSourceDefault + } +} + +// SetOpenAIWSClientMaxMessageBytesHeader announces the gateway's client read +// limit in the WebSocket handshake response, so Codex clients stop before +// uploading a message the gateway would reject. It must be called before the +// connection is accepted. +func SetOpenAIWSClientMaxMessageBytesHeader(headers http.Header, readLimit int64) { + if headers == nil || readLimit <= 0 { + return + } + headers.Set(openAIWSMaxMessageBytesHeader, strconv.FormatInt(readLimit, 10)) +} diff --git a/backend/internal/service/openai_ws_message_limit_test.go b/backend/internal/service/openai_ws_message_limit_test.go new file mode 100644 index 0000000000..9fabd01366 --- /dev/null +++ b/backend/internal/service/openai_ws_message_limit_test.go @@ -0,0 +1,332 @@ +//go:build unit + +package service + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + coderws "github.com/coder/websocket" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +const wsLimitTestMiB = int64(1024 * 1024) + +func openAIWSLimitHeader(value string) http.Header { + headers := http.Header{} + headers.Set(openAIWSMaxMessageBytesHeader, value) + return headers +} + +// recordOpenAIWSLimitForTest stores a limit for accountID and removes it when +// the test finishes, keeping the shared registry clean. +func recordOpenAIWSLimitForTest(t *testing.T, accountID int64, limit int64) { + t.Helper() + recordOpenAIWSUpstreamMessageLimit(accountID, openAIWSLimitHeader(strconv.FormatInt(limit, 10))) + t.Cleanup(func() { recordOpenAIWSUpstreamMessageLimit(accountID, nil) }) +} + +func newOpenAIWSBridgeTestService(threshold int64) *OpenAIGatewayService { + cfg := &config.Config{} + cfg.Gateway.OpenAIWS.HTTPBridgeEnabled = true + cfg.Gateway.OpenAIWS.HTTPBridgeThresholdBytes = threshold + return &OpenAIGatewayService{cfg: cfg} +} + +func TestParseOpenAIWSMaxMessageBytes(t *testing.T) { + tests := []struct { + name string + headers http.Header + want int64 + ok bool + }{ + {name: "nil headers"}, + {name: "missing", headers: http.Header{}}, + {name: "valid", headers: openAIWSLimitHeader("134217728"), want: 134217728, ok: true}, + {name: "surrounding spaces", headers: openAIWSLimitHeader(" 1048576 "), want: 1048576, ok: true}, + {name: "zero", headers: openAIWSLimitHeader("0")}, + {name: "negative", headers: openAIWSLimitHeader("-1")}, + {name: "not a number", headers: openAIWSLimitHeader("128MiB")}, + {name: "implausibly large", headers: openAIWSLimitHeader(strconv.FormatInt(openAIWSUpstreamMessageLimitMax+1, 10))}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, ok := parseOpenAIWSMaxMessageBytes(tt.headers) + require.Equal(t, tt.ok, ok) + require.Equal(t, tt.want, got) + }) + } +} + +func TestOpenAIWSUpstreamMessageLimitRegistry(t *testing.T) { + registry := &openAIWSUpstreamMessageLimitRegistry{limits: map[int64]openAIWSUpstreamMessageLimit{}} + now := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) + + registry.record(1, openAIWSLimitHeader("134217728"), now) + registry.record(2, openAIWSLimitHeader("16777216"), now) + + limit, ok := registry.lookup(1, now.Add(time.Hour)) + require.True(t, ok) + require.Equal(t, int64(134217728), limit) + limit, ok = registry.lookup(2, now) + require.True(t, ok) + require.Equal(t, int64(16777216), limit) + + _, ok = registry.lookup(3, now) + require.False(t, ok, "accounts without a handshake have no limit") + _, ok = registry.lookup(1, now.Add(openAIWSUpstreamMessageLimitTTL+time.Second)) + require.False(t, ok, "expired limits are ignored") + + registry.record(1, http.Header{}, now) + _, ok = registry.lookup(1, now) + require.False(t, ok, "a handshake without the header clears the stored limit") + + registry.record(0, openAIWSLimitHeader("1048576"), now) + _, ok = registry.lookup(0, now) + require.False(t, ok, "invalid account IDs are not stored") +} + +func TestOpenAIWSHTTPBridgeThreshold(t *testing.T) { + tests := []struct { + name string + configured int64 + upstream int64 + want int64 + wantSource string + }{ + {name: "nothing known", want: openAIWSHTTPBridgeThresholdBytesDefault, wantSource: openAIWSBridgeThresholdSourceDefault}, + {name: "configured only", configured: 20 * wsLimitTestMiB, want: 20 * wsLimitTestMiB, wantSource: openAIWSBridgeThresholdSourceConfig}, + {name: "upstream only", upstream: 128 * wsLimitTestMiB, want: 127 * wsLimitTestMiB, wantSource: openAIWSBridgeThresholdSourceUpstream}, + {name: "configured caps upstream", configured: 20 * wsLimitTestMiB, upstream: 128 * wsLimitTestMiB, want: 20 * wsLimitTestMiB, wantSource: openAIWSBridgeThresholdSourceConfig}, + {name: "upstream below configured", configured: 20 * wsLimitTestMiB, upstream: 10 * wsLimitTestMiB, want: 9 * wsLimitTestMiB, wantSource: openAIWSBridgeThresholdSourceUpstream}, + {name: "upstream below margin", upstream: wsLimitTestMiB / 2, want: wsLimitTestMiB / 2, wantSource: openAIWSBridgeThresholdSourceUpstream}, + } + for i, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + account := &Account{ID: int64(910000 + i), Platform: PlatformOpenAI, Type: AccountTypeOAuth} + if tt.upstream > 0 { + recordOpenAIWSLimitForTest(t, account.ID, tt.upstream) + } + got, source := newOpenAIWSBridgeTestService(tt.configured).openAIWSHTTPBridgeThreshold(account) + require.Equal(t, tt.want, got) + require.Equal(t, tt.wantSource, source) + }) + } + + got, source := (&OpenAIGatewayService{}).openAIWSHTTPBridgeThreshold(nil) + require.Equal(t, openAIWSHTTPBridgeThresholdBytesDefault, got) + require.Equal(t, openAIWSBridgeThresholdSourceDefault, source) +} + +func TestShouldBridgeOpenAIWSHTTPFollowsUpstreamLimit(t *testing.T) { + svc := newOpenAIWSBridgeTestService(0) + payloadBytes := int(51 * wsLimitTestMiB) + + known := &Account{ID: 920001, Platform: PlatformOpenAI, Type: AccountTypeOAuth} + recordOpenAIWSLimitForTest(t, known.ID, 128*wsLimitTestMiB) + require.False(t, svc.shouldBridgeOpenAIWSHTTP(known, payloadBytes, ""), + "a first message below the announced upstream limit stays on WebSocket") + require.True(t, svc.shouldBridgeOpenAIWSHTTP(known, int(127*wsLimitTestMiB), ""), + "a first message at the margin below the upstream limit is bridged") + + unknown := &Account{ID: 920002, Platform: PlatformOpenAI, Type: AccountTypeOAuth} + require.True(t, svc.shouldBridgeOpenAIWSHTTP(unknown, payloadBytes, ""), + "without an announced limit the historical threshold applies") + + capped := newOpenAIWSBridgeTestService(20 * wsLimitTestMiB) + require.True(t, capped.shouldBridgeOpenAIWSHTTP(known, payloadBytes, ""), + "an explicit threshold still caps the upstream limit") +} + +func TestShouldBridgeOpenAIWSPassthroughFirstMessageFollowsUpstreamLimit(t *testing.T) { + svc := newOpenAIWSBridgeTestService(0) + payload := []byte(`{"type":"response.create","model":"gpt-5","input":"` + strings.Repeat("x", int(3*wsLimitTestMiB)) + `"}`) + + small := &Account{ID: 930001, Platform: PlatformOpenAI, Type: AccountTypeOAuth} + recordOpenAIWSLimitForTest(t, small.ID, 2*wsLimitTestMiB) + require.True(t, svc.shouldBridgeOpenAIWSPassthroughFirstMessage(small, payload)) + + large := &Account{ID: 930002, Platform: PlatformOpenAI, Type: AccountTypeOAuth} + recordOpenAIWSLimitForTest(t, large.ID, 8*wsLimitTestMiB) + require.False(t, svc.shouldBridgeOpenAIWSPassthroughFirstMessage(large, payload)) +} + +type openAIWSLimitHeaderDialer struct { + headers http.Header +} + +func (d *openAIWSLimitHeaderDialer) Dial(context.Context, string, http.Header, string) (openAIWSClientConn, int, http.Header, error) { + return &openAIWSFakeConn{}, http.StatusSwitchingProtocols, cloneHeader(d.headers), nil +} + +func TestOpenAIWSConnPoolDialRecordsUpstreamMessageLimit(t *testing.T) { + pool := newOpenAIWSConnPool(&config.Config{}) + pool.setClientDialerForTest(&openAIWSLimitHeaderDialer{headers: openAIWSLimitHeader("134217728")}) + account := &Account{ID: 940001, Platform: PlatformOpenAI, Type: AccountTypeOAuth} + t.Cleanup(func() { recordOpenAIWSUpstreamMessageLimit(account.ID, nil) }) + + conn, err := pool.dialConn(context.Background(), openAIWSAcquireRequest{Account: account, WSURL: "wss://example.test/responses"}) + require.NoError(t, err) + t.Cleanup(conn.close) + + limit, ok := openAIWSUpstreamMessageLimits.lookup(account.ID, time.Now()) + require.True(t, ok) + require.Equal(t, int64(134217728), limit) +} + +func TestSetOpenAIWSClientMaxMessageBytesHeader(t *testing.T) { + headers := http.Header{} + SetOpenAIWSClientMaxMessageBytesHeader(headers, 64*wsLimitTestMiB) + require.Equal(t, "67108864", headers.Get(openAIWSMaxMessageBytesHeader)) + + empty := http.Header{} + SetOpenAIWSClientMaxMessageBytesHeader(empty, 0) + require.Empty(t, empty.Get(openAIWSMaxMessageBytesHeader)) + SetOpenAIWSClientMaxMessageBytesHeader(nil, 64*wsLimitTestMiB) +} + +// TestOpenAIWSPassthroughLargeFirstMessageFollowsUpstreamLimit sends a first +// message above the historical 15 MiB threshold through the WebSocket ingress +// and checks that it stays on the upstream WebSocket when the account's last +// handshake announced a larger limit, and is bridged to HTTP otherwise. +func TestOpenAIWSPassthroughLargeFirstMessageFollowsUpstreamLimit(t *testing.T) { + tests := []struct { + name string + accountID int64 + upstreamLimit int64 + wantBridge bool + }{ + {name: "announced limit keeps WebSocket", accountID: 950001, upstreamLimit: 128 * wsLimitTestMiB}, + {name: "unknown limit bridges to HTTP", accountID: 950002, wantBridge: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + gin.SetMode(gin.TestMode) + if tt.upstreamLimit > 0 { + recordOpenAIWSLimitForTest(t, tt.accountID, tt.upstreamLimit) + } + t.Cleanup(func() { recordOpenAIWSUpstreamMessageLimit(tt.accountID, nil) }) + + cfg := &config.Config{} + cfg.Security.URLAllowlist.Enabled = false + cfg.Security.URLAllowlist.AllowInsecureHTTP = true + cfg.Gateway.MaxLineSize = defaultMaxLineSize + cfg.Gateway.OpenAIWS.Enabled = true + cfg.Gateway.OpenAIWS.APIKeyEnabled = true + cfg.Gateway.OpenAIWS.ResponsesWebsocketsV2 = true + cfg.Gateway.OpenAIWS.ModeRouterV2Enabled = true + cfg.Gateway.OpenAIWS.IngressModeDefault = OpenAIWSIngressModeCtxPool + cfg.Gateway.OpenAIWS.ClientReadLimitBytes = 64 * wsLimitTestMiB + cfg.Gateway.OpenAIWS.HTTPBridgeEnabled = true + + upstreamConn := &openAIWSCaptureConn{events: [][]byte{ + []byte(`{"type":"response.completed","response":{"id":"resp_large_ws","model":"gpt-5","usage":{"input_tokens":1,"output_tokens":1}}}`), + }} + dialer := &openAIWSCaptureDialer{conn: upstreamConn} + sseBody := strings.Join([]string{ + `data: {"type":"response.created","response":{"id":"resp_large_bridge","model":"gpt-5"}}`, + "", + `data: {"type":"response.completed","response":{"id":"resp_large_bridge","model":"gpt-5","usage":{"input_tokens":1,"output_tokens":1}}}`, + "", + }, "\n") + httpUpstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader(sseBody)), + }} + svc := &OpenAIGatewayService{ + cfg: cfg, + httpUpstream: httpUpstream, + cache: &stubGatewayCache{}, + openaiWSResolver: NewOpenAIWSProtocolResolver(cfg), + toolCorrector: NewCodexToolCorrector(), + openaiWSPassthroughDialer: dialer, + } + account := &Account{ + ID: tt.accountID, + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Status: StatusActive, + Schedulable: true, + Concurrency: 1, + Credentials: map[string]any{"api_key": "sk-test"}, + Extra: map[string]any{ + "openai_apikey_responses_websockets_v2_mode": OpenAIWSIngressModePassthrough, + }, + } + + errCh := make(chan error, 1) + wsServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + conn, err := coderws.Accept(w, r, nil) + if err != nil { + errCh <- err + return + } + defer func() { _ = conn.CloseNow() }() + conn.SetReadLimit(ResolveOpenAIWSClientReadLimitBytes(cfg)) + _, firstMessage, err := conn.Read(r.Context()) + if err != nil { + errCh <- err + return + } + rec := httptest.NewRecorder() + ginCtx, _ := gin.CreateTestContext(rec) + ginCtx.Request = r + errCh <- svc.ProxyResponsesWebSocketFromClient(r.Context(), ginCtx, conn, account, "sk-test", firstMessage, nil) + })) + defer wsServer.Close() + + payload := []byte(`{"type":"response.create","model":"gpt-5","stream":true,"input":"` + strings.Repeat("x", int(16*wsLimitTestMiB)) + `"}`) + require.Greater(t, int64(len(payload)), openAIWSHTTPBridgeThresholdBytesDefault) + + clientConn, _, err := coderws.Dial(context.Background(), "ws"+strings.TrimPrefix(wsServer.URL, "http"), nil) + require.NoError(t, err) + defer func() { _ = clientConn.CloseNow() }() + writeCtx, cancelWrite := context.WithTimeout(context.Background(), 20*time.Second) + require.NoError(t, clientConn.Write(writeCtx, coderws.MessageText, payload)) + cancelWrite() + + wantResponseID := "resp_large_ws" + if tt.wantBridge { + wantResponseID = "resp_large_bridge" + } + for { + readCtx, cancelRead := context.WithTimeout(context.Background(), 10*time.Second) + _, event, readErr := clientConn.Read(readCtx) + cancelRead() + require.NoError(t, readErr) + if gjson.GetBytes(event, "type").String() == "response.completed" { + require.Equal(t, wantResponseID, gjson.GetBytes(event, "response.id").String()) + break + } + } + require.NoError(t, clientConn.Close(coderws.StatusNormalClosure, "done")) + + select { + case proxyErr := <-errCh: + if proxyErr != nil { + require.Contains(t, proxyErr.Error(), "StatusNormalClosure") + } + case <-time.After(10 * time.Second): + t.Fatal("timed out waiting for websocket proxy to finish") + } + + if tt.wantBridge { + require.Zero(t, dialer.DialCount()) + require.NotNil(t, httpUpstream.lastReq) + } else { + require.Equal(t, 1, dialer.DialCount()) + require.Nil(t, httpUpstream.lastReq) + } + }) + } +} diff --git a/backend/internal/service/openai_ws_pool.go b/backend/internal/service/openai_ws_pool.go index f46b09f537..b444d3848a 100644 --- a/backend/internal/service/openai_ws_pool.go +++ b/backend/internal/service/openai_ws_pool.go @@ -2156,6 +2156,7 @@ func (p *openAIWSConnPool) dialConn(ctx context.Context, req openAIWSAcquireRequ Err: errors.New("openai ws dialer returned nil connection"), } } + recordOpenAIWSUpstreamMessageLimit(req.Account.ID, handshakeHeaders) id := p.nextConnID(req.Account.ID) pooledConn := newOpenAIWSConn(id, req.Account.ID, conn, handshakeHeaders) accountID := req.Account.ID diff --git a/backend/internal/service/openai_ws_v2_passthrough_adapter.go b/backend/internal/service/openai_ws_v2_passthrough_adapter.go index 856a79ed98..1cffe0a6dc 100644 --- a/backend/internal/service/openai_ws_v2_passthrough_adapter.go +++ b/backend/internal/service/openai_ws_v2_passthrough_adapter.go @@ -889,6 +889,7 @@ func (s *OpenAIGatewayService) proxyResponsesWebSocketV2Passthrough( upstreamConn, statusCode, handshakeHeaders, err = dialer.Dial(dialCtx, wsURL, headers, proxyURL) cancelDial() if err == nil { + recordOpenAIWSUpstreamMessageLimit(account.ID, handshakeHeaders) break } var handshakeErr *openAIWSHandshakeError