mirror of
https://github.com/chenyme/grok2api.git
synced 2026-12-06 00:01:05 +00:00
放宽「同一 Provider + 同一 upstream 只能有一条路由」的限制,使管理端可创建:
gpt-5.4 → grok-4.5 gpt-5.5 → grok-4.5 并与发现/目录产生的 grok-4.5 → grok-4.5 共存。 仍保持 对外名 public_id 全局唯一;重复创建同一个 gpt-5.5 继续 409。
This commit is contained in:
1 parent
4fcc97d939
commit
037faab38b
6 files changed
+295
-28
No files matched your search
@@ -0,0 +1,179 @@
|
||||
package relational
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/chenyme/grok2api/backend/internal/domain/account"
|
||||
"github.com/chenyme/grok2api/backend/internal/domain/model"
|
||||
"github.com/chenyme/grok2api/backend/internal/repository"
|
||||
)
|
||||
|
||||
func TestMultiplePublicIDsCanShareUpstream(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database := openTestDatabase(t)
|
||||
repo := NewModelRepository(database)
|
||||
accounts := NewAccountRepository(database)
|
||||
buildAccount, _, err := accounts.UpsertByIdentity(ctx, account.Credential{
|
||||
Provider: account.ProviderBuild, Name: "build", SourceKey: "build-multi-public",
|
||||
EncryptedAccessToken: testEncryptedToken, AuthStatus: account.AuthStatusActive, Enabled: true,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := repo.ReplaceAccountCapabilities(ctx, buildAccount.ID, []string{"grok-4.5"}, time.Now().UTC()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
discovered, err := repo.Create(ctx, model.Route{
|
||||
PublicID: "grok-4.5", Provider: account.ProviderBuild, UpstreamModel: "grok-4.5",
|
||||
Capability: model.CapabilityResponses, Origin: model.OriginDiscovered, Enabled: true,
|
||||
}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
aliasA, err := repo.Create(ctx, model.Route{
|
||||
PublicID: "gpt-5.4", Provider: account.ProviderBuild, UpstreamModel: "grok-4.5",
|
||||
Capability: model.CapabilityResponses, Origin: model.OriginManual, Enabled: true,
|
||||
}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
aliasB, err := repo.Create(ctx, model.Route{
|
||||
PublicID: "gpt-5.5", Provider: account.ProviderBuild, UpstreamModel: "grok-4.5",
|
||||
Capability: model.CapabilityResponses, Origin: model.OriginManual, Enabled: true,
|
||||
}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := repo.Create(ctx, model.Route{
|
||||
PublicID: "gpt-5.5", Provider: account.ProviderBuild, UpstreamModel: "grok-4.5",
|
||||
Capability: model.CapabilityResponses, Origin: model.OriginManual, Enabled: true,
|
||||
}, nil); !errors.Is(err, repository.ErrConflict) {
|
||||
t.Fatalf("duplicate public id error = %v, want conflict", err)
|
||||
}
|
||||
|
||||
preferred, err := repo.GetByProviderUpstream(ctx, account.ProviderBuild, "grok-4.5")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if preferred.ID != discovered.ID || preferred.PublicID != "Build/grok-4.5" {
|
||||
t.Fatalf("preferred route = %#v, want discovered %#v", preferred, discovered)
|
||||
}
|
||||
|
||||
for _, publicID := range []string{"gpt-5.4", "gpt-5.5", "grok-4.5"} {
|
||||
route, lookupErr := repo.GetByPublicIDIncludingDisabled(ctx, publicID)
|
||||
if lookupErr != nil {
|
||||
t.Fatalf("lookup %s: %v", publicID, lookupErr)
|
||||
}
|
||||
if route.UpstreamModel != "grok-4.5" {
|
||||
t.Fatalf("route %s upstream = %q", publicID, route.UpstreamModel)
|
||||
}
|
||||
}
|
||||
if aliasA.PublicID != "Build/gpt-5.4" || aliasB.PublicID != "Build/gpt-5.5" {
|
||||
t.Fatalf("alias public ids = %#v %#v", aliasA, aliasB)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpsertDiscoveredCreatesCanonicalWhenManualAliasExists(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database := openTestDatabase(t)
|
||||
repo := NewModelRepository(database)
|
||||
|
||||
manual, err := repo.Create(ctx, model.Route{
|
||||
PublicID: "gpt-5.5", Provider: account.ProviderBuild, UpstreamModel: "grok-4.5",
|
||||
Capability: model.CapabilityResponses, Origin: model.OriginManual, Enabled: true,
|
||||
}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := repo.UpsertDiscovered(ctx, account.ProviderBuild, []string{"grok-4.5"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var rows []modelRouteModel
|
||||
if err := database.db.WithContext(ctx).Where("provider = ? AND upstream_model = ?", account.ProviderBuild, "grok-4.5").Order("id ASC").Find(&rows).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(rows) != 2 {
|
||||
t.Fatalf("routes = %#v", rows)
|
||||
}
|
||||
if rows[0].ID != manual.ID || rows[0].PublicID != "Build/gpt-5.5" || rows[0].Origin != string(model.OriginManual) {
|
||||
t.Fatalf("manual route rewritten: %#v", rows[0])
|
||||
}
|
||||
if rows[1].PublicID != "Build/grok-4.5" || rows[1].Origin != string(model.OriginDiscovered) {
|
||||
t.Fatalf("discovered route missing: %#v", rows[1])
|
||||
}
|
||||
}
|
||||
|
||||
func TestReplaceProviderRoutesKeepsManualAliasesWithSharedUpstream(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database := openTestDatabase(t)
|
||||
repo := NewModelRepository(database)
|
||||
|
||||
if err := repo.UpsertRoutes(ctx, []model.Route{
|
||||
{PublicID: "grok-chat-fast", Provider: account.ProviderWeb, UpstreamModel: "fast", Capability: model.CapabilityChat, Enabled: true},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
manual, err := repo.Create(ctx, model.Route{
|
||||
PublicID: "gpt-fast", Provider: account.ProviderWeb, UpstreamModel: "fast",
|
||||
Capability: model.CapabilityChat, Origin: model.OriginManual, Enabled: true,
|
||||
}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var catalogBefore modelRouteModel
|
||||
if err := database.db.WithContext(ctx).Where("public_id = ?", "Web/grok-chat-fast").First(&catalogBefore).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := repo.ReplaceProviderRoutes(ctx, account.ProviderWeb, []model.Route{
|
||||
{PublicID: "grok-chat-fast", Provider: account.ProviderWeb, UpstreamModel: "grok-chat-fast", Capability: model.CapabilityChat, Enabled: true},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var catalogAfter modelRouteModel
|
||||
if err := database.db.WithContext(ctx).Where("id = ?", catalogBefore.ID).First(&catalogAfter).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if catalogAfter.PublicID != "Web/grok-chat-fast" || catalogAfter.UpstreamModel != "grok-chat-fast" {
|
||||
t.Fatalf("catalog route = %#v", catalogAfter)
|
||||
}
|
||||
var manualAfter modelRouteModel
|
||||
if err := database.db.WithContext(ctx).Where("id = ?", manual.ID).First(&manualAfter).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if manualAfter.PublicID != "Web/gpt-fast" || manualAfter.UpstreamModel != "fast" || manualAfter.Origin != string(model.OriginManual) {
|
||||
t.Fatalf("manual alias rewritten: %#v", manualAfter)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDropProviderUpstreamUniqueIndexOnUpgrade(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database := openTestDatabase(t)
|
||||
if err := database.db.WithContext(ctx).Exec("CREATE UNIQUE INDEX IF NOT EXISTS uidx_provider_upstream ON model_routes(provider, upstream_model)").Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertSQLiteMissingIndexes(t, database, "model_routes", "uidx_provider_upstream")
|
||||
assertSQLiteIndexes(t, database, "model_routes", "idx_model_routes_provider_upstream")
|
||||
|
||||
repo := NewModelRepository(database)
|
||||
if _, err := repo.Create(ctx, model.Route{
|
||||
PublicID: "shared-a", Provider: account.ProviderBuild, UpstreamModel: "shared-upstream",
|
||||
Capability: model.CapabilityResponses, Origin: model.OriginManual, Enabled: true,
|
||||
}, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := repo.Create(ctx, model.Route{
|
||||
PublicID: "shared-b", Provider: account.ProviderBuild, UpstreamModel: "shared-upstream",
|
||||
Capability: model.CapabilityResponses, Origin: model.OriginManual, Enabled: true,
|
||||
}, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -223,11 +223,35 @@ func findModelRoutesByPublicID(db *gorm.DB, publicID string) ([]modelRouteModel,
|
||||
}
|
||||
|
||||
func (r *ModelRepository) GetByProviderUpstream(ctx context.Context, provider account.Provider, upstreamModel string) (model.Route, error) {
|
||||
var row modelRouteModel
|
||||
if err := r.availableRoutes(r.db.db.WithContext(ctx)).Where("provider = ? AND upstream_model = ? AND enabled = ?", provider, upstreamModel, true).First(&row).Error; err != nil {
|
||||
var rows []modelRouteModel
|
||||
if err := r.availableRoutes(r.db.db.WithContext(ctx)).Where("provider = ? AND upstream_model = ? AND enabled = ?", provider, upstreamModel, true).Find(&rows).Error; err != nil {
|
||||
return model.Route{}, mapError(err)
|
||||
}
|
||||
return toModelDomain(row), nil
|
||||
if len(rows) == 0 {
|
||||
return model.Route{}, repository.ErrNotFound
|
||||
}
|
||||
return toModelDomain(preferProviderUpstreamRoute(provider, upstreamModel, rows)), nil
|
||||
}
|
||||
|
||||
// preferProviderUpstreamRoute 在同一上游存在多条对外名路由时选出稳定代表路由。
|
||||
func preferProviderUpstreamRoute(provider account.Provider, upstreamModel string, rows []modelRouteModel) modelRouteModel {
|
||||
preferred := rows[0]
|
||||
localID, _ := discoveredRouteDefaults(provider, upstreamModel)
|
||||
canonical, hasCanonical := model.NormalizePublicID(provider, localID)
|
||||
for _, row := range rows {
|
||||
if hasCanonical && row.PublicID == canonical {
|
||||
return row
|
||||
}
|
||||
originPreferred := row.Origin == string(model.OriginDiscovered) || row.Origin == string(model.OriginCatalog)
|
||||
currentPreferred := preferred.Origin == string(model.OriginDiscovered) || preferred.Origin == string(model.OriginCatalog)
|
||||
switch {
|
||||
case originPreferred && !currentPreferred:
|
||||
preferred = row
|
||||
case originPreferred == currentPreferred && row.ID < preferred.ID:
|
||||
preferred = row
|
||||
}
|
||||
}
|
||||
return preferred
|
||||
}
|
||||
|
||||
func (r *ModelRepository) ReplaceAccountCapabilities(ctx context.Context, accountID uint64, upstreamModels []string, syncedAt time.Time) error {
|
||||
@@ -307,26 +331,20 @@ func (r *ModelRepository) UpsertDiscovered(ctx context.Context, provider account
|
||||
if err := tx.Where("provider = ?", provider).Find(&existing).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
existingUpstream := make(map[string]bool, len(existing))
|
||||
publicIDs := make(map[string]bool, len(existing))
|
||||
for _, row := range existing {
|
||||
if row.Provider == string(provider) {
|
||||
existingUpstream[row.UpstreamModel] = true
|
||||
}
|
||||
publicIDs[row.PublicID] = true
|
||||
}
|
||||
rows := make([]modelRouteModel, 0, len(upstreamModels))
|
||||
for _, upstreamModel := range upstreamModels {
|
||||
if existingUpstream[upstreamModel] {
|
||||
continue
|
||||
}
|
||||
localID, capability := discoveredRouteDefaults(provider, upstreamModel)
|
||||
publicID, ok := model.NormalizePublicID(provider, localID)
|
||||
if !ok {
|
||||
return fmt.Errorf("Provider %s 发现了无效模型 ID %q", provider, localID)
|
||||
}
|
||||
// 仅按规范 public_id 幂等;允许手动别名路由与发现路由共享同一上游。
|
||||
if publicIDs[publicID] {
|
||||
return fmt.Errorf("Provider %s 的模型公开 ID %q 冲突", provider, publicID)
|
||||
continue
|
||||
}
|
||||
if err := ensureModelPublicIDNotAlias(tx, publicID, 0); err != nil {
|
||||
return err
|
||||
@@ -335,7 +353,7 @@ func (r *ModelRepository) UpsertDiscovered(ctx context.Context, provider account
|
||||
rows = append(rows, modelRouteModel{PublicID: publicID, Provider: string(provider), UpstreamModel: upstreamModel, Capability: string(capability), Origin: string(model.OriginDiscovered), Enabled: true})
|
||||
}
|
||||
if len(rows) > 0 {
|
||||
// 多实例可能同时发现同一上游模型;唯一约束负责最终幂等,避免竞态变成整批失败。
|
||||
// 多实例可能同时发现同一规范 public_id;public_id 唯一约束负责最终幂等。
|
||||
result := tx.Clauses(clause.OnConflict{DoNothing: true}).CreateInBatches(rows, 200)
|
||||
changed = result.Error == nil && result.RowsAffected > 0
|
||||
return result.Error
|
||||
@@ -389,7 +407,7 @@ func (r *ModelRepository) UpsertRoutes(ctx context.Context, values []model.Route
|
||||
return fmt.Errorf("模型路由目录包含无效条目")
|
||||
}
|
||||
var existing modelRouteModel
|
||||
err := tx.Where("provider = ? AND upstream_model = ?", value.Provider, value.UpstreamModel).First(&existing).Error
|
||||
err := tx.Where("public_id = ?", value.PublicID).First(&existing).Error
|
||||
if err == nil {
|
||||
continue
|
||||
}
|
||||
@@ -439,22 +457,39 @@ func (r *ModelRepository) ReplaceProviderRoutes(ctx context.Context, provider ac
|
||||
return err
|
||||
}
|
||||
|
||||
byUpstream := make(map[string]modelRouteModel, len(existing))
|
||||
byPublicID := make(map[string]modelRouteModel, len(existing))
|
||||
byUpstreamNonManual := make(map[string][]modelRouteModel, len(existing))
|
||||
for _, row := range existing {
|
||||
byUpstream[row.UpstreamModel] = row
|
||||
byPublicID[row.PublicID] = row
|
||||
if row.Origin == string(model.OriginManual) {
|
||||
continue
|
||||
}
|
||||
byUpstreamNonManual[row.UpstreamModel] = append(byUpstreamNonManual[row.UpstreamModel], row)
|
||||
}
|
||||
matched := make(map[int]modelRouteModel, len(values))
|
||||
usedIDs := make(map[uint64]bool, len(values))
|
||||
for index, value := range values {
|
||||
row, ok := byUpstream[value.UpstreamModel]
|
||||
if !ok || usedIDs[row.ID] {
|
||||
row, ok = byPublicID[value.PublicID]
|
||||
}
|
||||
if ok && !usedIDs[row.ID] {
|
||||
if row, ok := byPublicID[value.PublicID]; ok && !usedIDs[row.ID] {
|
||||
matched[index] = row
|
||||
usedIDs[row.ID] = true
|
||||
continue
|
||||
}
|
||||
// 仅回退匹配非手动路由,避免把手动别名路由改写成目录项。
|
||||
candidates := byUpstreamNonManual[value.UpstreamModel]
|
||||
var chosen modelRouteModel
|
||||
found := false
|
||||
for _, candidate := range candidates {
|
||||
if usedIDs[candidate.ID] {
|
||||
continue
|
||||
}
|
||||
if !found || candidate.ID < chosen.ID {
|
||||
chosen = candidate
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if found {
|
||||
matched[index] = chosen
|
||||
usedIDs[chosen.ID] = true
|
||||
}
|
||||
}
|
||||
for _, row := range existing {
|
||||
@@ -474,8 +509,8 @@ func (r *ModelRepository) ReplaceProviderRoutes(ctx context.Context, provider ac
|
||||
return err
|
||||
}
|
||||
}
|
||||
// Both identifiers are unique. Temporary values allow public IDs or upstream
|
||||
// identifiers to be swapped while stable route IDs and key permissions survive.
|
||||
// Temporary values allow public IDs or upstream identifiers to be swapped while
|
||||
// stable route IDs and key permissions survive.
|
||||
for index, row := range matched {
|
||||
if row.PublicID != values[index].PublicID {
|
||||
if err := preserveModelRouteAlias(tx, row.PublicID, row.ID); err != nil {
|
||||
|
||||
@@ -179,8 +179,8 @@ func (quotaRecoveryModel) TableName() string { return "account_quota_recovery" }
|
||||
type modelRouteModel struct {
|
||||
ID uint64 `gorm:"primaryKey;autoIncrement"`
|
||||
PublicID string `gorm:"size:255;uniqueIndex;not null;check:chk_model_routes_public_id,length(trim(public_id)) BETWEEN 1 AND 255"`
|
||||
Provider string `gorm:"size:32;uniqueIndex:uidx_provider_upstream;not null;check:chk_model_routes_provider,provider IN ('grok_build','grok_web','grok_console')"`
|
||||
UpstreamModel string `gorm:"size:255;uniqueIndex:uidx_provider_upstream;not null;check:chk_model_routes_upstream_model,length(trim(upstream_model)) BETWEEN 1 AND 255"`
|
||||
Provider string `gorm:"size:32;index:idx_model_routes_provider_upstream;not null;check:chk_model_routes_provider,provider IN ('grok_build','grok_web','grok_console')"`
|
||||
UpstreamModel string `gorm:"size:255;index:idx_model_routes_provider_upstream;not null;check:chk_model_routes_upstream_model,length(trim(upstream_model)) BETWEEN 1 AND 255"`
|
||||
Capability string `gorm:"size:32;not null;check:chk_model_routes_capability,capability IN ('responses','chat','image','image_edit','video')"`
|
||||
Origin string `gorm:"size:32;not null;default:discovered;check:chk_model_routes_origin,origin IN ('catalog','discovered','manual')"`
|
||||
Enabled bool `gorm:"not null"`
|
||||
|
||||
@@ -63,7 +63,7 @@ var schemaIndexes = []string{
|
||||
"CREATE INDEX IF NOT EXISTS idx_account_credentials_refresh_due ON account_credentials(refresh_due_at, account_id)",
|
||||
"CREATE INDEX IF NOT EXISTS idx_quota_windows_due ON account_quota_windows(remaining, reset_at, account_id)",
|
||||
"CREATE UNIQUE INDEX IF NOT EXISTS idx_model_routes_public_id ON model_routes(public_id)",
|
||||
"CREATE UNIQUE INDEX IF NOT EXISTS uidx_provider_upstream ON model_routes(provider, upstream_model)",
|
||||
"CREATE INDEX IF NOT EXISTS idx_model_routes_provider_upstream ON model_routes(provider, upstream_model)",
|
||||
"CREATE INDEX IF NOT EXISTS idx_model_routes_created_id ON model_routes(created_at DESC, id DESC)",
|
||||
"CREATE INDEX IF NOT EXISTS idx_model_routes_enabled ON model_routes(enabled, public_id, id)",
|
||||
"CREATE INDEX IF NOT EXISTS idx_model_route_aliases_route ON model_route_aliases(model_route_id, alias)",
|
||||
@@ -175,6 +175,9 @@ func (d *Database) initializeSchema(ctx context.Context) error {
|
||||
if err := d.dropRedundantResponseExpiryIndexes(ctx); err != nil {
|
||||
return fmt.Errorf("迁移响应过期索引: %w", err)
|
||||
}
|
||||
if err := d.dropProviderUpstreamUniqueIndex(ctx); err != nil {
|
||||
return fmt.Errorf("迁移模型路由上游唯一约束: %w", err)
|
||||
}
|
||||
for _, statement := range schemaIndexes {
|
||||
if err := db.Exec(statement).Error; err != nil {
|
||||
return fmt.Errorf("初始化数据库索引: %w", err)
|
||||
@@ -232,6 +235,14 @@ func (d *Database) dropRedundantResponseExpiryIndexes(ctx context.Context) error
|
||||
return nil
|
||||
}
|
||||
|
||||
// dropProviderUpstreamUniqueIndex 允许同一 Provider 下多条对外名映射到同一上游模型。
|
||||
func (d *Database) dropProviderUpstreamUniqueIndex(ctx context.Context) error {
|
||||
if err := d.db.WithContext(ctx).Exec("DROP INDEX IF EXISTS uidx_provider_upstream").Error; err != nil {
|
||||
return fmt.Errorf("drop index uidx_provider_upstream: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// backfillReauthMarkedAt 为历史 reauthRequired 账号补齐清理锚点;优先使用 updated_at。
|
||||
func (d *Database) backfillReauthMarkedAt(ctx context.Context) error {
|
||||
return d.db.WithContext(ctx).Exec(`
|
||||
|
||||
@@ -65,7 +65,9 @@ func TestInitializeSchemaUpgradesProviderChecksForConsole(t *testing.T) {
|
||||
}
|
||||
}
|
||||
assertSQLiteUniqueIndexes(t, database, "provider_accounts", "idx_provider_accounts_identity_key")
|
||||
assertSQLiteUniqueIndexes(t, database, "model_routes", "idx_model_routes_public_id", "uidx_provider_upstream")
|
||||
assertSQLiteUniqueIndexes(t, database, "model_routes", "idx_model_routes_public_id")
|
||||
assertSQLiteIndexes(t, database, "model_routes", "idx_model_routes_provider_upstream")
|
||||
assertSQLiteMissingIndexes(t, database, "model_routes", "uidx_provider_upstream")
|
||||
assertTableColumns(t, database, "response_ownership", []string{"prompt_cache_key", "reasoning_replay_key"}, nil)
|
||||
}
|
||||
|
||||
@@ -125,6 +127,46 @@ func assertSQLiteUniqueIndexes(t *testing.T, database *Database, table string, e
|
||||
}
|
||||
}
|
||||
|
||||
func assertSQLiteIndexes(t *testing.T, database *Database, table string, expected ...string) {
|
||||
t.Helper()
|
||||
var indexes []struct {
|
||||
Name string
|
||||
Unique int
|
||||
}
|
||||
if err := database.db.Raw("PRAGMA index_list('" + table + "')").Scan(&indexes).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
found := make(map[string]bool, len(indexes))
|
||||
for _, index := range indexes {
|
||||
found[index.Name] = true
|
||||
}
|
||||
for _, name := range expected {
|
||||
if !found[name] {
|
||||
t.Fatalf("table %s missing index %s: %#v", table, name, indexes)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func assertSQLiteMissingIndexes(t *testing.T, database *Database, table string, unexpected ...string) {
|
||||
t.Helper()
|
||||
var indexes []struct {
|
||||
Name string
|
||||
Unique int
|
||||
}
|
||||
if err := database.db.Raw("PRAGMA index_list('" + table + "')").Scan(&indexes).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
found := make(map[string]bool, len(indexes))
|
||||
for _, index := range indexes {
|
||||
found[index.Name] = true
|
||||
}
|
||||
for _, name := range unexpected {
|
||||
if found[name] {
|
||||
t.Fatalf("table %s still has index %s: %#v", table, name, indexes)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type legacyProviderAccountModel struct {
|
||||
ID uint64 `gorm:"primaryKey"`
|
||||
Provider string `gorm:"size:32;not null;check:chk_accounts_provider,provider IN ('grok_build','grok_web')"`
|
||||
|
||||
@@ -589,7 +589,7 @@ const resources = {
|
||||
},
|
||||
models: {
|
||||
title: "模型路由",
|
||||
description: "同一对外模型名称可映射到 Grok Build、Grok Web 与 Grok Console 的不同上游路由。",
|
||||
description: "同一对外模型名称可映射到 Grok Build、Grok Web 与 Grok Console 的不同上游路由;多个对外名称也可指向同一上游模型。",
|
||||
sync: "同步模型",
|
||||
search: "搜索对外模型名称或上游模型",
|
||||
model: "对外模型名称",
|
||||
@@ -1213,7 +1213,7 @@ const resources = {
|
||||
shell: { appearance: "Appearance", dark: "Dark", light: "Light", system: "System", language: "Language", navigation: "Navigation", openNavigation: "Open navigation" },
|
||||
dashboard: { title: "Dashboard", subtitle: "Welcome, {{name}}", lastUpdated: "Updated {{time}}", welcome: "Welcome, {{name}}", gatewayOnline: "Gateway healthy", gatewayOffline: "Unavailable", gatewayReady: "The gateway is ready to process API requests.", gatewayNeedsAccount: "Connect an available account to process API requests.", manageAccounts: "Manage accounts", usage: "Usage overview", seeAll: "View audits", activeAccounts: "Available accounts", accountCapacity: "{{total}} accounts · {{rate}}% success", manage: "Manage", tokens: "Total tokens", requests: "Requests", successRate: "Success rate", accountCount: "Accounts", accountDistribution: "Build {{build}} · Web {{web}} · Console {{console}}", requestSuccessRate: "{{rate}}% success", averageRequestCost: "{{cost}} per request", availableSummary: "{{active}} / {{total}} available", requestBreakdown: "{{success}} succeeded · {{failed}} failed", requestQualitySummary: "{{success}}% success · {{failed}} failed", periodSummary: "Current {{period}} range", successSummary: "{{success}} / {{total}} requests succeeded", trend: "Usage trend", trendRequests: "Requests", trendTokens: "Tokens", trendSummary: "{{requests}} requests · {{rate}}% success", resourcesTitle: "Resource availability", availability: "Account availability", unavailableAccounts: "Unavailable accounts", unavailableSummary: "{{unavailable}} / {{total}} unavailable", enabledModels: "Enabled models", modelsAvailableSummary: "{{enabled}} / {{total}} enabled", activeClientKeys: "Available keys", keysAvailableSummary: "{{active}} / {{total}} available", allTimeRequests: "All-time requests", allTimeRequestsSummary: "Since the first recorded request", qualityTitle: "Request quality", successfulRequests: "Successful requests", failedRequests: "Failed requests", topModels: "Top 10 model billing", model: "Model", share: "Call share", noTopModels: "No model calls in this period", noTrendData: "No usage data in this period", billing: "Billing", billingSummary: "Accumulated in the current {{period}} range", inputTokens: "Input", cachedTokens: "Cached", outputTokens: "Output", reasoningTokens: "Reasoning", uncachedInput: "Uncached input", visibleOutput: "Visible output", otherModels: "Other models", providerDistribution: "Provider distribution", providerDetail: "{{rate}}% success · {{tokens}} tokens", providerStripeDetail: "{{provider}} · {{requests}} requests · {{share}}%", providerNoRequests: "No provider requests", activityTitle: "Request activity", lastDays: "Last {{count}} days", activityDay: "{{date}} · {{requests}} requests", activityLess: "Less", activityMore: "More", tokenBreakdown: "Input {{input}} · Cached {{cached}} · Output {{output}} · Reasoning {{reasoning}}", tokenEfficiency: "Cache hit rate {{rate}}%", explore: "Manage resources", accountsProduct: "Upstream accounts", accountsProductDescription: "Manage OAuth credentials, health, quota, and concurrency.", keysProduct: "Client keys", keysProductDescription: "Create downstream API keys and control models, RPM, and concurrency.", modelsProduct: "Model routes", modelsProductDescription: "Manage public model IDs, upstream mappings, and availability.", auditsProduct: "Request audits", auditsProductDescription: "Inspect status, latency, and token usage records.", gatewayFooter: "A lightweight API gateway", learnMore: "View models", unknown: "Unknown" },
|
||||
accounts: { title: "Upstream accounts", description: "Manage separate Grok Build OAuth and Grok Web SSO pools, health, concurrency, and quotas.", add: "Connect account", connectAccount: "Connect account", convertToBuild: "Convert to Build", convertToBuildTitle: "Convert Grok Web accounts to Build?", convertToBuildDescription: "Choose the conversion scope for the selected {{count}} Web accounts. Conversion may take a moment.", convertingProgress: "Converting {{completed}} / {{total}}", syncingProgress: "Syncing {{completed}} / {{total}}", conversionCompleted: "Conversion complete: {{created}} created, {{linked}} linked, {{skipped}} skipped, {{failed}} failed", linkedAccountTooltip: "Linked account: {{name}}", syncAll: "Sync all", renewAll: "Renew all", syncAllTitle: "Sync all accounts?", syncAllDescription: "Refresh quota data for every enabled Grok Build account.", syncAllWebDescription: "Refresh real quota data for every enabled Grok Web account.", renewAllTitle: "Renew all accounts?", renewAllDescription: "Refresh every renewable Grok Build credential. Accounts without automatic renewal will be skipped.", search: "Search accounts", deviceLogin: "Device OAuth", importAuth: "Import account files", importSSO: "Import SSO JSON", quickImportSSO: "Quick import SSO", importWebFile: "Import account files", quickImportTitle: "Quick import Grok Web accounts", quickImportDescription: "Paste multiple SSO tokens or upload a TXT file with one token per line. Duplicate entries are ignored.", ssoTokens: "SSO tokens (one per line)", uploadTXT: "Upload TXT", ssoTokenPlaceholder: "sso_token_1\nsso_token_2\nsso=token_3", importAction: "Import", exportAuth: "Export account file", exported: "Account credentials exported", exportTitle: "Export {{provider}} accounts?", exportDescription: "The JSON contains credentials for the current provider and any configured Cloudflare cookies, and can be imported back into this project. Store it only in a trusted location.", refreshAllBilling: "Sync all quotas", account: "Account", status: "Status", type: "Type", quota: "Quota", routing: "Routing", credentialExpiry: "Credential expiry", credentialRenewal: "Renewal capability", autoRefresh: "Auto-renewal", noAutoRefresh: "No auto-renewal", buildAccountCount: "Grok Build accounts", webAccountCount: "Grok Web accounts", consoleAccountCount: "Grok Console accounts", abnormalAccountCount: "Abnormal accounts", routableAccountCount: "{{count}} routable", abnormalAccountBreakdown: "Recovering {{recovering}} · Needs attention {{attention}}", riskAccountCount: "Risk {{count}}", riskFilter: "Risk", riskNormal: "Normal", lastUsed: "Last used", createdAt: "Created at", name: "Name", priority: "Priority", maxConcurrent: "Max concurrency", minimumRemaining: "Minimum remaining threshold", routingSummary: "Priority {{priority}} · {{count}} concurrent", minimumRemainingSummary: "Minimum remaining {{value}}", minimumRemainingNotApplicable: "Minimum remaining does not apply to Free", refreshToken: "Refresh credential", refreshBilling: "Sync quota", refreshModeQuota: "Sync quota", quotaNotSynced: "Not synced", quotaResetAt: "Next reset {{time}}", quotaResetUnknown: "The upstream did not return a reset time", webQuotaUsage: "Used {{used}} / {{total}} total · {{remaining}} remaining", webModeQuotaRemaining: "{{mode}} has {{remaining}} calls remaining", webWeeklyQuotaUsage: "Weekly quota {{remaining}}% remaining", paidQuotaDetails: "{{remaining}} credits remaining", created: "Account connected", createdWithSyncFailure: "Account connected, but initial quota or model sync failed", updated: "Account updated", updatedWithModelSyncFailure: "Account updated, but model capability sync failed. Run model sync again later.", deleted: "Account deleted", imported: "Import complete: {{created}} created, {{updated}} updated", importedWithSyncFailures: "Import complete: {{created}} created, {{updated}} updated; {{synced}} synced, {{syncFailed}} failed initial sync", billingRefreshed: "Quota synced", authRefreshed: "Credential refreshed", allBillingRefreshed: "Sync complete: {{succeeded}} succeeded, {{failed}} failed", allTokensRefreshed: "Renewal complete: {{succeeded}} succeeded, {{failed}} failed, {{skipped}} skipped", statusDisabled: "Disabled", statusReauthRequired: "Invalid", statusCooldown: "Cooling", statusActive: "Normal", botRisk: "Risk", botRiskTooltip: "Bot risk control. This may affect video generation and other permissions.", nsfwEnabledMark: "NSFW", nsfwEnabledTooltip: "NSFW enabled · {{time}}", agreementFilter: "Account agreements", agreementNsfwEnabled: "NSFW enabled", agreementNsfwDisabled: "NSFW not enabled", agreementTermsAccepted: "Terms accepted", agreementTermsNotAccepted: "Terms not accepted", agreementAllAccepted: "All accepted", agreementAllNotAccepted: "All not accepted", associationFilter: "Account links", associationBuildLinked: "Build linked", associationBuildUnlinked: "Build not linked", associationConsoleLinked: "Console linked", associatLine truncated
|
||||
models: { title: "Model routes", description: "Map one client-facing model name to provider-specific Build, Web, and Console routes.", sync: "Sync models", search: "Search models", model: "Public model name", publicId: "Public model name", upstream: "Upstream model", provider: "Model source", providerGrokBuild: "Grok Build", providerGrokWeb: "Grok Web", accountSupport: "Supported accounts", lastSyncedAt: "Last synced", capability: "Account model capabilities", supportSummary: "{{supported}} available / {{total}} total", awaitingCapabilitySync: "Awaiting model capability sync", unknownCapability: "Pending sync", partialCapability: "Awaiting remaining accounts", available: "Available", unavailable: "Unavailable", status: "Status", create: "Add model", createTitle: "Add model route", createDescription: "Add a custom Grok Build route. The public model name has no source prefix; the upstream model uses Build/ to identify its actual channel.", editTitle: "Edit model route", bindAccounts: "Bind specific accounts", boundAccounts: "Bound accounts", bindAccountsDescription: "Route only through selected accounts; when disabled, use synchronized model capabilities.", enabledDescription: "Controls whether this route participates in model discovery and request scheduling.", searchAccounts: "Search account name or ID", selectedAccounts: "{{count}} accounts selected", selectAccountRequired: "Select at least one account", noBindableAccounts: "No accounts from this provider can be bound", deleteTitle: "Delete model route?", deleteDescription: "This removes {{name}} and its client-key permissions. A later sync recreates it if upstream accounts still support the model.", batchDeleteTitle: "Delete {{count}} selected model routes?", batchDeleteDescription: "This removes the selected routes and their client-key permissions. Models still supported by upstream accounts are recreated on a later sync.", synced: "Synced {{count}} models", created: "Model route created", updated: "Model route updated", deleted: "Model route deleted", batchDeleted: "Deleted {{count}} model routes", batchUpdated: "Selected models updated" },
|
||||
models: { title: "Model routes", description: "Map one client-facing model name to provider-specific Build, Web, and Console routes. Multiple public names may also target the same upstream model.", sync: "Sync models", search: "Search models", model: "Public model name", publicId: "Public model name", upstream: "Upstream model", provider: "Model source", providerGrokBuild: "Grok Build", providerGrokWeb: "Grok Web", accountSupport: "Supported accounts", lastSyncedAt: "Last synced", capability: "Account model capabilities", supportSummary: "{{supported}} available / {{total}} total", awaitingCapabilitySync: "Awaiting model capability sync", unknownCapability: "Pending sync", partialCapability: "Awaiting remaining accounts", available: "Available", unavailable: "Unavailable", status: "Status", create: "Add model", createTitle: "Add model route", createDescription: "Add a custom Grok Build route. The public model name has no source prefix; the upstream model uses Build/ to identify its actual channel.", editTitle: "Edit model route", bindAccounts: "Bind specific accounts", boundAccounts: "Bound accounts", bindAccountsDescription: "Route only through selected accounts; when disabled, use synchronized model capabilities.", enabledDescription: "Controls whether this route participates in model discovery and request scheduling.", searchAccounts: "Search account name or ID", selectedAccounts: "{{count}} accounts selected", selectAccountRequired: "Select at least one account", noBindableAccounts: "No accounts from this provider can be bound", deleteTitle: "Delete model route?", deleteDescription: "This removes {{name}} and its client-key permissions. A later sync recreates it if upstream accounts still support the model.", batchDeleteTitle: "Delete {{count}} selected model routes?", batchDeleteDescription: "This removes the selected routes and their client-key permissions. Models still supported by upstream accounts are recreated on a later sync.", synced: "Synced {{count}} models", created: "Model route created", updated: "Model route updated", deleted: "Model route deleted", batchDeleted: "Deleted {{count}} model routes", batchUpdated: "Selected models updated" },
|
||||
keys: { title: "Client keys", description: "Control downstream model access, RPM, concurrency, billed usage, and expiration.", search: "Search keys", create: "Create key", name: "Name", prefix: "Key", limits: "Limits", rpmLimit: "RPM limit", concurrencyLimit: "Concurrency limit", rpmShort: "RPM", concurrencyShort: "Concurrency", billingLimit: "Usage limit", models: "Allowed models", status: "Status", statusActive: "Active", statusExpired: "Expired", modelScope: "Model scope", restrictedModels: "Selected models", expires: "Expires", lastUsed: "Last used", rpm: "Requests per minute", maxConcurrent: "Max concurrency", rpmValue: "{{value}} RPM", concurrentValue: "{{value}} concurrent", unlimited: "Unlimited", billedUsage: "{{value}} billed", billingLimitDescription: "Accumulates billed request audits, preferring upstream-reported cost and otherwise using the official price estimate.", enabledDescription: "Controls whether this key can make API requests.", allModels: "All models", modelSearch: "Search models. Leave blank to allow all models.", selectedModels: "{{count}} models selected", neverExpires: "Never expires", selectExpiry: "Select expiration date", clearExpiry: "Clear expiration", expiryTime: "Expiration time", createTitle: "Create client key", editTitle: "Edit client key", secretTitle: "Client key created", secretDescription: "Store this key securely.", secretLabel: "Key", copySecret: "Copy", copySecretTitle: "Copy key", copySecretDescription: "Use the button below to copy your key.", secretReady: "Ready", created: "Client key created", updated: "Client key updated", deleted: "Client key deleted", deleteTitle: "Delete client key?", deleteDescription: "All downstream requests using this key will stop immediately.", batchUpdated: "Selected keys updated", batchDeleteTitle: "Delete {{count}} selected keys?" },
|
||||
audits: {
|
||||
title: "Request audits",
|
||||
|
||||
Reference in new issue
Block a user