mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-06 00:05:30 +00:00
Merge pull request #8590 from william-drakemond/pr/antigravity-usage-query
feat(antigravity): 用量格子加查询按钮,强制查询跳过缓存 / Query button for antigravity usage; force skips the cache
This commit is contained in:
4 files changed
+139
-24
No files matched your search
@@ -0,0 +1,39 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// A manual refresh (force=true) must not be answered from the antigravity usage cache: an
|
||||
// account upgraded or reset upstream otherwise keeps showing old figures for the cache TTL.
|
||||
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()})
|
||||
|
||||
usage, ok := s.cachedAntigravityUsage(6, 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 {
|
||||
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 {
|
||||
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 {
|
||||
t.Fatalf("expired entry must miss")
|
||||
}
|
||||
}
|
||||
@@ -396,7 +396,7 @@ func (s *AccountUsageService) getUsageForAccount(ctx context.Context, account *A
|
||||
|
||||
// Antigravity 平台:使用 AntigravityQuotaFetcher 获取额度
|
||||
if account.Platform == PlatformAntigravity {
|
||||
usage, err := s.getAntigravityUsage(ctx, account)
|
||||
usage, err := s.getAntigravityUsage(ctx, account, forceProbe)
|
||||
if err == nil {
|
||||
s.tryClearRecoverableAccountError(ctx, account)
|
||||
}
|
||||
@@ -1091,41 +1091,45 @@ func (s *AccountUsageService) getGeminiUsage(ctx context.Context, account *Accou
|
||||
return usage, nil
|
||||
}
|
||||
|
||||
// getAntigravityUsage 获取 Antigravity 账户额度
|
||||
func (s *AccountUsageService) getAntigravityUsage(ctx context.Context, account *Account) (*UsageInfo, error) {
|
||||
// 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) {
|
||||
if force {
|
||||
return nil, false
|
||||
}
|
||||
cached, ok := s.cache.antigravityCache.Load(accountID)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
cache, ok := cached.(*antigravityUsageCache)
|
||||
if !ok || time.Since(cache.timestamp) >= antigravityCacheTTL(cache.usageInfo) {
|
||||
return nil, false
|
||||
}
|
||||
usage := cache.usageInfo
|
||||
// 重新计算 RemainingSeconds,避免返回过时的剩余秒数
|
||||
recalcAntigravityRemainingSeconds(usage)
|
||||
return usage, true
|
||||
}
|
||||
|
||||
// getAntigravityUsage 获取 Antigravity 账户额度;force 跳过缓存(仍经 singleflight 合并并发请求)。
|
||||
func (s *AccountUsageService) getAntigravityUsage(ctx context.Context, account *Account, force bool) (*UsageInfo, error) {
|
||||
if s.antigravityQuotaFetcher == nil || !s.antigravityQuotaFetcher.CanFetch(account) {
|
||||
now := time.Now()
|
||||
return &UsageInfo{UpdatedAt: &now}, nil
|
||||
}
|
||||
|
||||
// 1. 检查缓存
|
||||
if cached, ok := s.cache.antigravityCache.Load(account.ID); ok {
|
||||
if cache, ok := cached.(*antigravityUsageCache); ok {
|
||||
ttl := antigravityCacheTTL(cache.usageInfo)
|
||||
if time.Since(cache.timestamp) < ttl {
|
||||
usage := cache.usageInfo
|
||||
if usage.FiveHour != nil && usage.FiveHour.ResetsAt != nil {
|
||||
usage.FiveHour.RemainingSeconds = int(time.Until(*usage.FiveHour.ResetsAt).Seconds())
|
||||
}
|
||||
return usage, nil
|
||||
}
|
||||
}
|
||||
if usage, ok := s.cachedAntigravityUsage(account.ID, force); ok {
|
||||
return usage, nil
|
||||
}
|
||||
|
||||
// 2. singleflight 防止并发击穿
|
||||
flightKey := fmt.Sprintf("ag-usage:%d", account.ID)
|
||||
result, flightErr, _ := s.cache.antigravityFlight.Do(flightKey, func() (any, error) {
|
||||
// 再次检查缓存(等待期间可能已被填充)
|
||||
if cached, ok := s.cache.antigravityCache.Load(account.ID); ok {
|
||||
if cache, ok := cached.(*antigravityUsageCache); ok {
|
||||
ttl := antigravityCacheTTL(cache.usageInfo)
|
||||
if time.Since(cache.timestamp) < ttl {
|
||||
usage := cache.usageInfo
|
||||
// 重新计算 RemainingSeconds,避免返回过时的剩余秒数
|
||||
recalcAntigravityRemainingSeconds(usage)
|
||||
return usage, nil
|
||||
}
|
||||
}
|
||||
if usage, ok := s.cachedAntigravityUsage(account.ID, force); ok {
|
||||
return usage, nil
|
||||
}
|
||||
|
||||
// 使用独立 context,避免调用方 cancel 导致所有共享 flight 的请求失败
|
||||
|
||||
@@ -357,6 +357,37 @@
|
||||
💳 {{ t('admin.accounts.aiCreditsBalance') }}: {{ aiCreditsDisplay }}
|
||||
</div>
|
||||
<div v-else class="text-xs text-gray-400">-</div>
|
||||
|
||||
<!--
|
||||
Query the upstream now, bypassing the server's usage cache (force=true), like the Claude
|
||||
and OpenAI cells: an account upgraded or reset upstream otherwise shows old figures for
|
||||
the cache TTL. Shown in every state, including errors, where a retry matters most.
|
||||
-->
|
||||
<div v-if="!loading" class="mt-1">
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center gap-0.5 rounded px-1.5 py-0.5 text-[10px] font-medium text-blue-600 hover:bg-blue-50 dark:text-blue-400 dark:hover:bg-blue-900/30 transition-colors disabled:cursor-not-allowed disabled:opacity-50"
|
||||
data-testid="antigravity-active-query"
|
||||
:disabled="activeQueryLoading"
|
||||
@click="loadActiveUsage"
|
||||
>
|
||||
<svg
|
||||
class="h-2.5 w-2.5"
|
||||
:class="{ 'animate-spin': activeQueryLoading }"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
stroke-width="2"
|
||||
d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
|
||||
/>
|
||||
</svg>
|
||||
{{ t('admin.accounts.usageWindow.activeQuery') }}
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- Grok OAuth accounts: passive xAI quota headers + local Sub2API usage -->
|
||||
|
||||
@@ -510,6 +510,47 @@ describe('AccountUsageCell', () => {
|
||||
expect(wrapper.text()).not.toContain('gemini3Flash')
|
||||
})
|
||||
|
||||
it('Antigravity query button refreshes past the server cache', async () => {
|
||||
const first = {
|
||||
antigravity_quota_groups: [
|
||||
{ key: '3p', name: 'Claude and GPT models', windows: [{ window: 'weekly', utilization: 100, resets_at: '2026-11-12T03:39:37Z' }] }
|
||||
]
|
||||
}
|
||||
const upgraded = {
|
||||
antigravity_quota_groups: [
|
||||
{ key: '3p', name: 'Claude and GPT models', windows: [{ window: 'weekly', utilization: 0, resets_at: '2026-11-14T21:22:49Z' }] }
|
||||
]
|
||||
}
|
||||
getUsage.mockResolvedValueOnce(first).mockResolvedValueOnce(upgraded)
|
||||
|
||||
const wrapper = mount(AccountUsageCell, {
|
||||
props: {
|
||||
account: makeAccount({ id: 1006, platform: 'antigravity', type: 'oauth', extra: {} })
|
||||
},
|
||||
global: {
|
||||
stubs: {
|
||||
UsageProgressBar: {
|
||||
props: ['label', 'utilization', 'resetsAt', 'color'],
|
||||
template: '<div class="usage-bar">{{ label }}|{{ utilization }}|{{ resetsAt }}</div>'
|
||||
},
|
||||
AccountQuotaInfo: true
|
||||
}
|
||||
}
|
||||
})
|
||||
await flushPromises()
|
||||
expect(wrapper.find('.usage-bar').text()).toContain('|100|')
|
||||
|
||||
const button = wrapper.find('[data-testid="antigravity-active-query"]')
|
||||
expect(button.exists()).toBe(true)
|
||||
expect(button.text()).toContain('admin.accounts.usageWindow.activeQuery')
|
||||
await button.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
// An active query that bypasses the cache (an upgrade or reset shows at once).
|
||||
expect(getUsage).toHaveBeenLastCalledWith(1006, 'active', true)
|
||||
expect(wrapper.find('.usage-bar').text()).toContain('|0|2026-11-14T21:22:49Z')
|
||||
})
|
||||
|
||||
it('Antigravity 会显示 AI Credits 余额信息', async () => {
|
||||
getUsage.mockResolvedValue({
|
||||
ai_credits: [
|
||||
|
||||
Reference in new issue
Block a user