diff --git a/backend/internal/application/account/quota_refresh_test.go b/backend/internal/application/account/quota_refresh_test.go index 4a3bf7df..a459ed56 100644 --- a/backend/internal/application/account/quota_refresh_test.go +++ b/backend/internal/application/account/quota_refresh_test.go @@ -24,10 +24,12 @@ func TestWebQuotaRefreshDeduplicatesPerMode(t *testing.T) { service.QueueQuotaRefresh(43, "console") service.QueueQuotaRefresh(43, "console_image") service.QueueQuotaRefresh(43, "console_video") + service.QueueQuotaRefresh(44, accountdomain.QuotaModeWebImagePro) + service.QueueQuotaRefresh(44, accountdomain.QuotaModeWebVideo720p) service.quotaRefreshMu.Lock() defer service.quotaRefreshMu.Unlock() - if len(service.quotaRefreshes) != 5 { + if len(service.quotaRefreshes) != 6 { t.Fatalf("refresh states = %#v", service.quotaRefreshes) } if service.quotaRefreshes["42:fast"].generation != 2 || !service.quotaRefreshes["42:fast"].queued { @@ -44,7 +46,10 @@ func TestWebQuotaRefreshDeduplicatesPerMode(t *testing.T) { t.Fatalf("Console %s refresh state is invalid: %#v", mode, state) } } - if len(service.quotaRefreshQueue) != 5 { + if state := service.quotaRefreshes["44:"+accountdomain.QuotaGroupWebImagine]; state == nil || state.generation != 2 || !state.queued { + t.Fatalf("Imagine group refresh state is invalid: %#v", state) + } + if len(service.quotaRefreshQueue) != 6 { t.Fatalf("queued refreshes = %d", len(service.quotaRefreshQueue)) } } @@ -354,6 +359,58 @@ func TestRefreshQuotaModeDoesNotTriggerFullProviderSyncForAutoTier(t *testing.T) } } +func TestRefreshWebImagineQuotaModeAtomicallyReplacesGroup(t *testing.T) { + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "imagine-quota-group.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = database.Close() }) + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + accounts := relational.NewAccountRepository(database) + credential, _, err := accounts.UpsertByIdentity(ctx, accountdomain.Credential{ + Provider: accountdomain.ProviderWeb, AuthType: accountdomain.AuthTypeSSO, + Name: "web-imagine", SourceKey: "web-imagine", EncryptedAccessToken: "encrypted", + Enabled: true, AuthStatus: accountdomain.AuthStatusActive, + }) + if err != nil { + t.Fatal(err) + } + now := time.Now().UTC() + if err := accounts.SaveQuotaWindows(ctx, credential.ID, accountdomain.WebTierSuper, now, []accountdomain.QuotaWindow{ + {AccountID: credential.ID, Mode: "weekly", Remaining: 90, Total: 100, UpdatedAt: now}, + {AccountID: credential.ID, Mode: accountdomain.QuotaModeWebImagePro, Remaining: 4, UpdatedAt: now}, + {AccountID: credential.ID, Mode: accountdomain.QuotaModeWebVideo720p, Remaining: 1, UpdatedAt: now}, + }); err != nil { + t.Fatal(err) + } + adapter := &imagineQuotaGroupAdapter{} + service := NewService(accounts, nil, nil, nil, provider.NewRegistry(adapter), nil, nil) + window, err := service.RefreshQuotaMode(ctx, credential.ID, accountdomain.QuotaModeWebImagePro) + if err != nil { + t.Fatal(err) + } + if window.Remaining != 3 || adapter.calls.Load() != 1 { + t.Fatalf("window = %#v, calls = %d", window, adapter.calls.Load()) + } + stored, err := accounts.GetQuotaWindows(ctx, []uint64{credential.ID}) + if err != nil { + t.Fatal(err) + } + byMode := make(map[string]accountdomain.QuotaWindow) + for _, current := range stored[credential.ID] { + byMode[current.Mode] = current + } + if byMode["weekly"].Remaining != 90 || byMode[accountdomain.QuotaModeWebImagePro].Remaining != 3 { + t.Fatalf("stored = %#v", stored[credential.ID]) + } + if _, exists := byMode[accountdomain.QuotaModeWebVideo720p]; exists { + t.Fatalf("stale video_720p window survived group replacement: %#v", stored[credential.ID]) + } +} + func TestRefreshConsoleQuotaModePersistsCompleteUsageSnapshot(t *testing.T) { ctx := context.Background() database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "console-quota-mode.db")) @@ -839,6 +896,36 @@ type quotaCountingAdapter struct { modeRelease chan struct{} } +type imagineQuotaGroupAdapter struct { + calls atomic.Int64 +} + +func (a *imagineQuotaGroupAdapter) Provider() accountdomain.Provider { + return accountdomain.ProviderWeb +} + +func (a *imagineQuotaGroupAdapter) Definition() provider.Definition { + return provider.Definition{ + Provider: accountdomain.ProviderWeb, ModelNamespace: accountdomain.ProviderWeb.ModelNamespace(), + Quota: provider.QuotaRemoteWindow, Credential: provider.CredentialSurface{AuthType: accountdomain.AuthTypeSSO}, + } +} + +func (a *imagineQuotaGroupAdapter) SyncQuotaGroup(_ context.Context, credential accountdomain.Credential, group string) (provider.QuotaGroupSnapshot, error) { + a.calls.Add(1) + if group != accountdomain.QuotaGroupWebImagine { + return provider.QuotaGroupSnapshot{}, errors.New("unexpected group") + } + now := time.Now().UTC() + return provider.QuotaGroupSnapshot{ + Group: group, Modes: accountdomain.WebImagineQuotaModes(), SyncedAt: now, + Windows: []accountdomain.QuotaWindow{{ + AccountID: credential.ID, Mode: accountdomain.QuotaModeWebImagePro, Remaining: 3, + WindowSeconds: 86400, SyncedAt: &now, Source: accountdomain.QuotaSourceUpstream, UpdatedAt: now, + }}, + }, nil +} + type consoleQuotaSnapshotAdapter struct { fullCalls atomic.Int64 modeCalls atomic.Int64 diff --git a/backend/internal/application/account/service.go b/backend/internal/application/account/service.go index 1ece9d8e..afad1f0b 100644 --- a/backend/internal/application/account/service.go +++ b/backend/internal/application/account/service.go @@ -134,6 +134,7 @@ type quotaRefreshRequest struct { type quotaRefreshResult struct { Credential accountdomain.Credential Windows []accountdomain.QuotaWindow + Modes []string } type QuotaRefreshStats struct { @@ -2786,56 +2787,9 @@ func (s *Service) refreshQuota(ctx context.Context, id uint64) (quotaRefreshResu if err := s.accounts.ReplaceQuotaWindows(ctx, id, snapshot.Tier, snapshot.SyncedAt, snapshot.Windows); err != nil { return quotaRefreshResult{}, err } - if value.Provider == accountdomain.ProviderWeb { - s.applyImagineQuotaCooldown(ctx, id, snapshot.Windows) - } return quotaRefreshResult{Credential: value, Windows: snapshot.Windows}, nil } -// imagineQuotaBlockModel 把 Imagine 配额窗口的 mode 映射到受冷却影响的上游模型。 -// imagePro 由 quality 文本生图(imagine-x-1 与 grok-imagine-image-quality)共用, -// 触顶时两者一并冷却;其余 mode 一一对应。 -var imagineQuotaBlockModels = map[string][]string{ - "image_pro": {"imagine-x-1", "grok-imagine-image-quality"}, - "image_edit": {"imagine-image-edit"}, - "video": {"grok-imagine-video"}, - "video_720p": {"grok-imagine-video"}, -} - -// applyImagineQuotaCooldown 在 Imagine 配额触顶(剩余 0)时为受影响的模型写入 -// model 级冷却块。CooldownUntil 对齐上游 nextAvailableAt(即配额窗口 ResetAt), -// 未提供时回退为 24 小时。selector 通过 ModelQuotaBlock 跳过该账号用于该模型, -// 过期记录由 model_cooldown_cleanup 定时任务清理。 -func (s *Service) applyImagineQuotaCooldown(ctx context.Context, accountID uint64, windows []accountdomain.QuotaWindow) { - const fallbackCooldown = 24 * time.Hour - now := s.now() - for _, window := range windows { - models, ok := imagineQuotaBlockModels[window.Mode] - if !ok { - continue - } - if window.Remaining > 0 { - continue - } - cooldownUntil := now.Add(fallbackCooldown) - if window.ResetAt != nil && window.ResetAt.After(now) { - cooldownUntil = *window.ResetAt - } - for _, upstreamModel := range models { - block := accountdomain.ModelQuotaBlock{ - AccountID: accountID, - UpstreamModel: upstreamModel, - Reason: "imagine_quota_exhausted", - CooldownUntil: cooldownUntil, - UpdatedAt: now, - } - if err := s.accounts.OverwriteModelQuotaBlock(ctx, block); err != nil { - s.logger.Warn("imagine_quota_cooldown_write_failed", "account_id", accountID, "upstream_model", upstreamModel, "mode", window.Mode, "error", err) - } - } - } -} - func preserveActiveQuotaWindows(existing, incoming []accountdomain.QuotaWindow, now time.Time) []accountdomain.QuotaWindow { byMode := make(map[string]accountdomain.QuotaWindow, len(existing)) for _, window := range existing { @@ -2880,6 +2834,9 @@ func (s *Service) RefreshQuotaMode(ctx context.Context, id uint64, mode string) mode = strings.TrimSpace(mode) key := quotaSyncKey(id, mode) result, err, _ := s.quotaSyncs.Do(key, func() (any, error) { + if isWebImagineQuotaMode(mode) { + return s.refreshQuotaGroup(ctx, id, accountdomain.QuotaGroupWebImagine) + } return s.refreshQuotaMode(ctx, id, mode) }) if err != nil { @@ -2889,19 +2846,26 @@ func (s *Service) RefreshQuotaMode(ctx context.Context, id uint64, mode string) if !ok { return accountdomain.QuotaWindow{}, fmt.Errorf("Provider 模式额度同步返回类型无效") } + if len(refreshed.Modes) > 0 { + if err := s.reconcileQuotaGroupWindows(ctx, refreshed.Credential.Provider, id, refreshed.Modes, refreshed.Windows); err != nil { + return accountdomain.QuotaWindow{}, err + } + } window, ok := quotaWindowByMode(refreshed.Windows, mode) if !ok { return accountdomain.QuotaWindow{}, fmt.Errorf("Provider usage 响应缺少 %s 额度", mode) } - if refreshed.Credential.Provider == accountdomain.ProviderConsole { + if len(refreshed.Modes) == 0 && refreshed.Credential.Provider == accountdomain.ProviderConsole { // One Console request refreshes all three authoritative windows. Reconcile // every matching recovery event so externally consumed media quota cannot // remain unscheduled merely because a different kind triggered the refresh. if err := s.reconcileQuotaRecoveryWindows(ctx, refreshed.Credential.Provider, id, refreshed.Windows); err != nil { return window, err } - } else if err := s.reconcileQuotaRecoveryWindow(ctx, refreshed.Credential.Provider, id, window); err != nil { - return window, err + } else if len(refreshed.Modes) == 0 { + if err := s.reconcileQuotaRecoveryWindow(ctx, refreshed.Credential.Provider, id, window); err != nil { + return window, err + } } return window, nil } @@ -2913,6 +2877,9 @@ func (s *Service) ProbeQuotaMode(ctx context.Context, id uint64, mode string) (a mode = strings.TrimSpace(mode) key := quotaSyncKey(id, mode) result, err, _ := s.quotaSyncs.Do(key, func() (any, error) { + if isWebImagineQuotaMode(mode) { + return s.refreshQuotaGroup(ctx, id, accountdomain.QuotaGroupWebImagine) + } return s.refreshQuotaMode(ctx, id, mode) }) if err != nil { @@ -2929,6 +2896,34 @@ func (s *Service) ProbeQuotaMode(ctx context.Context, id uint64, mode string) (a return window, nil } +func (s *Service) refreshQuotaGroup(ctx context.Context, id uint64, group string) (quotaRefreshResult, error) { + value, err := s.accounts.Get(ctx, id) + if err != nil { + return quotaRefreshResult{}, mapRepositoryError(err) + } + adapter, ok := s.providers.QuotaGroup(value.Provider) + if !ok { + return quotaRefreshResult{}, fmt.Errorf("%s quota group Provider 未注册", value.Provider) + } + snapshot, err := adapter.SyncQuotaGroup(ctx, value, group) + if err != nil { + if errors.Is(err, provider.ErrUnauthorized) { + err = errors.Join(err, s.markSSOCredentialRejected(ctx, value, fmt.Sprintf("%s SSO credential rejected", value.Provider))) + } + return quotaRefreshResult{}, err + } + if snapshot.Group != group || len(snapshot.Modes) == 0 { + return quotaRefreshResult{}, fmt.Errorf("Provider quota group %s 返回无效快照", group) + } + if snapshot.SyncedAt.IsZero() { + snapshot.SyncedAt = s.now() + } + if err := s.accounts.ReplaceQuotaWindowGroup(ctx, id, snapshot.SyncedAt, snapshot.Modes, snapshot.Windows); err != nil { + return quotaRefreshResult{}, err + } + return quotaRefreshResult{Credential: value, Windows: snapshot.Windows, Modes: snapshot.Modes}, nil +} + func (s *Service) refreshQuotaMode(ctx context.Context, id uint64, mode string) (quotaRefreshResult, error) { value, err := s.accounts.Get(ctx, id) if err != nil { @@ -2988,9 +2983,6 @@ func (s *Service) refreshQuotaMode(ctx context.Context, id uint64, mode string) } else if err := s.accounts.SaveQuotaWindows(ctx, id, tier, syncedAt, windows); err != nil { return quotaRefreshResult{}, err } - if isWebImagineQuotaMode(mode) { - s.applyImagineQuotaCooldown(ctx, id, windows) - } return quotaRefreshResult{Credential: value, Windows: windows}, nil } @@ -2999,6 +2991,9 @@ func quotaSyncKey(accountID uint64, mode string) string { if isConsoleUsageQuotaMode(mode) { return "all:" + strconv.FormatUint(accountID, 10) } + if isWebImagineQuotaMode(mode) || mode == accountdomain.QuotaGroupWebImagine { + return accountdomain.QuotaGroupWebImagine + ":" + strconv.FormatUint(accountID, 10) + } return mode + ":" + strconv.FormatUint(accountID, 10) } @@ -3020,6 +3015,27 @@ func (s *Service) reconcileQuotaRecoveryWindows(ctx context.Context, providerVal return nil } +func (s *Service) reconcileQuotaGroupWindows(ctx context.Context, providerValue accountdomain.Provider, accountID uint64, modes []string, windows []accountdomain.QuotaWindow) error { + byMode := make(map[string]accountdomain.QuotaWindow, len(windows)) + for _, window := range windows { + byMode[window.Mode] = window + } + for _, mode := range modes { + if window, ok := byMode[mode]; ok { + if err := s.reconcileQuotaRecoveryWindow(ctx, providerValue, accountID, window); err != nil { + return err + } + continue + } + if s.quotaQueue != nil { + if err := s.quotaQueue.CancelQuotaRecovery(ctx, accountID, mode); err != nil { + return fmt.Errorf("取消额度恢复事件: %w", err) + } + } + } + return nil +} + func (s *Service) reconcileQuotaRecoveryWindow(ctx context.Context, providerValue accountdomain.Provider, accountID uint64, window accountdomain.QuotaWindow) error { if s.quotaQueue == nil || !quotaWindowControlsRouting(providerValue, window.Mode) { return nil @@ -3062,7 +3078,10 @@ func quotaRecoveryDueAt(window accountdomain.QuotaWindow, now time.Time, exhaust // QueueQuotaRefresh asynchronously refreshes the remote quota window after a successful request. func (s *Service) QueueQuotaRefresh(id uint64, mode string) { mode = strings.TrimSpace(mode) - if id == 0 || (!isConsoleUsageQuotaMode(mode) && mode != "weekly" && !isWebChatQuotaMode(mode) && !isWebImagineQuotaMode(mode)) { + if isWebImagineQuotaMode(mode) { + mode = accountdomain.QuotaGroupWebImagine + } + if id == 0 || (!isConsoleUsageQuotaMode(mode) && mode != "weekly" && mode != accountdomain.QuotaGroupWebImagine && !isWebChatQuotaMode(mode)) { return } key := strconv.FormatUint(id, 10) + ":" + mode @@ -3231,10 +3250,10 @@ func (s *Service) runQuotaRefresh(parent context.Context, request quotaRefreshRe break } } - } else if !isWebImagineQuotaMode(request.mode) { + } else if request.mode != accountdomain.QuotaGroupWebImagine { // Weekly remains a Grok Web capability. Console never inherits this // legacy mode and always refreshes its authoritative /usage snapshot. - // Imagine 配额走 /rest/media/imagine/quota_info,保持原 mode,不可被改刷 weekly。 + // Imagine 配额组走 /rest/media/imagine/quota_info,不可被改刷 weekly。 for _, window := range windows[request.accountID] { if window.Mode == "weekly" { refreshMode = "weekly" @@ -3257,7 +3276,15 @@ func (s *Service) runQuotaRefresh(parent context.Context, request quotaRefreshRe } if !skipUpstream && refreshErr == nil && acquired { if err := s.syncPool.Do(ctx, func(workCtx context.Context) error { - _, refreshErr = s.RefreshQuotaMode(workCtx, request.accountID, refreshMode) + if refreshMode == accountdomain.QuotaGroupWebImagine { + var refreshed quotaRefreshResult + refreshed, refreshErr = s.refreshQuotaGroup(workCtx, request.accountID, refreshMode) + if refreshErr == nil { + refreshErr = s.reconcileQuotaGroupWindows(workCtx, refreshed.Credential.Provider, request.accountID, refreshed.Modes, refreshed.Windows) + } + } else { + _, refreshErr = s.RefreshQuotaMode(workCtx, request.accountID, refreshMode) + } return refreshErr }); err != nil { refreshErr = err @@ -3512,8 +3539,7 @@ func isConsoleUsageQuotaMode(mode string) bool { } func isWebImagineQuotaMode(mode string) bool { - _, ok := imagineQuotaBlockModels[mode] - return ok + return accountdomain.IsWebImagineQuotaMode(mode) } func quotaWindowControlsRouting(providerValue accountdomain.Provider, mode string) bool { diff --git a/backend/internal/application/gateway/image.go b/backend/internal/application/gateway/image.go index b6ca7145..f5b3295b 100644 --- a/backend/internal/application/gateway/image.go +++ b/backend/internal/application/gateway/image.go @@ -166,6 +166,7 @@ func (s *Service) executeImage( } }() quotaMode := s.providers.QuotaMode(route.Provider, route.UpstreamModel) + quotaRefreshGroup := s.providers.QuotaRefreshGroup(route.Provider, route.UpstreamModel) attemptPolicy := newRoutingAttemptPolicy(int(s.maxAttempts.Load())) excluded := make(map[uint64]bool) var selection *selectionSession @@ -295,26 +296,25 @@ func (s *Service) executeImage( } } quotaKind, _ := s.providers.QuotaKind(route.Provider) - // catalog 有 Mode 且 effectiveQuotaMode=weekly → imagine 模型,配额为只读快照, - // 本地不递减,仅触发上游 /rest/media/imagine/quota_info 同步以反映消耗。 - imagineModel := quotaMode != "" && effectiveQuotaMode == "weekly" refreshMode := effectiveQuotaMode - if imagineModel { - refreshMode = quotaMode + decrementMode := effectiveQuotaMode + if quotaRefreshGroup != "" { + refreshMode = quotaRefreshGroup + decrementMode = quotaMode } - if successful && quotaKind == provider.QuotaRemoteWindow && (effectiveQuotaMode != "" || imagineModel) { - if refreshMode != "weekly" && !imagineModel { + if successful && quotaKind == provider.QuotaRemoteWindow && refreshMode != "" { + if decrementMode != "" && decrementMode != "weekly" { units := max(1, response.QuotaUnits) var updated bool err := budget.run("quota_decrement", finalizationQuotaBudget, func(stageCtx context.Context) error { var decrementErr error - updated, decrementErr = s.accounts.DecrementWebQuota(stageCtx, accountID, effectiveQuotaMode, units) + updated, decrementErr = s.accounts.DecrementWebQuota(stageCtx, accountID, decrementMode, units) return decrementErr }) if err != nil { - s.logger.Warn("web_quota_decrement_failed", "account_id", accountID, "mode", effectiveQuotaMode, "units", units, "error", err) + s.logger.Warn("web_quota_decrement_failed", "account_id", accountID, "mode", decrementMode, "units", units, "error", err) } else if updated { - s.selector.ConsumeQuota(route.Provider, accountID, effectiveQuotaMode, units) + s.selector.ConsumeQuota(route.Provider, accountID, decrementMode, units) } } s.accounts.QueueQuotaRefresh(accountID, refreshMode) diff --git a/backend/internal/application/gateway/video.go b/backend/internal/application/gateway/video.go index 91c801d1..c5f21d64 100644 --- a/backend/internal/application/gateway/video.go +++ b/backend/internal/application/gateway/video.go @@ -79,7 +79,7 @@ func (s *Service) CreateVideo(ctx context.Context, input VideoInput) (media.Job, return media.Job{}, err } externalModel := model.ExternalPublicID(route.Provider, route.PublicID) - quotaMode := s.providers.QuotaMode(route.Provider, route.UpstreamModel) + quotaMode := videoQuotaMode(route.Provider, s.providers.QuotaMode(route.Provider, route.UpstreamModel), input.Resolution) lease, err := s.selector.AcquireForKey(ctx, route.Provider, route.ID, route.UpstreamModel, quotaMode, "", nil, false, input.ClientKey.AccountScope()) if err != nil { return media.Job{}, fmt.Errorf("%w: %w", ErrNoAvailableAccount, err) @@ -311,7 +311,8 @@ func (s *Service) runVideoJob(parent context.Context, job media.Job, route model defer releaseInputSlot() // 视频任务创建时已持久化账号归属;恢复只能重新获取原账号,禁止因后续 // 轮询或结果处理失败切换到其他账号。 - quotaMode := s.providers.QuotaMode(route.Provider, route.UpstreamModel) + quotaMode := videoQuotaMode(route.Provider, s.providers.QuotaMode(route.Provider, route.UpstreamModel), job.Quality) + quotaRefreshGroup := s.providers.QuotaRefreshGroup(route.Provider, route.UpstreamModel) lease, err := s.selector.AcquirePinned(ctx, route.Provider, job.AccountID, route.ID, route.UpstreamModel, quotaMode, true) if err != nil { if parent.Err() != nil { @@ -433,21 +434,20 @@ func (s *Service) runVideoJob(parent context.Context, job media.Job, route model return } s.selector.MarkSuccess(context.Background(), lease.Credential) - // catalog 有 Mode 且 lease.QuotaMode=weekly → imagine 视频,配额为只读快照, - // 本地不递减,仅触发上游 /rest/media/imagine/quota_info 同步以反映消耗。 - imagineModel := quotaMode != "" && lease.QuotaMode == "weekly" refreshMode := lease.QuotaMode - if imagineModel { - refreshMode = quotaMode + decrementMode := lease.QuotaMode + if quotaRefreshGroup != "" { + refreshMode = quotaRefreshGroup + decrementMode = quotaMode } - if lease.QuotaMode != "" && lease.QuotaMode != "weekly" && !imagineModel { + if decrementMode != "" && decrementMode != "weekly" { quotaCtx, quotaCancel := context.WithTimeout(context.Background(), accountStateWriteTimeout) - updated, quotaErr := s.accounts.DecrementQuota(quotaCtx, job.AccountID, lease.QuotaMode, 1) + updated, quotaErr := s.accounts.DecrementQuota(quotaCtx, job.AccountID, decrementMode, 1) quotaCancel() if quotaErr != nil { - s.logger.Warn("video_quota_decrement_failed", "provider", route.Provider, "account_id", job.AccountID, "mode", lease.QuotaMode, "error", quotaErr) + s.logger.Warn("video_quota_decrement_failed", "provider", route.Provider, "account_id", job.AccountID, "mode", decrementMode, "error", quotaErr) } else if updated { - s.selector.ConsumeQuota(route.Provider, job.AccountID, lease.QuotaMode, 1) + s.selector.ConsumeQuota(route.Provider, job.AccountID, decrementMode, 1) } } if err := s.recordVideoAudit(context.Background(), job, time.Since(startedAt).Milliseconds()); err != nil { @@ -460,6 +460,16 @@ func (s *Service) runVideoJob(parent context.Context, job media.Job, route model s.releaseVideoInputs(job) } +func videoQuotaMode(providerValue account.Provider, catalogMode, resolution string) string { + if providerValue == account.ProviderWeb && catalogMode == account.QuotaModeWebVideo { + resolution = strings.ToLower(strings.TrimSpace(resolution)) + if resolution == "" || resolution == "720p" { + return account.QuotaModeWebVideo720p + } + } + return catalogMode +} + func (s *Service) acquireVideoInputSlot(ctx context.Context, references []string) (func(), error) { hasLocalInput := false for _, reference := range references { diff --git a/backend/internal/application/gateway/video_test.go b/backend/internal/application/gateway/video_test.go index d8240995..61ddad3d 100644 --- a/backend/internal/application/gateway/video_test.go +++ b/backend/internal/application/gateway/video_test.go @@ -20,6 +20,24 @@ import ( "github.com/chenyme/grok2api/backend/internal/repository" ) +func TestVideoQuotaModeUsesWeb720pProduct(t *testing.T) { + tests := []struct { + provider account.Provider + resolution string + want string + }{ + {account.ProviderWeb, "", account.QuotaModeWebVideo720p}, + {account.ProviderWeb, "720p", account.QuotaModeWebVideo720p}, + {account.ProviderWeb, "480p", account.QuotaModeWebVideo}, + {account.ProviderConsole, "720p", account.QuotaModeWebVideo}, + } + for _, test := range tests { + if got := videoQuotaMode(test.provider, account.QuotaModeWebVideo, test.resolution); got != test.want { + t.Fatalf("videoQuotaMode(%s, %q) = %q, want %q", test.provider, test.resolution, got, test.want) + } + } +} + func TestRecoverVideoJobsRetriesUsageWithoutRegeneratingVideo(t *testing.T) { completedAt := time.Now().UTC() repository := &videoUsageRepository{job: media.Job{ diff --git a/backend/internal/domain/account/account.go b/backend/internal/domain/account/account.go index fda62ff7..57c84e42 100644 --- a/backend/internal/domain/account/account.go +++ b/backend/internal/domain/account/account.go @@ -269,6 +269,27 @@ const ( QuotaSourceUpstream QuotaSource = "upstream" ) +const ( + QuotaModeWebImagePro = "image_pro" + QuotaModeWebImageEdit = "image_edit" + QuotaModeWebVideo = "video" + QuotaModeWebVideo720p = "video_720p" + QuotaGroupWebImagine = "web_imagine" +) + +func WebImagineQuotaModes() []string { + return []string{QuotaModeWebImagePro, QuotaModeWebImageEdit, QuotaModeWebVideo, QuotaModeWebVideo720p} +} + +func IsWebImagineQuotaMode(mode string) bool { + switch mode { + case QuotaModeWebImagePro, QuotaModeWebImageEdit, QuotaModeWebVideo, QuotaModeWebVideo720p: + return true + default: + return false + } +} + // QuotaWindow 表示 Provider 单个模式的额度窗口。 type QuotaWindow struct { AccountID uint64 diff --git a/backend/internal/infra/persistence/relational/account_repository.go b/backend/internal/infra/persistence/relational/account_repository.go index 58e857d1..81491d6c 100644 --- a/backend/internal/infra/persistence/relational/account_repository.go +++ b/backend/internal/infra/persistence/relational/account_repository.go @@ -642,7 +642,10 @@ func (r *AccountRepository) getRoutingQuotaWindows(ctx context.Context, provider return result, nil } modes := make([]string, 0, 2) - if provider == account.ProviderWeb { + // Paid Web chat routes are governed by the shared weekly pool. Imagine + // products have independent authoritative windows and must not be hidden by + // a weekly row merely because the same account also has paid chat access. + if provider == account.ProviderWeb && !account.IsWebImagineQuotaMode(quotaMode) { modes = append(modes, "weekly") } if quotaMode != "" { @@ -2102,32 +2105,6 @@ func (r *AccountRepository) UpsertModelQuotaBlock(ctx context.Context, value acc return err } -// OverwriteModelQuotaBlock 无条件以新值覆盖既有的模型冷却块(包括把更长的旧块缩短)。 -// 用于对齐上游权威恢复时刻(如 Imagine quota_info 的 nextAvailableAt), -// 与 UpsertModelQuotaBlock 的“只延长不缩短”保护语义相反,调用方必须确认覆盖是安全的。 -func (r *AccountRepository) OverwriteModelQuotaBlock(ctx context.Context, value account.ModelQuotaBlock) error { - value.UpstreamModel = strings.TrimSpace(value.UpstreamModel) - value.Reason = strings.TrimSpace(value.Reason) - if value.AccountID == 0 || value.UpstreamModel == "" || value.Reason == "" || value.CooldownUntil.IsZero() { - return repository.ErrConflict - } - now := time.Now().UTC() - row := accountModelQuotaBlockModel{ - AccountID: value.AccountID, UpstreamModel: truncate(value.UpstreamModel, 255), Reason: truncate(value.Reason, 100), - CooldownUntil: value.CooldownUntil.UTC(), UpdatedAt: now, - } - err := r.db.db.WithContext(ctx).Clauses(clause.OnConflict{ - Columns: []clause.Column{{Name: "account_id"}, {Name: "upstream_model"}}, - DoUpdates: clause.Assignments(map[string]any{ - "reason": row.Reason, "cooldown_until": row.CooldownUntil, "updated_at": now, - }), - }).Create(&row).Error - if err == nil { - r.notifyInvalidation(ctx, repository.InvalidationEvent{Kind: repository.InvalidationAccountModelQuotaChanged, AccountID: value.AccountID, UpstreamModel: value.UpstreamModel}) - } - return err -} - func (r *AccountRepository) PruneExpiredModelQuotaBlocks(ctx context.Context, now time.Time, limit int) (int64, error) { if limit <= 0 || limit > 1000 { limit = 100 @@ -2331,7 +2308,7 @@ func (r *AccountRepository) GetQuotaWindows(ctx context.Context, accountIDs []ui } func (r *AccountRepository) SaveQuotaWindows(ctx context.Context, accountID uint64, tier account.WebTier, syncedAt time.Time, values []account.QuotaWindow) error { - err := r.saveQuotaWindows(ctx, accountID, tier, syncedAt, values, false) + err := r.saveQuotaWindows(ctx, accountID, tier, syncedAt, values, false, nil) if err == nil { r.notifyInvalidation(ctx, repository.InvalidationEvent{Kind: repository.InvalidationAccountQuotaChanged, AccountID: accountID}) } @@ -2339,14 +2316,48 @@ func (r *AccountRepository) SaveQuotaWindows(ctx context.Context, accountID uint } func (r *AccountRepository) ReplaceQuotaWindows(ctx context.Context, accountID uint64, tier account.WebTier, syncedAt time.Time, values []account.QuotaWindow) error { - err := r.saveQuotaWindows(ctx, accountID, tier, syncedAt, values, true) + err := r.saveQuotaWindows(ctx, accountID, tier, syncedAt, values, true, nil) if err == nil { r.notifyInvalidation(ctx, repository.InvalidationEvent{Kind: repository.InvalidationAccountQuotaChanged, AccountID: accountID}) } return err } -func (r *AccountRepository) saveQuotaWindows(ctx context.Context, accountID uint64, tier account.WebTier, syncedAt time.Time, values []account.QuotaWindow, replace bool) error { +func (r *AccountRepository) ReplaceQuotaWindowGroup(ctx context.Context, accountID uint64, syncedAt time.Time, modes []string, values []account.QuotaWindow) error { + allowed := make(map[string]struct{}, len(modes)) + cleanModes := make([]string, 0, len(modes)) + for _, mode := range modes { + mode = strings.TrimSpace(mode) + if mode == "" { + return repository.ErrConflict + } + if _, exists := allowed[mode]; !exists { + allowed[mode] = struct{}{} + cleanModes = append(cleanModes, mode) + } + } + if accountID == 0 || len(cleanModes) == 0 { + return repository.ErrConflict + } + seen := make(map[string]struct{}, len(values)) + for _, value := range values { + mode := strings.TrimSpace(value.Mode) + if _, ok := allowed[mode]; !ok { + return repository.ErrConflict + } + if _, duplicate := seen[mode]; duplicate { + return repository.ErrConflict + } + seen[mode] = struct{}{} + } + err := r.saveQuotaWindows(ctx, accountID, "", syncedAt, values, false, cleanModes) + if err == nil { + r.notifyInvalidation(ctx, repository.InvalidationEvent{Kind: repository.InvalidationAccountQuotaChanged, AccountID: accountID}) + } + return err +} + +func (r *AccountRepository) saveQuotaWindows(ctx context.Context, accountID uint64, tier account.WebTier, syncedAt time.Time, values []account.QuotaWindow, replace bool, replaceModes []string) error { return r.db.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { if tier != "" { profile := webAccountProfileModel{AccountID: accountID, Tier: string(tier), SyncedAt: &syncedAt} @@ -2358,6 +2369,10 @@ func (r *AccountRepository) saveQuotaWindows(ctx context.Context, accountID uint if err := tx.Where("account_id = ?", accountID).Delete("aWindowModel{}).Error; err != nil { return err } + } else if len(replaceModes) > 0 { + if err := tx.Where("account_id = ? AND mode IN ?", accountID, replaceModes).Delete("aWindowModel{}).Error; err != nil { + return err + } } for _, value := range values { serializedBreakdown := make([]quotaBreakdownJSON, 0, len(value.Breakdown)) diff --git a/backend/internal/infra/persistence/relational/repository_test.go b/backend/internal/infra/persistence/relational/repository_test.go index bde32048..532ce331 100644 --- a/backend/internal/infra/persistence/relational/repository_test.go +++ b/backend/internal/infra/persistence/relational/repository_test.go @@ -256,6 +256,47 @@ func TestAccountRepositoryDecrementsQuotaByAmountAtomically(t *testing.T) { } } +func TestAccountRepositoryReplacesQuotaGroupWithoutTouchingOtherModes(t *testing.T) { + ctx := context.Background() + repo := NewAccountRepository(openTestDatabase(t)) + value, _, err := repo.UpsertByIdentity(ctx, account.Credential{ + Provider: account.ProviderWeb, AuthType: account.AuthTypeSSO, Name: "quota-group", SourceKey: "quota-group", + EncryptedAccessToken: testEncryptedToken, AuthStatus: account.AuthStatusActive, + }) + if err != nil { + t.Fatal(err) + } + now := time.Now().UTC() + initial := []account.QuotaWindow{ + {AccountID: value.ID, Mode: "weekly", Remaining: 90, Total: 100, UpdatedAt: now}, + {AccountID: value.ID, Mode: account.QuotaModeWebImagePro, Remaining: 4, UpdatedAt: now}, + {AccountID: value.ID, Mode: account.QuotaModeWebVideo720p, Remaining: 1, UpdatedAt: now}, + } + if err := repo.SaveQuotaWindows(ctx, value.ID, account.WebTierSuper, now, initial); err != nil { + t.Fatal(err) + } + updatedAt := now.Add(time.Minute) + if err := repo.ReplaceQuotaWindowGroup(ctx, value.ID, updatedAt, account.WebImagineQuotaModes(), []account.QuotaWindow{ + {AccountID: value.ID, Mode: account.QuotaModeWebImagePro, Remaining: 3, UpdatedAt: updatedAt}, + }); err != nil { + t.Fatal(err) + } + windows, err := repo.GetQuotaWindows(ctx, []uint64{value.ID}) + if err != nil { + t.Fatal(err) + } + byMode := make(map[string]account.QuotaWindow) + for _, window := range windows[value.ID] { + byMode[window.Mode] = window + } + if byMode["weekly"].Remaining != 90 || byMode[account.QuotaModeWebImagePro].Remaining != 3 { + t.Fatalf("windows = %#v", windows[value.ID]) + } + if _, exists := byMode[account.QuotaModeWebVideo720p]; exists { + t.Fatalf("explicitly unavailable group mode was preserved: %#v", windows[value.ID]) + } +} + func TestAccountRepositorySummarizesOperationalStates(t *testing.T) { ctx := context.Background() now := time.Now().UTC() diff --git a/backend/internal/infra/persistence/relational/routing_projection_test.go b/backend/internal/infra/persistence/relational/routing_projection_test.go index 3d90cdd7..a211a249 100644 --- a/backend/internal/infra/persistence/relational/routing_projection_test.go +++ b/backend/internal/infra/persistence/relational/routing_projection_test.go @@ -44,6 +44,9 @@ func TestRoutingProjectionLeavesSecretsAndLargeJSONOutOfCandidateLoad(t *testing AccountID: created.ID, Mode: "weekly", Remaining: 10, Total: 20, UsagePercent: 50, Breakdown: []account.QuotaBreakdown{{ProductCode: account.QuotaProductChat, UsagePercent: 50}}, WindowSeconds: 3600, ResetAt: &resetAt, SyncedAt: &now, Source: account.QuotaSourceUpstream, + }, { + AccountID: created.ID, Mode: account.QuotaModeWebImagePro, Remaining: 3, + WindowSeconds: 86400, SyncedAt: &now, Source: account.QuotaSourceUpstream, }}); err != nil { t.Fatal(err) } @@ -62,6 +65,13 @@ func TestRoutingProjectionLeavesSecretsAndLargeJSONOutOfCandidateLoad(t *testing if bases[0].QuotaWindow == nil || bases[0].QuotaWindow.Remaining != 10 || len(bases[0].QuotaWindow.Breakdown) != 0 { t.Fatalf("routing quota = %#v, want scalar quota without breakdown", bases[0].QuotaWindow) } + imagineBases, err := accounts.ListRoutingAccountBases(ctx, account.ProviderWeb, account.QuotaModeWebImagePro) + if err != nil { + t.Fatal(err) + } + if len(imagineBases) != 1 || imagineBases[0].QuotaWindow == nil || imagineBases[0].QuotaWindow.Mode != account.QuotaModeWebImagePro || imagineBases[0].QuotaWindow.Remaining != 3 { + t.Fatalf("Imagine routing quota = %#v", imagineBases) + } candidates, err := accounts.ListRoutingCandidates(ctx, account.ProviderWeb, 0, "grok-test", "") if err != nil { @@ -94,8 +104,8 @@ func TestRoutingProjectionLeavesSecretsAndLargeJSONOutOfCandidateLoad(t *testing if err != nil { t.Fatal(err) } - if len(windows[created.ID]) != 1 || len(windows[created.ID][0].Breakdown) != 1 { - t.Fatalf("management quota windows = %#v, want breakdown", windows) + if len(windows[created.ID]) != 2 { + t.Fatalf("management quota windows = %#v, want two modes", windows) } } diff --git a/backend/internal/infra/provider/provider.go b/backend/internal/infra/provider/provider.go index 358927b8..d1bd8288 100644 --- a/backend/internal/infra/provider/provider.go +++ b/backend/internal/infra/provider/provider.go @@ -240,6 +240,17 @@ type QuotaSnapshot struct { SyncedAt time.Time } +// QuotaGroupSnapshot is an authoritative snapshot for a group of quota modes +// returned by one upstream request. Modes lists the complete local scope so +// callers can atomically remove products that the upstream explicitly reports +// as unavailable without touching unrelated quota windows. +type QuotaGroupSnapshot struct { + Group string + Modes []string + Windows []account.QuotaWindow + SyncedAt time.Time +} + type ImageGenerationRequest struct { Credential account.Credential Model string @@ -387,6 +398,20 @@ type QuotaAdapter interface { SyncQuotaMode(ctx context.Context, credential account.Credential, mode string) (account.QuotaWindow, error) } +// QuotaGroupAdapter is optional. It is used when one upstream endpoint returns +// several related quota products as one authoritative response. +type QuotaGroupAdapter interface { + Adapter + SyncQuotaGroup(ctx context.Context, credential account.Credential, group string) (QuotaGroupSnapshot, error) +} + +// QuotaRefreshMetadataAdapter maps a model to an internal refresh group. The +// group is scheduling metadata, not a routable quota mode. +type QuotaRefreshMetadataAdapter interface { + Adapter + QuotaRefreshGroup(upstreamModel string) string +} + // WebAccountSettingsAdapter defines upstream profile-setting capabilities for Grok Web SSO accounts. // This capability belongs only to the Web Provider; Build and Console must not emulate it through generic account logic. type WebAccountSettingsAdapter interface { @@ -749,6 +774,15 @@ func (r *Registry) Quota(value account.Provider) (QuotaAdapter, bool) { return result, ok } +func (r *Registry) QuotaGroup(value account.Provider) (QuotaGroupAdapter, bool) { + adapter, ok := r.Get(value) + if !ok { + return nil, false + } + result, ok := adapter.(QuotaGroupAdapter) + return result, ok +} + // WebAccountSettings returns the Grok Web-specific account profile settings capability. func (r *Registry) WebAccountSettings() (WebAccountSettingsAdapter, bool) { adapter, ok := r.Get(account.ProviderWeb) @@ -771,6 +805,18 @@ func (r *Registry) QuotaMode(value account.Provider, upstreamModel string) strin return metadata.QuotaMode(upstreamModel) } +func (r *Registry) QuotaRefreshGroup(value account.Provider, upstreamModel string) string { + adapter, ok := r.Get(value) + if !ok { + return "" + } + metadata, ok := adapter.(QuotaRefreshMetadataAdapter) + if !ok { + return "" + } + return metadata.QuotaRefreshGroup(upstreamModel) +} + func (r *Registry) TierOrder(value account.Provider, upstreamModel string) []account.WebTier { adapter, ok := r.Get(value) if !ok { diff --git a/backend/internal/infra/provider/web/adapter.go b/backend/internal/infra/provider/web/adapter.go index 0d39acc9..b338a5ea 100644 --- a/backend/internal/infra/provider/web/adapter.go +++ b/backend/internal/infra/provider/web/adapter.go @@ -115,6 +115,13 @@ func (a *Adapter) QuotaMode(upstreamModel string) string { return "" } +func (a *Adapter) QuotaRefreshGroup(upstreamModel string) string { + if spec, ok := Resolve(upstreamModel); ok && account.IsWebImagineQuotaMode(spec.Mode) { + return account.QuotaGroupWebImagine + } + return "" +} + func (a *Adapter) TierOrder(upstreamModel string) []account.WebTier { spec, ok := Resolve(upstreamModel) if !ok { diff --git a/backend/internal/infra/provider/web/protocol_test.go b/backend/internal/infra/provider/web/protocol_test.go index 56f22b85..62c428fa 100644 --- a/backend/internal/infra/provider/web/protocol_test.go +++ b/backend/internal/infra/provider/web/protocol_test.go @@ -1056,6 +1056,18 @@ func TestOnlyChatModelsExposeRateLimitModes(t *testing.T) { } } +func TestQuotaRefreshGroupSeparatesImagineEndpointFromLiteChatQuota(t *testing.T) { + adapter := &Adapter{} + if got := adapter.QuotaRefreshGroup("grok-imagine-image"); got != "" { + t.Fatalf("lite refresh group = %q", got) + } + for _, model := range []string{"grok-imagine-image-quality", "imagine-x-1", "imagine-image-edit", "grok-imagine-video"} { + if got := adapter.QuotaRefreshGroup(model); got != account.QuotaGroupWebImagine { + t.Fatalf("QuotaRefreshGroup(%q) = %q", model, got) + } + } +} + func TestConsumeUpstreamChatFixture(t *testing.T) { fixture := strings.Join([]string{ `data: {"result":{"conversation":{"conversationId":"conv_1"}}}`, diff --git a/backend/internal/infra/provider/web/quota.go b/backend/internal/infra/provider/web/quota.go index 1d0ee660..eb47bd6a 100644 --- a/backend/internal/infra/provider/web/quota.go +++ b/backend/internal/infra/provider/web/quota.go @@ -21,53 +21,52 @@ import ( const weeklyQuotaMode = "weekly" func (a *Adapter) SyncQuota(ctx context.Context, credential account.Credential) (provider.QuotaSnapshot, error) { - windows := make([]account.QuotaWindow, 0, 2) + chatWindows := make([]account.QuotaWindow, 0, 2) autoWindow, autoErr := a.SyncQuotaMode(ctx, credential, "auto") if errors.Is(autoErr, provider.ErrUnauthorized) { return provider.QuotaSnapshot{}, autoErr } if autoErr == nil { - windows = append(windows, autoWindow) + chatWindows = append(chatWindows, autoWindow) } fastWindow, fastErr := a.SyncQuotaMode(ctx, credential, "fast") if errors.Is(fastErr, provider.ErrUnauthorized) { return provider.QuotaSnapshot{}, fastErr } if fastErr == nil { - windows = append(windows, fastWindow) + chatWindows = append(chatWindows, fastWindow) } - imagineWindows, imagineErr := a.syncImagineQuota(ctx, credential) - if errors.Is(imagineErr, provider.ErrUnauthorized) { + imagineSnapshot, imagineErr := a.SyncQuotaGroup(ctx, credential, account.QuotaGroupWebImagine) + if imagineErr != nil { + // A full refresh replaces every stored window. Never return a partial + // snapshot, otherwise a transient Imagine failure would erase the last + // known authoritative media quotas. return provider.QuotaSnapshot{}, imagineErr } - if imagineErr == nil { - windows = append(windows, imagineWindows...) - } - if len(windows) > 0 { - tier, _ := resolveWebTierFromQuota(credential.WebTier, windows, false) + if len(chatWindows) > 0 { + tier, _ := resolveWebTierFromQuota(credential.WebTier, chatWindows, false) + var windows []account.QuotaWindow // Basic/未知账号没有付费周池,避免为每次完整同步额外访问付费端点。 // 只有模式额度已经确认付费等级时才读取 weekly 作为权威额度。 if tier == account.WebTierSuper || tier == account.WebTierHeavy { if weekly, weeklyErr := a.syncWeeklyCredits(ctx, credential); weeklyErr == nil { // 周池覆盖 chat 模式窗口,但保留 imagine 窗口供前端展示与触顶判定。 - kept := make([]account.QuotaWindow, 0, 1+len(imagineWindows)) + kept := make([]account.QuotaWindow, 0, 1+len(imagineSnapshot.Windows)) kept = append(kept, weekly) - if imagineErr == nil { - kept = append(kept, imagineWindows...) - } + kept = append(kept, imagineSnapshot.Windows...) windows = kept } } + if windows == nil { + windows = append(chatWindows, imagineSnapshot.Windows...) + } return provider.QuotaSnapshot{Tier: tier, Windows: windows, SyncedAt: time.Now().UTC()}, nil } // 模式端点暂不可用时,仅已确认的付费账号允许用 weekly 兜底; // Basic/Auto 不能凭周额度探测提权,也不应制造无意义的付费端点流量。 if credential.WebTier == account.WebTierSuper || credential.WebTier == account.WebTierHeavy { if weekly, weeklyErr := a.syncWeeklyCredits(ctx, credential); weeklyErr == nil { - kept := []account.QuotaWindow{weekly} - if imagineErr == nil { - kept = append(kept, imagineWindows...) - } + kept := append([]account.QuotaWindow{weekly}, imagineSnapshot.Windows...) return provider.QuotaSnapshot{Tier: credential.WebTier, Windows: kept, SyncedAt: time.Now().UTC()}, nil } else { return provider.QuotaSnapshot{}, weeklyErr @@ -79,19 +78,22 @@ func (a *Adapter) SyncQuota(ctx context.Context, credential account.Credential) return provider.QuotaSnapshot{}, autoErr } -// syncImagineQuota 调用 POST /rest/media/imagine/quota_info 同步 Imagine 文本生图/编辑/视频配额。 -// 上游响应按产品字段返回剩余次数与窗口长度,不含总量;以同步时刻剩余次数近似总量, -// 触顶后 remaining=0。该窗口仅用于前端展示与配额刷新时的触顶判定,selector 选号冷却 -// 由 ModelQuotaBlock 承载(见 syncAccountCapabilities 触顶写入)。 -func (a *Adapter) syncImagineQuota(ctx context.Context, credential account.Credential) ([]account.QuotaWindow, error) { +// SyncQuotaGroup refreshes the authoritative Web Imagine quota group. The +// upstream endpoint returns every media product in one response, so callers +// must persist the snapshot atomically instead of treating its fields as four +// independent requests. +func (a *Adapter) SyncQuotaGroup(ctx context.Context, credential account.Credential, group string) (provider.QuotaGroupSnapshot, error) { + if group != account.QuotaGroupWebImagine { + return provider.QuotaGroupSnapshot{}, fmt.Errorf("unsupported Web quota group %q", group) + } cfg := a.config() token, err := a.cipher.Decrypt(credential.EncryptedAccessToken) if err != nil { - return nil, err + return provider.QuotaGroupSnapshot{}, err } lease, err := a.egress.AcquireCredential(ctx, domainegress.ScopeWeb, credential) if err != nil { - return nil, err + return provider.QuotaGroupSnapshot{}, err } defer lease.Release() endpoint := cfg.BaseURL + "/rest/media/imagine/quota_info" @@ -99,7 +101,7 @@ func (a *Adapter) syncImagineQuota(ctx context.Context, credential account.Crede defer cancel() request, err := http.NewRequestWithContext(requestCtx, http.MethodPost, endpoint, bytes.NewReader([]byte("{}"))) if err != nil { - return nil, err + return provider.QuotaGroupSnapshot{}, err } request.Header = buildHeaders(token, lease, "application/json") applyAppHeaders(request.Header, cfg.BaseURL, cfg.BaseURL+"/imagine") @@ -107,80 +109,108 @@ func (a *Adapter) syncImagineQuota(ctx context.Context, credential account.Crede response, err := lease.DoDeferredForbidden(request) if err != nil { a.egress.Feedback(context.WithoutCancel(ctx), lease.NodeID, 0, err) - return nil, err + return provider.QuotaGroupSnapshot{}, err } body, err := io.ReadAll(io.LimitReader(response.Body, 4<<20)) _ = response.Body.Close() if err != nil { - return nil, err + return provider.QuotaGroupSnapshot{}, err } if response.StatusCode == http.StatusUnauthorized { - return nil, provider.ErrUnauthorized + return provider.QuotaGroupSnapshot{}, provider.ErrUnauthorized } if response.StatusCode == http.StatusForbidden && provider.IsDefinitiveAccountBlockBody(body) { - return nil, fmt.Errorf("%w: account blocked", provider.ErrUnauthorized) + return provider.QuotaGroupSnapshot{}, fmt.Errorf("%w: account blocked", provider.ErrUnauthorized) } if response.StatusCode < 200 || response.StatusCode >= 300 { a.egress.Feedback(context.WithoutCancel(ctx), lease.NodeID, response.StatusCode, nil) - return nil, fmt.Errorf("Grok Web Imagine 配额接口返回 %d", response.StatusCode) + return provider.QuotaGroupSnapshot{}, fmt.Errorf("Grok Web Imagine 配额接口返回 %d", response.StatusCode) } a.egress.Feedback(context.WithoutCancel(ctx), lease.NodeID, response.StatusCode, nil) - var value struct { - Image *imagineQuotaProduct `json:"image"` - ImagePro *imagineQuotaProduct `json:"imagePro"` - ImageEdit *imagineQuotaProduct `json:"imageEdit"` - Video *imagineQuotaProduct `json:"video"` - Video720p *imagineQuotaProduct `json:"video720p"` - } - if err := json.Unmarshal(body, &value); err != nil { - return nil, err - } now := time.Now().UTC() - windows := make([]account.QuotaWindow, 0, 4) - windows = appendImagineQuotaWindow(windows, credential.ID, "image_pro", value.ImagePro, now) - windows = appendImagineQuotaWindow(windows, credential.ID, "image_edit", value.ImageEdit, now) - windows = appendImagineQuotaWindow(windows, credential.ID, "video", value.Video, now) - windows = appendImagineQuotaWindow(windows, credential.ID, "video_720p", value.Video720p, now) - return windows, nil + windows, err := decodeImagineQuotaSnapshot(body, credential.ID, now) + if err != nil { + return provider.QuotaGroupSnapshot{}, err + } + return provider.QuotaGroupSnapshot{ + Group: account.QuotaGroupWebImagine, Modes: account.WebImagineQuotaModes(), Windows: windows, SyncedAt: now, + }, nil } type imagineQuotaProduct struct { - Available bool `json:"available"` - RemainingQueries int `json:"remainingQueries"` - WindowSizeSeconds int `json:"windowSizeSeconds"` + Available *bool `json:"available"` + RemainingQueries *int `json:"remainingQueries"` + WindowSizeSeconds *int `json:"windowSizeSeconds"` NextAvailableAt *time.Time `json:"nextAvailableAt"` } func isImagineQuotaMode(mode string) bool { - switch mode { - case "image_pro", "image_edit", "video", "video_720p": - return true - default: - return false - } + return account.IsWebImagineQuotaMode(mode) } -func appendImagineQuotaWindow(windows []account.QuotaWindow, accountID uint64, mode string, product *imagineQuotaProduct, now time.Time) []account.QuotaWindow { - if product == nil || !product.Available { - return windows +func decodeImagineQuotaSnapshot(body []byte, accountID uint64, now time.Time) ([]account.QuotaWindow, error) { + var fields map[string]json.RawMessage + if err := json.Unmarshal(body, &fields); err != nil { + return nil, fmt.Errorf("解析 Grok Web Imagine 配额: %w", err) } - windowSeconds := product.WindowSizeSeconds - if windowSeconds <= 0 { - windowSeconds = 86400 + products := []struct { + field string + mode string + }{ + {"image", ""}, // lite uses the chat fast/weekly quota path. + {"imagePro", account.QuotaModeWebImagePro}, + {"imageEdit", account.QuotaModeWebImageEdit}, + {"video", account.QuotaModeWebVideo}, + {"video720p", account.QuotaModeWebVideo720p}, } - remaining := product.RemainingQueries - if remaining < 0 { - remaining = 0 + windows := make([]account.QuotaWindow, 0, 4) + for _, item := range products { + raw, ok := fields[item.field] + if !ok { + return nil, fmt.Errorf("Grok Web Imagine 配额响应缺少字段 %s", item.field) + } + if bytes.Equal(bytes.TrimSpace(raw), []byte("null")) { + continue + } + var product imagineQuotaProduct + if err := json.Unmarshal(raw, &product); err != nil { + return nil, fmt.Errorf("解析 Grok Web Imagine 配额字段 %s: %w", item.field, err) + } + if product.Available == nil { + return nil, fmt.Errorf("Grok Web Imagine 配额字段 %s 结构不完整", item.field) + } + if item.mode == "" { + continue + } + if *product.Available && (product.RemainingQueries == nil || product.WindowSizeSeconds == nil) { + return nil, fmt.Errorf("Grok Web Imagine 配额字段 %s 结构不完整", item.field) + } + remaining := 0 + if product.RemainingQueries != nil { + remaining = max(0, *product.RemainingQueries) + } + windowSeconds := 86400 + if product.WindowSizeSeconds != nil { + windowSeconds = *product.WindowSizeSeconds + } + if windowSeconds <= 0 { + return nil, fmt.Errorf("Grok Web Imagine 配额字段 %s 的 windowSizeSeconds 无效", item.field) + } + var resetAt *time.Time + if product.NextAvailableAt != nil { + value := product.NextAvailableAt.UTC() + resetAt = &value + } else if !*product.Available || remaining == 0 { + value := now.Add(time.Duration(windowSeconds) * time.Second) + resetAt = &value + } + windows = append(windows, account.QuotaWindow{ + AccountID: accountID, Mode: item.mode, Remaining: remaining, Total: 0, + WindowSeconds: windowSeconds, ResetAt: resetAt, SyncedAt: &now, + Source: account.QuotaSourceUpstream, UpdatedAt: now, + }) } - // 上游返回 nextAvailableAt 时直接对齐恢复时刻,否则按窗口时长估算。 - resetAt := now.Add(time.Duration(windowSeconds) * time.Second) - if product.NextAvailableAt != nil { - resetAt = *product.NextAvailableAt - } - return append(windows, account.QuotaWindow{ - AccountID: accountID, Mode: mode, Remaining: remaining, Total: remaining, - WindowSeconds: windowSeconds, ResetAt: &resetAt, SyncedAt: &now, Source: account.QuotaSourceUpstream, UpdatedAt: now, - }) + return windows, nil } func resolveWebTierFromQuota(current account.WebTier, windows []account.QuotaWindow, weeklyAvailable bool) (account.WebTier, bool) { @@ -247,12 +277,12 @@ func (a *Adapter) SyncQuotaMode(ctx context.Context, credential account.Credenti if mode == weeklyQuotaMode { return a.syncWeeklyCredits(ctx, credential) } - if isImagineQuotaMode(mode) { - windows, err := a.syncImagineQuota(ctx, credential) + if account.IsWebImagineQuotaMode(mode) { + snapshot, err := a.SyncQuotaGroup(ctx, credential, account.QuotaGroupWebImagine) if err != nil { return account.QuotaWindow{}, err } - for _, w := range windows { + for _, w := range snapshot.Windows { if w.Mode == mode { return w, nil } diff --git a/backend/internal/infra/provider/web/quota_test.go b/backend/internal/infra/provider/web/quota_test.go index a1ad19b0..9c7e8bab 100644 --- a/backend/internal/infra/provider/web/quota_test.go +++ b/backend/internal/infra/provider/web/quota_test.go @@ -9,6 +9,7 @@ import ( "math" "net/http" "net/http/httptest" + "strings" "sync" "sync/atomic" "testing" @@ -77,6 +78,8 @@ func TestSyncQuotaFetchesWeeklyOnlyAfterPaidTierIsConfirmed(t *testing.T) { var weeklyCalls atomic.Int64 server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { switch request.URL.Path { + case "/rest/media/imagine/quota_info": + writeEmptyImagineQuota(writer) case "/grok_api_v2.GrokBuildBilling/GetGrokCreditsConfig": weeklyCalls.Add(1) writer.Header().Set("Content-Type", "application/grpc-web+proto") @@ -386,6 +389,8 @@ func TestSyncQuotaCorrectsStoredSuperFromFreshWebQuota(t *testing.T) { var weeklyCalls atomic.Int64 server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { switch request.URL.Path { + case "/rest/media/imagine/quota_info": + writeEmptyImagineQuota(writer) case "/grok_api_v2.GrokBuildBilling/GetGrokCreditsConfig": weeklyCalls.Add(1) http.Error(writer, "not available", http.StatusNotFound) @@ -440,3 +445,63 @@ func TestSyncQuotaCorrectsStoredSuperFromFreshWebQuota(t *testing.T) { t.Fatalf("basic account probed weekly endpoint %d times", weeklyCalls.Load()) } } + +func writeEmptyImagineQuota(writer http.ResponseWriter) { + writer.Header().Set("Content-Type", "application/json") + _, _ = writer.Write([]byte(`{"image":null,"imageEdit":null,"imagePro":null,"video":null,"video720p":null}`)) +} + +func TestDecodeImagineQuotaSnapshotMatchesObservedProtocol(t *testing.T) { + now := time.Date(2026, 8, 13, 8, 0, 0, 0, time.UTC) + body := []byte(`{ + "image": null, + "imageEdit": null, + "imagePro": {"available":true,"remainingQueries":4,"windowSizeSeconds":86400}, + "video": null, + "video720p": {"available":true,"remainingQueries":1,"windowSizeSeconds":86400} + }`) + windows, err := decodeImagineQuotaSnapshot(body, 42, now) + if err != nil { + t.Fatal(err) + } + if len(windows) != 2 { + t.Fatalf("windows = %#v", windows) + } + if windows[0].Mode != account.QuotaModeWebImagePro || windows[0].Remaining != 4 || windows[0].Total != 0 || windows[0].ResetAt != nil { + t.Fatalf("image_pro = %#v", windows[0]) + } + if windows[1].Mode != account.QuotaModeWebVideo720p || windows[1].Remaining != 1 || windows[1].Total != 0 || windows[1].ResetAt != nil { + t.Fatalf("video_720p = %#v", windows[1]) + } +} + +func TestDecodeImagineQuotaSnapshotRequiresCompleteResponse(t *testing.T) { + now := time.Now().UTC() + _, err := decodeImagineQuotaSnapshot([]byte(`{"image":null,"imageEdit":null,"imagePro":null,"video":null}`), 42, now) + if err == nil || !strings.Contains(err.Error(), "video720p") { + t.Fatalf("err = %v", err) + } +} + +func TestDecodeImagineQuotaSnapshotAcceptsExplicitUnavailableProduct(t *testing.T) { + now := time.Now().UTC() + windows, err := decodeImagineQuotaSnapshot([]byte(`{ + "image":null,"imageEdit":{"available":false},"imagePro":null,"video":null,"video720p":null + }`), 42, now) + if err != nil { + t.Fatal(err) + } + if len(windows) != 1 || windows[0].Mode != account.QuotaModeWebImageEdit || windows[0].Remaining != 0 || windows[0].ResetAt == nil { + t.Fatalf("windows = %#v", windows) + } +} + +func TestDecodeImagineQuotaSnapshotRejectsIncompleteAvailableProduct(t *testing.T) { + now := time.Now().UTC() + _, err := decodeImagineQuotaSnapshot([]byte(`{ + "image":null,"imageEdit":null,"imagePro":{"available":true},"video":null,"video720p":null + }`), 42, now) + if err == nil || !strings.Contains(err.Error(), "imagePro") { + t.Fatalf("err = %v", err) + } +} diff --git a/backend/internal/repository/account.go b/backend/internal/repository/account.go index 60bf5463..bd07fd88 100644 --- a/backend/internal/repository/account.go +++ b/backend/internal/repository/account.go @@ -157,8 +157,6 @@ type AccountRepository interface { // MarkWebBirthDateSet 幂等记录 Web 账号首次确认生日已设置的时间。 MarkWebBirthDateSet(ctx context.Context, id uint64, setAt time.Time) error UpsertModelQuotaBlock(ctx context.Context, value account.ModelQuotaBlock) error - // OverwriteModelQuotaBlock 无条件覆盖既有模型冷却块(可缩短),用于对齐上游权威恢复时刻。 - OverwriteModelQuotaBlock(ctx context.Context, value account.ModelQuotaBlock) error PruneExpiredModelQuotaBlocks(ctx context.Context, now time.Time, limit int) (int64, error) SaveBilling(ctx context.Context, value account.Billing) error GetBilling(ctx context.Context, accountID uint64) (account.Billing, error) @@ -171,6 +169,7 @@ type AccountRepository interface { HasQuotaWindows(ctx context.Context, accountID uint64) (bool, error) GetQuotaWindows(ctx context.Context, accountIDs []uint64) (map[uint64][]account.QuotaWindow, error) ReplaceQuotaWindows(ctx context.Context, accountID uint64, tier account.WebTier, syncedAt time.Time, values []account.QuotaWindow) error + ReplaceQuotaWindowGroup(ctx context.Context, accountID uint64, syncedAt time.Time, modes []string, values []account.QuotaWindow) error SaveQuotaWindows(ctx context.Context, accountID uint64, tier account.WebTier, syncedAt time.Time, values []account.QuotaWindow) error UpsertManyByIdentity(ctx context.Context, values []account.Credential) ([]AccountUpsertResult, error) DecrementQuotaWindow(ctx context.Context, accountID uint64, mode string, now time.Time) (bool, error) diff --git a/frontend/src/features/accounts/account-quota.tsx b/frontend/src/features/accounts/account-quota.tsx index 16ab7119..8843cb6e 100644 --- a/frontend/src/features/accounts/account-quota.tsx +++ b/frontend/src/features/accounts/account-quota.tsx @@ -186,8 +186,9 @@ function ImagineQuotaRow({ windows, locale, t }: { windows: WebQuotaWindow[]; lo {columns.map(({ mode }) => { const window = windowsByMode.get(mode)!; const exhausted = window.remaining <= 0; - const used = Math.max(0, window.total - window.remaining); - const percent = window.total > 0 ? Math.max(0, Math.min(100, used / window.total * 100)) : 100; + const hasTotal = window.total > 0; + const used = hasTotal ? Math.max(0, window.total - window.remaining) : 0; + const percent = hasTotal ? Math.max(0, Math.min(100, used / window.total * 100)) : 0; const label = imagineModeLabel(mode, t); return ( @@ -197,11 +198,15 @@ function ImagineQuotaRow({ windows, locale, t }: { windows: WebQuotaWindow[]; lo {label} {exhausted ? ( {t("accounts.imagineQuotaExhausted")} - ) : ( + ) : hasTotal ? ( {formatNumber(window.remaining, locale, 0)}/{formatNumber(window.total, locale, 0)} + ) : ( + {t("accounts.imagineQuotaRemaining", { remaining: formatNumber(window.remaining, locale, 0) })} )} -
+
+ {exhausted ?
: hasTotal ?
: null} +