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.
This commit is contained in:
shaw committed 2026-11-27 16:25:22 +08:00
1 parent 650fab97d2
commit cbe5bfd1cb
2 files changed
+47 -33

No files matched your search

@@ -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"])
})
}
}
}
@@ -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