fix(antigravity): scope quota cache to the access token

This commit is contained in:
Ming-Sir-69 committed 2026-12-02 22:42:14 +08:00
1 parent 272b331868
commit 3fcd1c15b9
3 files changed
+31 -22

No files matched your search

@@ -41,7 +41,7 @@ func TestAntigravityUsage_AuthenticationStatus(t *testing.T) {
{name: "known refresh rejection", expiresAt: fresh, refreshToken: "fake-refresh", accountError: "Token refresh failed (non-retryable): invalid_grant", wantCode: "unauthenticated", wantReauth: true},
{name: "known verification restriction", expiresAt: expired, refreshToken: "fake-refresh", accountError: "403 VALIDATION_REQUIRED", wantCode: "forbidden", wantForbidden: "validation"},
{name: "401 cannot establish refresh rejection", expiresAt: fresh, refreshToken: "fake-refresh", accountError: "Token refresh failed (non-retryable): invalid_client", upstreamCode: 401, upstreamBody: "UNAUTHENTICATED", wantCode: "unauthenticated", wantCalls: 1},
{name: "401 with unknown expiration", expiresAt: "legacy", refreshToken: "fake-refresh", upstreamCode: 401, upstreamBody: "invalid_grant", wantCode: "unauthenticated", wantCalls: 1},
{name: "401 with unknown expiration", expiresAt: "legacy", refreshToken: "fake-refresh", upstreamCode: 401, upstreamBody: "invalid_grant", wantCode: "unauthenticated", wantCalls: 1, renew: true},
{name: "verified ban", expiresAt: fresh, refreshToken: "fake-refresh", upstreamCode: 403, upstreamBody: "TOS_VIOLATION", wantCode: "forbidden", wantForbidden: "violation", wantCalls: 1},
{name: "rate limit", expiresAt: fresh, refreshToken: "fake-refresh", upstreamCode: 429, upstreamBody: "RESOURCE_EXHAUSTED", wantCode: "rate_limited", wantCalls: 1},
{name: "valid access token", expiresAt: fresh, refreshToken: "fake-refresh", upstreamCode: 200, wantCalls: 3},
@@ -51,7 +51,7 @@ func TestAntigravityUsage_AuthenticationStatus(t *testing.T) {
var calls atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
calls.Add(1)
if tc.upstreamCode == 200 {
if tc.upstreamCode == 200 || req.Header.Get("Authorization") == "Bearer renewed-fake-access" {
body := `{}`
if req.URL.Path == "/v1internal:fetchAvailableModels" {
body = `{"models":{"gemini-3-flash":{"quotaInfo":{"remainingFraction":0.75}}}}`
@@ -104,6 +104,11 @@ func TestAntigravityUsage_AuthenticationStatus(t *testing.T) {
require.Zero(t, repo.clearCalls)
if tc.renew {
cached, err := svc.GetUsage(context.Background(), account.ID)
require.NoError(t, err)
require.Equal(t, tc.wantCode, cached.ErrorCode)
require.Equal(t, tc.wantCalls, calls.Load())
// Another authorized path saved renewed credentials. The next quota
// read should recover without a manual cache bypass or reauthorization.
repo.accounts[0].Credentials["expires_at"] = fresh
@@ -113,7 +118,7 @@ func TestAntigravityUsage_AuthenticationStatus(t *testing.T) {
require.Empty(t, usage.ErrorCode)
require.False(t, usage.NeedsReauth)
require.Contains(t, usage.AntigravityQuota, "gemini-3-flash")
require.Equal(t, int32(3), calls.Load())
require.Equal(t, tc.wantCalls+3, calls.Load())
}
})
}
@@ -3,6 +3,7 @@
package service
import (
"crypto/sha256"
"testing"
"time"
)
@@ -13,27 +14,28 @@ func TestCachedAntigravityUsage_ForceSkipsFreshCache(t *testing.T) {
s := &AccountUsageService{cache: NewUsageCache()}
resetsAt := time.Now().Add(2 * time.Hour)
stored := &UsageInfo{FiveHour: &UsageProgress{ResetsAt: &resetsAt}}
s.cache.antigravityCache.Store(int64(6), &antigravityUsageCache{usageInfo: stored, timestamp: time.Now()})
tokenHash := sha256.Sum256([]byte("test-token"))
s.cache.antigravityCache.Store(int64(6), &antigravityUsageCache{accessTokenHash: tokenHash, usageInfo: stored, timestamp: time.Now()})
usage, ok := s.cachedAntigravityUsage(6, false)
usage, ok := s.cachedAntigravityUsage(6, tokenHash, false)
if !ok || usage != stored {
t.Fatalf("fresh cache should answer a normal query, got ok=%v", ok)
}
if usage.FiveHour.RemainingSeconds <= 0 {
t.Fatalf("remaining seconds should be recalculated, got %d", usage.FiveHour.RemainingSeconds)
}
if usage, ok := s.cachedAntigravityUsage(6, true); ok || usage != nil {
if usage, ok := s.cachedAntigravityUsage(6, tokenHash, true); ok || usage != nil {
t.Fatalf("a forced query must skip the cache")
}
}
func TestCachedAntigravityUsage_ExpiredOrMissing(t *testing.T) {
s := &AccountUsageService{cache: NewUsageCache()}
if _, ok := s.cachedAntigravityUsage(7, false); ok {
if _, ok := s.cachedAntigravityUsage(7, [sha256.Size]byte{}, false); ok {
t.Fatalf("missing entry must miss")
}
s.cache.antigravityCache.Store(int64(7), &antigravityUsageCache{usageInfo: &UsageInfo{}, timestamp: time.Now().Add(-time.Hour)})
if _, ok := s.cachedAntigravityUsage(7, false); ok {
if _, ok := s.cachedAntigravityUsage(7, [sha256.Size]byte{}, false); ok {
t.Fatalf("expired entry must miss")
}
}
@@ -3,6 +3,7 @@ package service
import (
"bytes"
"context"
"crypto/sha256"
"encoding/json"
"fmt"
"log"
@@ -119,8 +120,9 @@ type windowStatsCacheKey struct {
// antigravityUsageCache 缓存 Antigravity 额度数据
type antigravityUsageCache struct {
usageInfo *UsageInfo
timestamp time.Time
accessTokenHash [sha256.Size]byte
usageInfo *UsageInfo
timestamp time.Time
}
const (
@@ -1158,7 +1160,7 @@ func (s *AccountUsageService) getGeminiUsage(ctx context.Context, account *Accou
// cachedAntigravityUsage returns the account's cached usage while it is fresh, unless force is
// set: a manual refresh (the usage cell's query button, force=true) must reach Google, or an
// account upgraded or reset upstream keeps showing the old figures for the cache TTL.
func (s *AccountUsageService) cachedAntigravityUsage(accountID int64, force bool) (*UsageInfo, bool) {
func (s *AccountUsageService) cachedAntigravityUsage(accountID int64, accessTokenHash [sha256.Size]byte, force bool) (*UsageInfo, bool) {
if force {
return nil, false
}
@@ -1167,7 +1169,7 @@ func (s *AccountUsageService) cachedAntigravityUsage(accountID int64, force bool
return nil, false
}
cache, ok := cached.(*antigravityUsageCache)
if !ok || time.Since(cache.timestamp) >= antigravityCacheTTL(cache.usageInfo) {
if !ok || cache.accessTokenHash != accessTokenHash || time.Since(cache.timestamp) >= antigravityCacheTTL(cache.usageInfo) {
return nil, false
}
usage := cache.usageInfo
@@ -1189,16 +1191,14 @@ func (s *AccountUsageService) getAntigravityUsage(ctx context.Context, account *
return &UsageInfo{UpdatedAt: &now}, nil
}
// 1. 检查缓存
if usage, ok := s.cachedAntigravityUsage(account.ID, force); ok {
accessTokenHash := sha256.Sum256([]byte(account.GetCredential("access_token")))
if usage, ok := s.cachedAntigravityUsage(account.ID, accessTokenHash, force); ok {
return usage, nil
}
// 2. singleflight 防止并发击穿
flightKey := fmt.Sprintf("ag-usage:%d", account.ID)
flightKey := fmt.Sprintf("ag-usage:%d:%x", account.ID, accessTokenHash)
result, flightErr, _ := s.cache.antigravityFlight.Do(flightKey, func() (any, error) {
// 再次检查缓存(等待期间可能已被填充)
if usage, ok := s.cachedAntigravityUsage(account.ID, force); ok {
if usage, ok := s.cachedAntigravityUsage(account.ID, accessTokenHash, force); ok {
return usage, nil
}
@@ -1212,16 +1212,18 @@ func (s *AccountUsageService) getAntigravityUsage(ctx context.Context, account *
degraded := buildAntigravityDegradedUsage(err)
enrichUsageWithAccountError(degraded, account)
s.cache.antigravityCache.Store(account.ID, &antigravityUsageCache{
usageInfo: degraded,
timestamp: time.Now(),
accessTokenHash: accessTokenHash,
usageInfo: degraded,
timestamp: time.Now(),
})
return degraded, nil
}
enrichUsageWithAccountError(fetchResult.UsageInfo, account)
s.cache.antigravityCache.Store(account.ID, &antigravityUsageCache{
usageInfo: fetchResult.UsageInfo,
timestamp: time.Now(),
accessTokenHash: accessTokenHash,
usageInfo: fetchResult.UsageInfo,
timestamp: time.Now(),
})
return fetchResult.UsageInfo, nil
})