feat: enhance BatchUpdate to validate account provider and handle account pool mismatches

This commit is contained in:
Chenyme committed 2026-07-28 16:16:06 +08:00
1 parent f4f439a462
commit 2a336686fd
11 files changed
+317 -37

No files matched your search

@@ -0,0 +1,79 @@
package account
import (
"context"
"errors"
"slices"
"testing"
accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account"
"github.com/chenyme/grok2api/backend/internal/repository"
)
type batchUpdateRepository struct {
repository.AccountRepository
updateErr error
updatedIDs []uint64
}
func (r *batchUpdateRepository) UpdateMany(_ context.Context, providerValue accountdomain.Provider, ids []uint64, _ repository.AccountUpdates) (int64, error) {
if providerValue != accountdomain.ProviderBuild {
return 0, errors.New("unexpected provider")
}
r.updatedIDs = append([]uint64(nil), ids...)
if r.updateErr != nil {
return 0, r.updateErr
}
return int64(len(ids)), nil
}
func TestBatchUpdateSupportsMoreThanAdminPageLimit(t *testing.T) {
ids := make([]uint64, 2501)
for index := range ids {
ids[index] = uint64(index + 1)
}
repo := &batchUpdateRepository{}
service := NewService(repo, nil, nil, nil, nil, nil, nil)
maxConcurrent := 3
updated, err := service.BatchUpdate(context.Background(), accountdomain.ProviderBuild, ids, UpdateInput{MaxConcurrent: &maxConcurrent})
if err != nil {
t.Fatal(err)
}
if updated != int64(len(ids)) || !slices.Equal(repo.updatedIDs, ids) {
t.Fatalf("updated = %d, ids = %d", updated, len(repo.updatedIDs))
}
}
func TestBatchUpdatePreservesProviderMismatchSemantics(t *testing.T) {
ids := make([]uint64, 501)
for index := range ids {
ids[index] = uint64(index + 1)
}
repo := &batchUpdateRepository{updateErr: repository.ErrAccountPoolMismatch}
service := NewService(repo, nil, nil, nil, nil, nil, nil)
maxConcurrent := 3
_, err := service.BatchUpdate(context.Background(), accountdomain.ProviderBuild, ids, UpdateInput{MaxConcurrent: &maxConcurrent})
if !errors.Is(err, ErrAccountPoolMismatch) {
t.Fatalf("error = %v, want account pool mismatch", err)
}
}
func TestBatchUpdateRetainsBoundedRequestSize(t *testing.T) {
ids := make([]uint64, maxBatchUpdateAccounts+1)
for index := range ids {
ids[index] = uint64(index + 1)
}
repo := &batchUpdateRepository{}
service := NewService(repo, nil, nil, nil, nil, nil, nil)
maxConcurrent := 3
_, err := service.BatchUpdate(context.Background(), accountdomain.ProviderBuild, ids, UpdateInput{MaxConcurrent: &maxConcurrent})
if !errors.Is(err, ErrInvalidInput) {
t.Fatalf("error = %v, want invalid input", err)
}
if len(repo.updatedIDs) != 0 {
t.Fatal("oversized update reached repository")
}
}
+34 -20
View File
@@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"log/slog"
"slices"
"strconv"
"strings"
"sync"
@@ -22,18 +23,19 @@ import (
)
var (
ErrDevicePending = errors.New("Device OAuth 等待用户授权")
ErrDeviceSlowDown = errors.New("Device OAuth 轮询过快")
ErrDeviceDenied = errors.New("Device OAuth 已拒绝或过期")
ErrInvalidFilter = errors.New("账号筛选条件无效")
ErrInvalidInput = errors.New("账号参数无效")
ErrInvalidImport = errors.New("账号凭据格式无效")
ErrImportLimit = errors.New("导入账号数量超过限制")
ErrExportLimit = errors.New("导出账号数量超过限制")
ErrNotFound = errors.New("账号不存在")
ErrUnsupported = errors.New("账号来源不支持该操作")
ErrConversionBusy = errors.New("账号正在转换为 Grok Build")
ErrConflict = errors.New("账号操作存在冲突")
ErrDevicePending = errors.New("Device OAuth 等待用户授权")
ErrDeviceSlowDown = errors.New("Device OAuth 轮询过快")
ErrDeviceDenied = errors.New("Device OAuth 已拒绝或过期")
ErrInvalidFilter = errors.New("账号筛选条件无效")
ErrInvalidInput = errors.New("账号参数无效")
ErrInvalidImport = errors.New("账号凭据格式无效")
ErrImportLimit = errors.New("导入账号数量超过限制")
ErrExportLimit = errors.New("导出账号数量超过限制")
ErrNotFound = errors.New("账号不存在")
ErrUnsupported = errors.New("账号来源不支持该操作")
ErrConversionBusy = errors.New("账号正在转换为 Grok Build")
ErrConflict = errors.New("账号操作存在冲突")
ErrAccountPoolMismatch = errors.New("批量操作包含不属于当前号池的账号")
)
var ErrCredentialRefreshPermanent = errors.New("OAuth refresh token 已永久失效")
@@ -63,6 +65,7 @@ const (
credentialImportChunkSize = 100
maxQuotaResetAccounts = 10000
quotaResetChunkSize = 500
maxBatchUpdateAccounts = 10000
maxBuildConversionAccounts = 1000
maxWebConsoleSyncAccounts = 1000
accountTaskBatchSize = 1000
@@ -561,12 +564,16 @@ func validAssociationFilter(providerValue, association string) bool {
}
}
// BatchUpdate 对一组账号应用同一组路由参数,单次最多处理一个管理端最大分页。
func (s *Service) BatchUpdate(ctx context.Context, ids []uint64, input UpdateInput) (int64, error) {
ids, err := normalizeBatchIDs(ids)
// BatchUpdate 对同一号池的一组账号应用相同路由参数。
func (s *Service) BatchUpdate(ctx context.Context, providerValue accountdomain.Provider, ids []uint64, input UpdateInput) (int64, error) {
ids, err := normalizeIDs(ids, maxBatchUpdateAccounts)
if err != nil {
return 0, err
}
if !providerValue.IsValid() {
return 0, invalidInput("账号来源无效")
}
slices.Sort(ids)
if input.MaxConcurrent != nil && (*input.MaxConcurrent < 1 || *input.MaxConcurrent > accountdomain.MaxConcurrent) {
return 0, invalidInput("maxConcurrent 必须在 1 到 256 之间")
}
@@ -576,13 +583,17 @@ func (s *Service) BatchUpdate(ctx context.Context, ids []uint64, input UpdateInp
if input.Name != nil {
return 0, invalidInput("批量更新不支持修改账号名称")
}
updated, err := s.accounts.UpdateMany(ctx, ids, repository.AccountUpdates{Enabled: input.Enabled, Priority: input.Priority, MaxConcurrent: input.MaxConcurrent, MinimumRemaining: input.MinimumRemaining})
updated, err := s.accounts.UpdateMany(ctx, providerValue, ids, repository.AccountUpdates{Enabled: input.Enabled, Priority: input.Priority, MaxConcurrent: input.MaxConcurrent, MinimumRemaining: input.MinimumRemaining})
if err != nil {
return 0, err
return 0, mapRepositoryError(err)
}
if input.Enabled != nil && !*input.Enabled {
for _, id := range ids {
_ = s.sticky.DeleteByAccount(ctx, id)
if input.Enabled != nil && !*input.Enabled && s.sticky != nil {
if batchDeleter, ok := s.sticky.(repository.StickySessionBatchDeleter); ok {
_ = batchDeleter.DeleteByAccounts(ctx, ids)
} else {
for _, id := range ids {
_ = s.sticky.DeleteByAccount(ctx, id)
}
}
}
return updated, nil
@@ -3277,6 +3288,9 @@ func mapLinkedDeleteError(err error) error {
}
func mapRepositoryError(err error) error {
if errors.Is(err, repository.ErrAccountPoolMismatch) {
return ErrAccountPoolMismatch
}
if errors.Is(err, repository.ErrNotFound) {
return ErrNotFound
}
@@ -0,0 +1,112 @@
package relational
import (
"context"
"errors"
"fmt"
"testing"
"time"
"github.com/chenyme/grok2api/backend/internal/domain/account"
"github.com/chenyme/grok2api/backend/internal/repository"
)
func TestAccountRepositoryUpdateManyChunksLargeAccountPool(t *testing.T) {
ctx := context.Background()
database := openTestDatabase(t)
repo := NewAccountRepository(database)
rows := seedBatchUpdateAccounts(t, database, 2001)
ids := accountModelIDs(rows)
maxConcurrent := 3
updated, err := repo.UpdateMany(ctx, account.ProviderBuild, ids, repository.AccountUpdates{MaxConcurrent: &maxConcurrent})
if err != nil {
t.Fatal(err)
}
if updated != int64(len(ids)) {
t.Fatalf("updated = %d, want %d", updated, len(ids))
}
var count int64
if err := database.db.Model(&accountModel{}).Where("max_concurrent = ?", maxConcurrent).Count(&count).Error; err != nil {
t.Fatal(err)
}
if count != int64(len(ids)) {
t.Fatalf("stored count = %d, want %d", count, len(ids))
}
}
func TestAccountRepositoryUpdateManyRollsBackAllChunks(t *testing.T) {
ctx := context.Background()
database := openTestDatabase(t)
repo := NewAccountRepository(database)
rows := seedBatchUpdateAccounts(t, database, accountUpdateBatchSize+1)
ids := accountModelIDs(rows)
failingID := ids[len(ids)-1]
trigger := fmt.Sprintf(`CREATE TRIGGER fail_batch_account_update BEFORE UPDATE OF max_concurrent ON provider_accounts WHEN NEW.id = %d BEGIN SELECT RAISE(ABORT, 'forced batch failure'); END`, failingID)
if err := database.db.Exec(trigger).Error; err != nil {
t.Fatal(err)
}
maxConcurrent := 3
updated, err := repo.UpdateMany(ctx, account.ProviderBuild, ids, repository.AccountUpdates{MaxConcurrent: &maxConcurrent})
if err == nil || updated != 0 {
t.Fatalf("updated = %d, error = %v", updated, err)
}
var changed int64
if err := database.db.Model(&accountModel{}).Where("id IN ? AND max_concurrent = ?", ids, maxConcurrent).Count(&changed).Error; err != nil {
t.Fatal(err)
}
if changed != 0 {
t.Fatalf("transaction left %d changed rows", changed)
}
}
func TestAccountRepositoryUpdateManyRejectsMixedProviderBeforeWriting(t *testing.T) {
ctx := context.Background()
database := openTestDatabase(t)
repo := NewAccountRepository(database)
rows := seedBatchUpdateAccounts(t, database, accountUpdateBatchSize+1)
ids := accountModelIDs(rows)
if err := database.db.Model(&accountModel{}).Where("id = ?", ids[len(ids)-1]).Update("provider", account.ProviderWeb).Error; err != nil {
t.Fatal(err)
}
maxConcurrent := 3
updated, err := repo.UpdateMany(ctx, account.ProviderBuild, ids, repository.AccountUpdates{MaxConcurrent: &maxConcurrent})
if !errors.Is(err, repository.ErrAccountPoolMismatch) || updated != 0 {
t.Fatalf("updated = %d, error = %v", updated, err)
}
var changed int64
if err := database.db.Model(&accountModel{}).Where("id IN ? AND max_concurrent = ?", ids, maxConcurrent).Count(&changed).Error; err != nil {
t.Fatal(err)
}
if changed != 0 {
t.Fatalf("provider mismatch left %d changed rows", changed)
}
}
func seedBatchUpdateAccounts(t *testing.T, database *Database, count int) []accountModel {
t.Helper()
now := time.Now().UTC()
rows := make([]accountModel, count)
for index := range rows {
rows[index] = accountModel{
IdentityKey: fmt.Sprintf("%064x", index+1),
Provider: string(account.ProviderBuild), Name: fmt.Sprintf("batch-%d", index+1), SourceKey: fmt.Sprintf("batch-%d", index+1),
Enabled: true, AuthStatus: string(account.AuthStatusActive), Priority: account.DefaultPriority, MaxConcurrent: account.DefaultMaxConcurrent,
BuildRouteMode: string(account.BuildRouteAuto), CreatedAt: now, UpdatedAt: now,
}
}
if err := database.db.CreateInBatches(&rows, 200).Error; err != nil {
t.Fatal(err)
}
return rows
}
func accountModelIDs(rows []accountModel) []uint64 {
ids := make([]uint64, len(rows))
for index := range rows {
ids[index] = rows[index].ID
}
return ids
}
@@ -38,6 +38,7 @@ type quotaBreakdownJSON struct {
}
const (
accountUpdateBatchSize = 500
accountPaidPlanSignal = `(LOWER(REPLACE(REPLACE(REPLACE(REPLACE(TRIM(billing.plan_code), ' ', ''), '_', ''), '-', ''), '+', 'plus')) IN ('super', 'supergrok', 'supergrokpro', 'supergrokheavy', 'supergroklite', 'grokpro', 'xpremium', 'xpremiumplus', 'apikey') OR LOWER(REPLACE(REPLACE(REPLACE(REPLACE(TRIM(billing.plan_name), ' ', ''), '_', ''), '-', ''), '+', 'plus')) IN ('super', 'supergrok', 'supergrokpro', 'supergrokheavy', 'supergroklite', 'grokpro', 'xpremium', 'xpremiumplus', 'apikey'))`
accountFreePlanSignal = `(LOWER(REPLACE(REPLACE(REPLACE(REPLACE(TRIM(billing.plan_code), ' ', ''), '_', ''), '-', ''), '+', 'plus')) IN ('free', 'grokfree', 'freetier', 'basic', 'grokbasic', 'xbasic') OR LOWER(REPLACE(REPLACE(REPLACE(REPLACE(TRIM(billing.plan_name), ' ', ''), '_', ''), '-', ''), '+', 'plus')) IN ('free', 'grokfree', 'freetier', 'basic', 'grokbasic', 'xbasic'))`
accountPaidBillingSignals = `(` + accountPaidPlanSignal + ` OR billing.monthly_limit > 0 OR billing.on_demand_cap > 0 OR billing.on_demand_used > 0 OR billing.prepaid_balance > 0)`
@@ -1255,7 +1256,7 @@ func (r *AccountRepository) markWebProfileTimestamp(ctx context.Context, id uint
}))
}
func (r *AccountRepository) UpdateMany(ctx context.Context, ids []uint64, updates repository.AccountUpdates) (int64, error) {
func (r *AccountRepository) UpdateMany(ctx context.Context, providerValue account.Provider, ids []uint64, updates repository.AccountUpdates) (int64, error) {
if len(ids) == 0 {
return 0, nil
}
@@ -1275,11 +1276,40 @@ func (r *AccountRepository) UpdateMany(ctx context.Context, ids []uint64, update
if len(values) == 0 {
return 0, nil
}
result := r.db.db.WithContext(ctx).Model(&accountModel{}).Where("id IN ?", ids).Updates(values)
if result.Error == nil && result.RowsAffected > 0 {
var updated int64
err := r.db.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
for start := 0; start < len(ids); start += accountUpdateBatchSize {
end := min(start+accountUpdateBatchSize, len(ids))
var rows []accountModel
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Select("id", "provider").Where("id IN ?", ids[start:end]).Order("id ASC").Find(&rows).Error; err != nil {
return err
}
if len(rows) != end-start {
return repository.ErrAccountPoolMismatch
}
for _, row := range rows {
if account.Provider(row.Provider) != providerValue {
return repository.ErrAccountPoolMismatch
}
}
}
for start := 0; start < len(ids); start += accountUpdateBatchSize {
end := min(start+accountUpdateBatchSize, len(ids))
result := tx.Model(&accountModel{}).Where("provider = ? AND id IN ?", providerValue, ids[start:end]).Updates(values)
if result.Error != nil {
return result.Error
}
updated += result.RowsAffected
}
return nil
})
if err != nil {
return 0, err
}
if updated > 0 {
r.notifyInvalidation(ctx, repository.InvalidationEvent{Kind: repository.InvalidationAccountStateChanged})
}
return result.RowsAffected, result.Error
return updated, nil
}
// UpdateEgressBindings assigns one egress node to multiple accounts of one
@@ -0,0 +1,44 @@
package relational
import (
"context"
"os"
"testing"
"github.com/chenyme/grok2api/backend/internal/domain/account"
"github.com/chenyme/grok2api/backend/internal/repository"
)
func TestPostgresAccountBatchUpdateBeyondAdminPageLimit(t *testing.T) {
dsn := os.Getenv("TEST_POSTGRES_DSN")
if dsn == "" {
t.Skip("TEST_POSTGRES_DSN is not configured")
}
ctx := context.Background()
database, err := OpenPostgres(ctx, dsn, 5, 2)
if err != nil {
t.Fatal(err)
}
defer database.Close()
if err := database.InitializeSchema(ctx); err != nil {
t.Fatal(err)
}
rows := seedBatchUpdateAccounts(t, database, 2001)
ids := accountModelIDs(rows)
maxConcurrent := 3
updated, err := NewAccountRepository(database).UpdateMany(ctx, account.ProviderBuild, ids, repository.AccountUpdates{MaxConcurrent: &maxConcurrent})
if err != nil {
t.Fatal(err)
}
if updated != int64(len(ids)) {
t.Fatalf("updated = %d, want %d", updated, len(ids))
}
var count int64
if err := database.db.Model(&accountModel{}).Where("id IN ? AND max_concurrent = ?", ids, maxConcurrent).Count(&count).Error; err != nil {
t.Fatal(err)
}
if count != int64(len(ids)) {
t.Fatalf("stored count = %d, want %d", count, len(ids))
}
}
@@ -959,7 +959,7 @@ func TestPostgresRoutingProjectionAndCredentialHydration(t *testing.T) {
t.Fatalf("cross-provider credential error = %v, want ErrNotFound", err)
}
disabled := false
if _, err := accounts.UpdateMany(ctx, []uint64{created.ID}, repository.AccountUpdates{Enabled: &disabled}); err != nil {
if _, err := accounts.UpdateMany(ctx, account.ProviderBuild, []uint64{created.ID}, repository.AccountUpdates{Enabled: &disabled}); err != nil {
t.Fatal(err)
}
if _, err := accounts.GetCredentialMaterial(ctx, created.ID, account.ProviderWeb); !errors.Is(err, repository.ErrNotFound) {
@@ -146,7 +146,7 @@ func TestGetCredentialMaterialHydratesOneAccountAndMapsNotFound(t *testing.T) {
t.Fatalf("cross-provider credential material error = %v, want ErrNotFound", err)
}
disabled := false
if _, err := accounts.UpdateMany(ctx, []uint64{created.ID}, repository.AccountUpdates{Enabled: &disabled}); err != nil {
if _, err := accounts.UpdateMany(ctx, account.ProviderBuild, []uint64{created.ID}, repository.AccountUpdates{Enabled: &disabled}); err != nil {
t.Fatal(err)
}
if _, err := accounts.GetCredentialMaterial(ctx, created.ID, account.ProviderBuild); !errors.Is(err, repository.ErrNotFound) {
+1 -1
View File
@@ -87,7 +87,7 @@ type AccountRepository interface {
GetQuotaRecoveries(ctx context.Context, accountIDs []uint64) (map[uint64]account.QuotaRecovery, error)
UpsertByIdentity(ctx context.Context, value account.Credential) (account.Credential, bool, error)
Update(ctx context.Context, value account.Credential) (account.Credential, error)
UpdateMany(ctx context.Context, ids []uint64, updates AccountUpdates) (int64, error)
UpdateMany(ctx context.Context, provider account.Provider, ids []uint64, updates AccountUpdates) (int64, error)
Delete(ctx context.Context, id uint64) error
DeleteMany(ctx context.Context, ids []uint64) (int64, error)
// ResolveLinkedDeleteIDs expands root account IDs with one-hop (or Build/Console two-hop via Web)
+5 -4
View File
@@ -6,10 +6,11 @@ import (
)
var (
ErrNotFound = errors.New("repository: not found")
ErrConflict = errors.New("repository: conflict")
ErrLimitExceeded = errors.New("repository: limit exceeded")
ErrInvalidRecord = errors.New("repository: invalid record")
ErrNotFound = errors.New("repository: not found")
ErrConflict = errors.New("repository: conflict")
ErrLimitExceeded = errors.New("repository: limit exceeded")
ErrInvalidRecord = errors.New("repository: invalid record")
ErrAccountPoolMismatch = errors.New("repository: account pool mismatch")
)
// InvalidBatchRecordError identifies a deterministic invalid record without
@@ -438,10 +438,7 @@ func (h *Handler) batchUpdate(c *gin.Context) {
response.Error(c, http.StatusBadRequest, "invalidId", err.Error())
return
}
if !h.validateProviderIDs(c, ids, request.Provider) {
return
}
updated, err := h.service.BatchUpdate(c.Request.Context(), ids, accountapp.UpdateInput{Enabled: request.Enabled, Priority: request.Priority, MaxConcurrent: request.MaxConcurrent, MinimumRemaining: request.MinimumRemaining})
updated, err := h.service.BatchUpdate(c.Request.Context(), accountdomain.Provider(request.Provider), ids, accountapp.UpdateInput{Enabled: request.Enabled, Priority: request.Priority, MaxConcurrent: request.MaxConcurrent, MinimumRemaining: request.MinimumRemaining})
if err != nil {
h.writeServiceError(c, "accountBatchUpdateFailed", err, http.StatusInternalServerError, "批量更新账号失败")
return
@@ -1284,6 +1281,8 @@ func (h *Handler) writeServiceError(c *gin.Context, code string, err error, fall
response.Error(c, http.StatusBadRequest, "accountExportLimitExceeded", err.Error())
case errors.Is(err, accountapp.ErrInvalidInput), errors.Is(err, accountapp.ErrInvalidImport):
response.Error(c, http.StatusBadRequest, code, err.Error())
case errors.Is(err, accountapp.ErrAccountPoolMismatch):
response.Error(c, http.StatusConflict, "accountPoolMismatch", err.Error())
case errors.Is(err, accountapp.ErrConflict):
response.Error(c, http.StatusConflict, code, err.Error())
case errors.Is(err, accountapp.ErrNotFound):
@@ -1636,7 +1636,7 @@ export function AccountsPage() {
if (!open && batchConcurrencyMutation.isPending) return;
setBatchConcurrencyOpen(open);
}}>
<DialogContent>
<DialogContent className="sm:max-w-[460px]">
<DialogHeader>
<DialogTitle>{t("accounts.batchConcurrencyTitle", { count: selected.size })}</DialogTitle>
<DialogDescription>{t("accounts.batchConcurrencyDescription")}</DialogDescription>
@@ -1654,9 +1654,10 @@ export function AccountsPage() {
/>
</div>
<DialogFooter>
<Button type="button" variant="outline" disabled={batchConcurrencyMutation.isPending} onClick={() => setBatchConcurrencyOpen(false)}>{t("common.cancel")}</Button>
<Button type="button" variant="secondary" size="sm" disabled={batchConcurrencyMutation.isPending} onClick={() => setBatchConcurrencyOpen(false)}>{t("common.cancel")}</Button>
<Button
type="button"
size="sm"
disabled={batchConcurrencyMutation.isPending || !Number.isInteger(Number(batchMaxConcurrent)) || Number(batchMaxConcurrent) < 1 || Number(batchMaxConcurrent) > 256}
onClick={() => batchConcurrencyMutation.mutate(Number(batchMaxConcurrent))}
>