From 4480cd90a42df239f83e0cc14033efd439128c6a Mon Sep 17 00:00:00 2001 From: wucm667 Date: Thu, 19 Nov 2026 23:45:59 +0800 Subject: [PATCH] fix(openai): fail over upstream request timeouts --- .../service/openai_gateway_grok_405_test.go | 4 +- .../openai_gateway_request_timeout_test.go | 71 +++++++++++++++++++ .../service/openai_gateway_upstream_errors.go | 2 +- .../internal/service/openai_images_test.go | 43 +++++++++++ 4 files changed, 117 insertions(+), 3 deletions(-) create mode 100644 backend/internal/service/openai_gateway_request_timeout_test.go diff --git a/backend/internal/service/openai_gateway_grok_405_test.go b/backend/internal/service/openai_gateway_grok_405_test.go index 10ed8a599e..bc17dd520e 100644 --- a/backend/internal/service/openai_gateway_grok_405_test.go +++ b/backend/internal/service/openai_gateway_grok_405_test.go @@ -17,12 +17,12 @@ func TestShouldFailoverUpstreamError_405IsFailoverEligible(t *testing.T) { func TestShouldFailoverUpstreamError_ExistingCodesStillWork(t *testing.T) { svc := &OpenAIGatewayService{} - failoverCodes := []int{401, 402, 403, 405, 429, 529, 500, 502, 503, 504} + failoverCodes := []int{401, 402, 403, 405, http.StatusRequestTimeout, 429, 529, 500, 502, 503, 504} for _, code := range failoverCodes { assert.True(t, svc.shouldFailoverUpstreamError(code), "status %d should trigger failover", code) } - nonFailoverCodes := []int{200, 201, 400, 404, 408, 422} + nonFailoverCodes := []int{200, 201, 400, 404, 422} for _, code := range nonFailoverCodes { assert.False(t, svc.shouldFailoverUpstreamError(code), "status %d should NOT trigger failover", code) } diff --git a/backend/internal/service/openai_gateway_request_timeout_test.go b/backend/internal/service/openai_gateway_request_timeout_test.go new file mode 100644 index 0000000000..b0fb1dae14 --- /dev/null +++ b/backend/internal/service/openai_gateway_request_timeout_test.go @@ -0,0 +1,71 @@ +package service + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func TestShouldFailoverOpenAIUpstreamResponse_RequestTimeout(t *testing.T) { + svc := &OpenAIGatewayService{} + account := &Account{Platform: PlatformOpenAI, Type: AccountTypeAPIKey} + tests := []struct { + name string + status int + body string + want bool + }{ + {"adobe_upstream", http.StatusRequestTimeout, `{"error":{"code":"upstream_unavailable","message":"Upstream request failed","type":"adobe_upstream"}}`, true}, + {"model_overloaded", http.StatusRequestTimeout, `{"error":{"message":"Model is overloaded, please retry later","type":"rate_limit_error"}}`, true}, + {"adobe_throttled", http.StatusRequestTimeout, `{"error":{"message":"adobe throttled: status 429 retry-after=21.48s envoy=false {\"error_code\":\"rate_limited\",\"message\":\"Too many requests. Please try again later.\"}","type":"rate_limit_error"}}`, true}, + {"plain_timeout", http.StatusRequestTimeout, `Request Timeout`, true}, + {"bad_gateway", http.StatusBadGateway, `{"error":{"message":"Upstream service temporarily unavailable","type":"upstream_error"}}`, true}, + {"rate_limit", http.StatusTooManyRequests, `{"error":{"message":"rate limited","type":"rate_limit_error"}}`, true}, + {"method_not_allowed", http.StatusMethodNotAllowed, ``, true}, + {"bad_request", http.StatusBadRequest, `{"error":{"message":"Invalid image size","type":"invalid_request_error"}}`, false}, + {"not_found", http.StatusNotFound, `{"error":{"message":"Not found"}}`, false}, + {"unprocessable_entity", http.StatusUnprocessableEntity, `{"error":{"message":"Invalid request"}}`, false}, + {"cyber_policy", http.StatusRequestTimeout, `{"error":{"code":"cyber_policy","message":"blocked"}}`, false}, + {"context_length", http.StatusRequestTimeout, `{"error":{"code":"context_length_exceeded","message":"Maximum context length exceeded"}}`, false}, + {"context_window", http.StatusRequestTimeout, `{"error":{"message":"Input exceeds the context window"}}`, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + body := []byte(tt.body) + require.Equal(t, tt.want, svc.shouldFailoverOpenAIUpstreamResponse(account, tt.status, extractUpstreamErrorMessage(body), body)) + }) + } +} + +func TestOpenAIRequestTimeout_CustomErrorCodesStillTakePrecedence(t *testing.T) { + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + account := &Account{ + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "custom_error_codes_enabled": true, + "custom_error_codes": []any{float64(http.StatusTooManyRequests)}, + }, + } + resp := &http.Response{ + StatusCode: http.StatusRequestTimeout, + Header: http.Header{}, + Body: io.NopCloser(strings.NewReader(`{"error":{"message":"Upstream request failed","type":"adobe_upstream"}}`)), + } + result, err := (&OpenAIGatewayService{}).handleErrorResponse(context.Background(), resp, c, account, nil) + require.Nil(t, result) + require.ErrorContains(t, err, "not in custom error codes") + var failoverErr *UpstreamFailoverError + require.NotErrorAs(t, err, &failoverErr) + require.Equal(t, http.StatusInternalServerError, rec.Code) + require.True(t, c.Writer.Written()) +} diff --git a/backend/internal/service/openai_gateway_upstream_errors.go b/backend/internal/service/openai_gateway_upstream_errors.go index db13c916e0..ae620ec283 100644 --- a/backend/internal/service/openai_gateway_upstream_errors.go +++ b/backend/internal/service/openai_gateway_upstream_errors.go @@ -302,7 +302,7 @@ func isOpenAIContextWindowError(upstreamMsg string, upstreamBody []byte) bool { func (s *OpenAIGatewayService) shouldFailoverUpstreamError(statusCode int) bool { switch statusCode { - case 401, 402, 403, 405, 429, 529: + case 401, 402, 403, 405, http.StatusRequestTimeout, 429, 529: return true default: return statusCode >= 500 diff --git a/backend/internal/service/openai_images_test.go b/backend/internal/service/openai_images_test.go index 01ec82e763..ac9b5d3ec9 100644 --- a/backend/internal/service/openai_images_test.go +++ b/backend/internal/service/openai_images_test.go @@ -1438,6 +1438,49 @@ func TestOpenAIGatewayServiceForwardImages_APIKeyAccessStateUsesTypedFailover(t require.False(t, c.Writer.Written()) } +func TestOpenAIGatewayServiceForwardImages_APIKeyRequestTimeoutReturnsFailoverBeforeWrite(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, upstreamBody := range []string{ + `{"error":{"code":"upstream_unavailable","message":"Upstream request failed","type":"adobe_upstream"}}`, + `{"error":{"message":"Model is overloaded, please retry later","type":"rate_limit_error"}}`, + `{"error":{"message":"adobe throttled: status 429 retry-after=21.48s envoy=false {\"error_code\":\"rate_limited\",\"message\":\"Too many requests. Please try again later.\"}","type":"rate_limit_error"}}`, + } { + t.Run(extractUpstreamErrorMessage([]byte(upstreamBody)), func(t *testing.T) { + body := []byte(`{"model":"gpt-image-1","prompt":"draw a cat"}`) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/images/generations", bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusRequestTimeout, + Header: http.Header{ + "Content-Type": {"application/json"}, + }, + Body: io.NopCloser(strings.NewReader(upstreamBody)), + }} + svc := &OpenAIGatewayService{cfg: &config.Config{}, httpUpstream: upstream} + parsed, err := svc.ParseOpenAIImagesRequest(c, body) + require.NoError(t, err) + account := &Account{ + ID: 51, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, + Credentials: map[string]any{"api_key": "sk-test"}, + } + + result, err := svc.ForwardImages(context.Background(), c, account, body, parsed, "") + + require.Nil(t, result) + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, http.StatusRequestTimeout, failoverErr.StatusCode) + require.Equal(t, upstreamBody, string(failoverErr.ResponseBody)) + require.False(t, failoverErr.RetryableOnSameAccount) + require.False(t, IsResponseCommitted(c)) + require.False(t, c.Writer.Written()) + require.Empty(t, rec.Body.String()) + }) + } +} + func TestOpenAIGatewayServiceForwardImages_APIKeyStreamJSONResponseBillsImage(t *testing.T) { gin.SetMode(gin.TestMode) body := []byte(`{"model":"gpt-image-2","prompt":"draw a cat","stream":true,"response_format":"b64_json"}`)