mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-05 08:05:12 +00:00
fix(openai): fail over upstream request timeouts
This commit is contained in:
1 parent
2af3f1e15c
commit
4480cd90a4
4 files changed
+117
-3
No files matched your search
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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"}`)
|
||||
|
||||
Reference in new issue
Block a user