From cbe5bfd1cba44c6a775445a1a035401f3d8ad4fd Mon Sep 17 00:00:00 2001 From: shaw Date: Fri, 27 Nov 2026 16:25:22 +0800 Subject: [PATCH] fix(gateway): sample Claude usage on the Responses bridge too The Anthropic /v1/responses bridge had the same gap as the Chat Completions bridge: successful OAuth/setup-token responses never refreshed the 5h/7d subscription windows. Sample the response headers on 2xx exactly like the Chat Completions path, and cover both bridges in one regression test. --- ...ateway_forward_as_chat_completions_test.go | 76 +++++++++++-------- .../service/gateway_forward_as_responses.go | 4 + 2 files changed, 47 insertions(+), 33 deletions(-) diff --git a/backend/internal/service/gateway_forward_as_chat_completions_test.go b/backend/internal/service/gateway_forward_as_chat_completions_test.go index 7ba2121faa..452c421edc 100644 --- a/backend/internal/service/gateway_forward_as_chat_completions_test.go +++ b/backend/internal/service/gateway_forward_as_chat_completions_test.go @@ -18,39 +18,49 @@ import ( "github.com/stretchr/testify/require" ) -func TestForwardAsChatCompletionsSamplesSubscriptionWindows(t *testing.T) { - for _, stream := range []bool{false, true} { - t.Run(fmt.Sprintf("stream=%t", stream), func(t *testing.T) { - fiveReset := time.Now().Add(time.Hour).Truncate(time.Second) - weekReset := fiveReset.Add(24 * time.Hour).Unix() - headers := make(http.Header) - headers.Set("anthropic-ratelimit-unified-5h-status", "allowed") - headers.Set("anthropic-ratelimit-unified-5h-reset", strconv.FormatInt(fiveReset.Unix(), 10)) - headers.Set("anthropic-ratelimit-unified-5h-utilization", "0.23") - headers.Set("anthropic-ratelimit-unified-7d-reset", strconv.FormatInt(weekReset, 10)) - headers.Set("anthropic-ratelimit-unified-7d-utilization", "0.41") - upstream := &anthropicHTTPUpstreamRecorder{resp: &http.Response{ - StatusCode: http.StatusOK, Header: headers, - Body: io.NopCloser(strings.NewReader(namespaceToolAnthropicStream())), - }} - repo := &sessionWindowMockRepo{} - svc := &GatewayService{cfg: &config.Config{}, httpUpstream: upstream, rateLimitService: newRateLimitServiceForTest(repo)} - account := &Account{ID: 42, Platform: PlatformAnthropic, Type: AccountTypeSetupToken, Credentials: map[string]any{"access_token": "test-token"}} - body := fmt.Sprintf(`{"model":"claude-sonnet-4-5","messages":[{"role":"user","content":"hello"}],"stream":%t}`, stream) - c, _ := gin.CreateTestContext(httptest.NewRecorder()) - c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(body)) - _, err := svc.ForwardAsChatCompletions(c.Request.Context(), c, account, []byte(body), nil) - require.NoError(t, err) - require.Len(t, repo.sessionWindowCalls, 1) - require.Equal(t, fiveReset.Unix(), repo.sessionWindowCalls[0].End.Unix()) - require.NotEmpty(t, repo.updateExtraCalls) - sample := repo.updateExtraCalls[len(repo.updateExtraCalls)-1] - require.Equal(t, account.ID, sample.ID) - require.Equal(t, 0.23, sample.Updates["session_window_utilization"]) - require.Equal(t, 0.41, sample.Updates["passive_usage_7d_utilization"]) - require.Equal(t, weekReset, sample.Updates["passive_usage_7d_reset"]) - require.NotEmpty(t, sample.Updates["passive_usage_sampled_at"]) - }) +func TestAnthropicBridgesSampleSubscriptionWindows(t *testing.T) { + for _, endpoint := range []string{"chat/completions", "responses"} { + for _, stream := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/stream=%t", endpoint, stream), func(t *testing.T) { + fiveReset := time.Now().Add(time.Hour).Truncate(time.Second) + weekReset := fiveReset.Add(24 * time.Hour).Unix() + headers := make(http.Header) + headers.Set("anthropic-ratelimit-unified-5h-status", "allowed") + headers.Set("anthropic-ratelimit-unified-5h-reset", strconv.FormatInt(fiveReset.Unix(), 10)) + headers.Set("anthropic-ratelimit-unified-5h-utilization", "0.23") + headers.Set("anthropic-ratelimit-unified-7d-reset", strconv.FormatInt(weekReset, 10)) + headers.Set("anthropic-ratelimit-unified-7d-utilization", "0.41") + upstream := &anthropicHTTPUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, Header: headers, + Body: io.NopCloser(strings.NewReader(namespaceToolAnthropicStream())), + }} + repo := &sessionWindowMockRepo{} + svc := &GatewayService{cfg: &config.Config{}, httpUpstream: upstream, rateLimitService: newRateLimitServiceForTest(repo)} + account := &Account{ID: 42, Platform: PlatformAnthropic, Type: AccountTypeSetupToken, Credentials: map[string]any{"access_token": "test-token"}} + body := fmt.Sprintf(`{"model":"claude-sonnet-4-5","messages":[{"role":"user","content":"hello"}],"stream":%t}`, stream) + if endpoint == "responses" { + body = fmt.Sprintf(`{"model":"claude-sonnet-4-5","input":"hello","stream":%t}`, stream) + } + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/"+endpoint, strings.NewReader(body)) + var err error + if endpoint == "responses" { + _, err = svc.ForwardAsResponses(c.Request.Context(), c, account, []byte(body), nil) + } else { + _, err = svc.ForwardAsChatCompletions(c.Request.Context(), c, account, []byte(body), nil) + } + require.NoError(t, err) + require.Len(t, repo.sessionWindowCalls, 1) + require.Equal(t, fiveReset.Unix(), repo.sessionWindowCalls[0].End.Unix()) + require.NotEmpty(t, repo.updateExtraCalls) + sample := repo.updateExtraCalls[len(repo.updateExtraCalls)-1] + require.Equal(t, account.ID, sample.ID) + require.Equal(t, 0.23, sample.Updates["session_window_utilization"]) + require.Equal(t, 0.41, sample.Updates["passive_usage_7d_utilization"]) + require.Equal(t, weekReset, sample.Updates["passive_usage_7d_reset"]) + require.NotEmpty(t, sample.Updates["passive_usage_sampled_at"]) + }) + } } } diff --git a/backend/internal/service/gateway_forward_as_responses.go b/backend/internal/service/gateway_forward_as_responses.go index a0c9a1e869..76e10c05c6 100644 --- a/backend/internal/service/gateway_forward_as_responses.go +++ b/backend/internal/service/gateway_forward_as_responses.go @@ -208,6 +208,10 @@ func (s *GatewayService) ForwardAsResponses( return nil, fmt.Errorf("upstream error: %d %s", resp.StatusCode, upstreamMsg) } + if resp.StatusCode >= 200 && resp.StatusCode < 300 && s.rateLimitService != nil && account.IsAnthropicOAuthOrSetupToken() { + s.rateLimitService.UpdateSessionWindow(ctx, account, resp.Header) + } + // 13. Handle normal response (convert Anthropic → Responses) var result *ForwardResult var handleErr error