mirror of
https://github.com/chenyme/grok2api.git
synced 2026-12-06 08:02:14 +00:00
Merge pull request #717 from chenyme/key
feat: implement unlimited RPM and concurrency options for client keys and enhance related tests
This commit is contained in:
11 files changed
+433
-89
No files matched your search
@@ -33,7 +33,9 @@ type CreateInput struct {
|
||||
Enabled bool
|
||||
ExpiresAt *time.Time
|
||||
RPMLimit int
|
||||
RPMUnlimited bool
|
||||
MaxConcurrent int
|
||||
ConcurrencyUnlimited bool
|
||||
BillingLimitUSDTicks int64
|
||||
AllowedModels []uint64
|
||||
}
|
||||
@@ -139,14 +141,18 @@ func (s *Service) Create(ctx context.Context, input CreateInput) (Created, error
|
||||
if err != nil {
|
||||
return Created{}, fmt.Errorf("加密客户端 Key: %w", err)
|
||||
}
|
||||
if input.RPMLimit == 0 {
|
||||
if input.RPMUnlimited {
|
||||
input.RPMLimit = 0
|
||||
} else if input.RPMLimit == 0 {
|
||||
input.RPMLimit = int(s.defaultRPM.Load())
|
||||
}
|
||||
if input.MaxConcurrent == 0 {
|
||||
if input.ConcurrencyUnlimited {
|
||||
input.MaxConcurrent = 0
|
||||
} else if input.MaxConcurrent == 0 {
|
||||
input.MaxConcurrent = int(s.defaultMax.Load())
|
||||
}
|
||||
if input.RPMLimit < 1 || input.MaxConcurrent < 1 {
|
||||
return Created{}, invalidInput("RPM 和最大并发必须大于零")
|
||||
if input.RPMLimit < 0 || input.MaxConcurrent < 0 {
|
||||
return Created{}, invalidInput("RPM 和最大并发不能小于零")
|
||||
}
|
||||
value, err := s.keys.Create(ctx, clientkeydomain.Key{Name: strings.TrimSpace(input.Name), Prefix: prefix, SecretHash: security.HashToken(raw), EncryptedSecret: encryptedSecret, Enabled: input.Enabled, ExpiresAt: input.ExpiresAt, RPMLimit: input.RPMLimit, MaxConcurrent: input.MaxConcurrent, BillingLimitUSDTicks: input.BillingLimitUSDTicks, AllowedModels: input.AllowedModels})
|
||||
return Created{Key: value, Secret: raw}, mapRepositoryError(err)
|
||||
@@ -192,14 +198,14 @@ func (s *Service) Update(ctx context.Context, id uint64, input UpdateInput) (cli
|
||||
value.ExpiresAt = input.ExpiresAt
|
||||
}
|
||||
if input.RPMLimit != nil {
|
||||
if *input.RPMLimit < 1 || *input.RPMLimit > clientkeydomain.MaxRPMLimit {
|
||||
return clientkeydomain.Key{}, invalidInput("rpmLimit 必须在 1 到 100000 之间")
|
||||
if *input.RPMLimit < 0 || *input.RPMLimit > clientkeydomain.MaxRPMLimit {
|
||||
return clientkeydomain.Key{}, invalidInput("rpmLimit 必须在 0 到 100000 之间")
|
||||
}
|
||||
value.RPMLimit = *input.RPMLimit
|
||||
}
|
||||
if input.MaxConcurrent != nil {
|
||||
if *input.MaxConcurrent < 1 || *input.MaxConcurrent > clientkeydomain.MaxConcurrent {
|
||||
return clientkeydomain.Key{}, invalidInput("maxConcurrent 必须在 1 到 1024 之间")
|
||||
if *input.MaxConcurrent < 0 || *input.MaxConcurrent > clientkeydomain.MaxConcurrent {
|
||||
return clientkeydomain.Key{}, invalidInput("maxConcurrent 必须在 0 到 1024 之间")
|
||||
}
|
||||
value.MaxConcurrent = *input.MaxConcurrent
|
||||
}
|
||||
@@ -288,19 +294,26 @@ func (s *Service) Authenticate(ctx context.Context, raw string) (clientkeydomain
|
||||
return clientkeydomain.Key{}, nil, ErrBillingLimit
|
||||
}
|
||||
}
|
||||
allowed, err := s.rateLimiter.Allow(ctx, fmt.Sprintf("client:%d", value.ID), value.RPMLimit, now)
|
||||
if err != nil {
|
||||
return clientkeydomain.Key{}, nil, fmt.Errorf("%w: RPM 限流器: %v", ErrRuntimeUnavailable, err)
|
||||
if value.RPMLimit > 0 {
|
||||
allowed, err := s.rateLimiter.Allow(ctx, fmt.Sprintf("client:%d", value.ID), value.RPMLimit, now)
|
||||
if err != nil {
|
||||
return clientkeydomain.Key{}, nil, fmt.Errorf("%w: RPM 限流器: %v", ErrRuntimeUnavailable, err)
|
||||
}
|
||||
if !allowed {
|
||||
return clientkeydomain.Key{}, nil, ErrRateLimited
|
||||
}
|
||||
}
|
||||
if !allowed {
|
||||
return clientkeydomain.Key{}, nil, ErrRateLimited
|
||||
}
|
||||
release, acquired, err := s.concurrency.Acquire(ctx, fmt.Sprintf("client:%d", value.ID), value.MaxConcurrent)
|
||||
if err != nil {
|
||||
return clientkeydomain.Key{}, nil, fmt.Errorf("%w: 并发租约: %v", ErrRuntimeUnavailable, err)
|
||||
}
|
||||
if !acquired {
|
||||
return clientkeydomain.Key{}, nil, ErrConcurrencyLimit
|
||||
release := func() {}
|
||||
if value.MaxConcurrent > 0 {
|
||||
var acquired bool
|
||||
var err error
|
||||
release, acquired, err = s.concurrency.Acquire(ctx, fmt.Sprintf("client:%d", value.ID), value.MaxConcurrent)
|
||||
if err != nil {
|
||||
return clientkeydomain.Key{}, nil, fmt.Errorf("%w: 并发租约: %v", ErrRuntimeUnavailable, err)
|
||||
}
|
||||
if !acquired {
|
||||
return clientkeydomain.Key{}, nil, ErrConcurrencyLimit
|
||||
}
|
||||
}
|
||||
if s.touches.shouldTouch(value.ID, now) {
|
||||
_ = s.keys.Touch(ctx, value.ID)
|
||||
|
||||
@@ -48,8 +48,9 @@ func TestCreateUsesG2AClientKeyFormat(t *testing.T) {
|
||||
t.Fatalf("negative rpm error = %v", err)
|
||||
}
|
||||
zero := 0
|
||||
if _, err := service.Update(ctx, created.Key.ID, UpdateInput{MaxConcurrent: &zero}); !errors.Is(err, ErrInvalidInput) {
|
||||
t.Fatalf("zero concurrency error = %v", err)
|
||||
updated, err := service.Update(ctx, created.Key.ID, UpdateInput{MaxConcurrent: &zero})
|
||||
if err != nil || updated.MaxConcurrent != 0 {
|
||||
t.Fatalf("zero concurrency update = %#v, err = %v", updated, err)
|
||||
}
|
||||
revealed, err := service.RevealSecret(ctx, created.Key.ID)
|
||||
if err != nil || revealed != created.Secret {
|
||||
@@ -57,6 +58,38 @@ func TestCreateUsesG2AClientKeyFormat(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnlimitedRuntimeLimitsBypassLimiterStores(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "unlimited-runtime.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repo := relational.NewClientKeyRepository(database)
|
||||
service := NewService(repo, failingRateLimiter{}, failingConcurrencyLimiter{}, 60, 5, testCipher(t))
|
||||
created, err := service.Create(ctx, CreateInput{
|
||||
Name: "unlimited", Enabled: true,
|
||||
RPMUnlimited: true, ConcurrencyUnlimited: true,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if created.Key.RPMLimit != 0 || created.Key.MaxConcurrent != 0 {
|
||||
t.Fatalf("persisted limits = rpm %d, concurrency %d", created.Key.RPMLimit, created.Key.MaxConcurrent)
|
||||
}
|
||||
value, release, err := service.Authenticate(ctx, created.Secret)
|
||||
if err != nil {
|
||||
t.Fatalf("authenticate unlimited key: %v", err)
|
||||
}
|
||||
if value.ID != created.Key.ID {
|
||||
t.Fatalf("authenticated key = %d, want %d", value.ID, created.Key.ID)
|
||||
}
|
||||
release()
|
||||
}
|
||||
|
||||
func TestAuthenticateDistinguishesRuntimeStoreFailures(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "runtime-errors.db"))
|
||||
|
||||
@@ -84,6 +84,22 @@ func (r *ClientKeyRepository) Create(ctx context.Context, value clientkey.Key) (
|
||||
if err := tx.Create(&row).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
// GORM 会把带 default tag 的零值替换为数据库默认值;这里显式写回 0,
|
||||
// 使其稳定表示该维度无限制。
|
||||
unlimited := make(map[string]any, 2)
|
||||
if value.RPMLimit == 0 {
|
||||
unlimited["rpm_limit"] = 0
|
||||
row.RPMLimit = 0
|
||||
}
|
||||
if value.MaxConcurrent == 0 {
|
||||
unlimited["max_concurrent"] = 0
|
||||
row.MaxConcurrent = 0
|
||||
}
|
||||
if len(unlimited) > 0 {
|
||||
if err := tx.Model(&row).Updates(unlimited).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return replacePermissions(tx, row.ID, value.AllowedModels)
|
||||
})
|
||||
if err != nil {
|
||||
|
||||
@@ -238,8 +238,8 @@ type clientKeyModel struct {
|
||||
EncryptedSecret string `gorm:"type:text;not null;check:chk_client_keys_encrypted_secret,length(trim(encrypted_secret)) BETWEEN 1 AND 4096"`
|
||||
Enabled bool `gorm:"not null"`
|
||||
ExpiresAt *time.Time
|
||||
RPMLimit int `gorm:"not null;default:120;check:chk_client_keys_rpm,rpm_limit BETWEEN 1 AND 100000"`
|
||||
MaxConcurrent int `gorm:"not null;default:8;check:chk_client_keys_max_concurrent,max_concurrent BETWEEN 1 AND 1024"`
|
||||
RPMLimit int `gorm:"not null;default:120;check:chk_client_keys_rpm,rpm_limit BETWEEN 0 AND 100000"`
|
||||
MaxConcurrent int `gorm:"not null;default:8;check:chk_client_keys_max_concurrent,max_concurrent BETWEEN 0 AND 1024"`
|
||||
BillingLimitUSDTicks int64 `gorm:"not null;default:0;check:chk_client_keys_billing_limit,billing_limit_usd_ticks BETWEEN 0 AND 9000000000000000"`
|
||||
BilledUsageUSDTicks int64 `gorm:"not null;default:0;check:chk_client_keys_billed_usage,billed_usage_usd_ticks >= 0"`
|
||||
ReservedUsageUSDTicks int64 `gorm:"not null;default:0;check:chk_client_keys_reserved_usage,reserved_usage_usd_ticks >= 0"`
|
||||
|
||||
@@ -117,6 +117,9 @@ func (d *Database) InitializeSchema(ctx context.Context) error {
|
||||
if err := d.ensureMediaAssetConstraints(ctx); err != nil {
|
||||
return fmt.Errorf("迁移 media asset 数据库约束: %w", err)
|
||||
}
|
||||
if err := d.ensureClientKeyLimitConstraints(ctx); err != nil {
|
||||
return fmt.Errorf("迁移客户端 Key 限额约束: %w", err)
|
||||
}
|
||||
if err := d.backfillWebEgressIdentities(ctx); err != nil {
|
||||
return fmt.Errorf("迁移 Web 出口身份: %w", err)
|
||||
}
|
||||
@@ -219,6 +222,45 @@ func (d *Database) ensureMediaAssetConstraints(ctx context.Context) error {
|
||||
}, "268435456")
|
||||
}
|
||||
|
||||
// ensureClientKeyLimitConstraints 将历史正数限制升级为允许 0 表示无限制。
|
||||
// PostgreSQL 不会由 AutoMigrate 可靠替换同名 CHECK,因此需显式检测并重建。
|
||||
func (d *Database) ensureClientKeyLimitConstraints(ctx context.Context) error {
|
||||
constraints := []consoleConstraint{
|
||||
{model: &clientKeyModel{}, table: "client_keys", name: "chk_client_keys_rpm"},
|
||||
{model: &clientKeyModel{}, table: "client_keys", name: "chk_client_keys_max_concurrent"},
|
||||
}
|
||||
migrate := func() error {
|
||||
db := d.db.WithContext(ctx)
|
||||
for _, value := range constraints {
|
||||
definition, err := d.constraintDefinition(ctx, value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if clientKeyLimitConstraintAllowsZero(definition) {
|
||||
continue
|
||||
}
|
||||
if definition != "" {
|
||||
if err := db.Migrator().DropConstraint(value.model, value.name); err != nil {
|
||||
return fmt.Errorf("删除旧约束 %s: %w", value.name, err)
|
||||
}
|
||||
}
|
||||
if err := db.Migrator().CreateConstraint(value.model, value.name); err != nil {
|
||||
return fmt.Errorf("创建约束 %s: %w", value.name, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if d.dialect == "sqlite" {
|
||||
return d.withSQLiteForeignKeysDisabled(ctx, migrate)
|
||||
}
|
||||
return migrate()
|
||||
}
|
||||
|
||||
func clientKeyLimitConstraintAllowsZero(definition string) bool {
|
||||
normalized := strings.NewReplacer(" ", "", "\n", "", "\t", "", "\"", "", "`", "", "(", "", ")", "").Replace(strings.ToLower(definition))
|
||||
return strings.Contains(normalized, "between0and") || strings.Contains(normalized, ">=0")
|
||||
}
|
||||
|
||||
// ensureNamedConstraints 在约束定义尚未包含 marker 时 drop/recreate;已升级则跳过。
|
||||
func (d *Database) ensureNamedConstraints(ctx context.Context, constraints []consoleConstraint, marker string) error {
|
||||
migrate := func() error {
|
||||
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
package relational
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestInitializeSchemaUpgradesClientKeyLimitsToAllowZero(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := OpenSQLite(ctx, filepath.Join(t.TempDir(), "legacy-client-key-limits.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
db := database.db.WithContext(ctx)
|
||||
now := time.Now().UTC()
|
||||
legacy := clientKeyModel{
|
||||
Name: "legacy", Prefix: "legacy-prefix", SecretHash: testSecretHash,
|
||||
EncryptedSecret: testEncryptedToken, Enabled: true, RPMLimit: 120, MaxConcurrent: 8,
|
||||
CreatedAt: now, UpdatedAt: now,
|
||||
}
|
||||
if err := db.Create(&legacy).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := recreatePositiveOnlyClientKeyLimits(ctx, database); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Exec("UPDATE client_keys SET rpm_limit = 0 WHERE prefix = ?", "legacy-prefix").Error; err == nil {
|
||||
t.Fatal("legacy RPM constraint unexpectedly accepted zero")
|
||||
}
|
||||
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Exec("UPDATE client_keys SET rpm_limit = 0, max_concurrent = 0 WHERE prefix = ?", "legacy-prefix").Error; err != nil {
|
||||
t.Fatalf("upgraded constraints rejected zero: %v", err)
|
||||
}
|
||||
var stored clientKeyModel
|
||||
if err := db.Where("prefix = ?", "legacy-prefix").First(&stored).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if stored.Name != "legacy" || stored.RPMLimit != 0 || stored.MaxConcurrent != 0 {
|
||||
t.Fatalf("stored key after upgrade = %#v", stored)
|
||||
}
|
||||
if err := db.Exec("UPDATE client_keys SET rpm_limit = -1 WHERE prefix = ?", "legacy-prefix").Error; err == nil {
|
||||
t.Fatal("upgraded RPM constraint accepted a negative value")
|
||||
}
|
||||
if err := db.Exec("UPDATE client_keys SET max_concurrent = 1025 WHERE prefix = ?", "legacy-prefix").Error; err == nil {
|
||||
t.Fatal("upgraded concurrency constraint accepted an oversized value")
|
||||
}
|
||||
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatalf("repeated schema initialization: %v", err)
|
||||
}
|
||||
if err := db.Where("prefix = ?", "legacy-prefix").First(&stored).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if stored.RPMLimit != 0 || stored.MaxConcurrent != 0 {
|
||||
t.Fatalf("limits after repeated initialization = rpm %d, concurrency %d", stored.RPMLimit, stored.MaxConcurrent)
|
||||
}
|
||||
}
|
||||
|
||||
func recreatePositiveOnlyClientKeyLimits(ctx context.Context, database *Database) error {
|
||||
return database.withSQLiteForeignKeysDisabled(ctx, func() error {
|
||||
db := database.db.WithContext(ctx)
|
||||
var tableSQL string
|
||||
if err := db.Raw("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'client_keys'").Scan(&tableSQL).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
legacySQL := strings.Replace(tableSQL, "rpm_limit BETWEEN 0 AND 100000", "rpm_limit BETWEEN 1 AND 100000", 1)
|
||||
legacySQL = strings.Replace(legacySQL, "max_concurrent BETWEEN 0 AND 1024", "max_concurrent BETWEEN 1 AND 1024", 1)
|
||||
if legacySQL == tableSQL {
|
||||
return nil
|
||||
}
|
||||
legacySQL = strings.Replace(legacySQL, "client_keys", "client_keys_legacy", 1)
|
||||
if err := db.Exec(legacySQL).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := db.Exec("INSERT INTO client_keys_legacy SELECT * FROM client_keys").Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := db.Exec("DROP TABLE client_keys").Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return db.Exec("ALTER TABLE client_keys_legacy RENAME TO client_keys").Error
|
||||
})
|
||||
}
|
||||
|
||||
func TestClientKeyLimitConstraintAllowsZero(t *testing.T) {
|
||||
for _, definition := range []string{
|
||||
"CHECK (rpm_limit BETWEEN 0 AND 100000)",
|
||||
`CHECK ((("max_concurrent" >= 0) AND ("max_concurrent" <= 1024)))`,
|
||||
} {
|
||||
if !clientKeyLimitConstraintAllowsZero(definition) {
|
||||
t.Fatalf("constraint should allow zero: %s", definition)
|
||||
}
|
||||
}
|
||||
if clientKeyLimitConstraintAllowsZero("CHECK (rpm_limit BETWEEN 1 AND 100000)") {
|
||||
t.Fatal("legacy positive-only constraint was treated as upgraded")
|
||||
}
|
||||
}
|
||||
@@ -32,8 +32,8 @@ type createRequest struct {
|
||||
Name string `json:"name" binding:"required"`
|
||||
Enabled *bool `json:"enabled"`
|
||||
ExpiresAt string `json:"expiresAt"`
|
||||
RPMLimit int `json:"rpmLimit"`
|
||||
MaxConcurrent int `json:"maxConcurrent"`
|
||||
RPMLimit *int `json:"rpmLimit"`
|
||||
MaxConcurrent *int `json:"maxConcurrent"`
|
||||
BillingLimitUSDTicks int64 `json:"billingLimitUsdTicks"`
|
||||
AllowedModelIDs []string `json:"allowedModelIds"`
|
||||
}
|
||||
@@ -147,7 +147,16 @@ func (h *Handler) create(c *gin.Context) {
|
||||
if request.Enabled != nil {
|
||||
enabled = *request.Enabled
|
||||
}
|
||||
created, err := h.service.Create(c.Request.Context(), clientkeyapp.CreateInput{Name: request.Name, Enabled: enabled, ExpiresAt: expiresAt, RPMLimit: request.RPMLimit, MaxConcurrent: request.MaxConcurrent, BillingLimitUSDTicks: request.BillingLimitUSDTicks, AllowedModels: modelIDs})
|
||||
input := clientkeyapp.CreateInput{Name: request.Name, Enabled: enabled, ExpiresAt: expiresAt, BillingLimitUSDTicks: request.BillingLimitUSDTicks, AllowedModels: modelIDs}
|
||||
if request.RPMLimit != nil {
|
||||
input.RPMLimit = *request.RPMLimit
|
||||
input.RPMUnlimited = *request.RPMLimit == 0
|
||||
}
|
||||
if request.MaxConcurrent != nil {
|
||||
input.MaxConcurrent = *request.MaxConcurrent
|
||||
input.ConcurrencyUnlimited = *request.MaxConcurrent == 0
|
||||
}
|
||||
created, err := h.service.Create(c.Request.Context(), input)
|
||||
if err != nil {
|
||||
h.writeServiceError(c, "clientKeyCreateFailed", err)
|
||||
return
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
package clientkey
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
clientkeyapp "github.com/chenyme/grok2api/backend/internal/application/clientkey"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/persistence/relational"
|
||||
"github.com/chenyme/grok2api/backend/internal/infra/security"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func TestCreateDistinguishesOmittedLimitsFromExplicitZero(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
ctx := context.Background()
|
||||
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "client-key-handler.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service := clientkeyapp.NewService(relational.NewClientKeyRepository(database), nil, nil, 60, 5, cipher)
|
||||
router := gin.New()
|
||||
NewHandler(service).Register(router.Group("/api"))
|
||||
|
||||
assertCreate := func(body string) {
|
||||
t.Helper()
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/client-keys", bytes.NewBufferString(body))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
response := httptest.NewRecorder()
|
||||
router.ServeHTTP(response, request)
|
||||
if response.Code != http.StatusCreated {
|
||||
t.Fatalf("create response = %d %s", response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
assertCreate(`{"name":"defaults"}`)
|
||||
assertCreate(`{"name":"unlimited","rpmLimit":0,"maxConcurrent":0}`)
|
||||
|
||||
defaults, total, err := service.List(ctx, 1, 20, "defaults", clientkeyapp.ListFilter{})
|
||||
if err != nil || total != 1 || len(defaults) != 1 {
|
||||
t.Fatalf("default key list = %#v, total = %d, err = %v", defaults, total, err)
|
||||
}
|
||||
if defaults[0].RPMLimit != 60 || defaults[0].MaxConcurrent != 5 {
|
||||
t.Fatalf("omitted limits = rpm %d, concurrency %d", defaults[0].RPMLimit, defaults[0].MaxConcurrent)
|
||||
}
|
||||
unlimited, total, err := service.List(ctx, 1, 20, "unlimited", clientkeyapp.ListFilter{})
|
||||
if err != nil || total != 1 || len(unlimited) != 1 {
|
||||
t.Fatalf("unlimited key list = %#v, total = %d, err = %v", unlimited, total, err)
|
||||
}
|
||||
if unlimited[0].RPMLimit != 0 || unlimited[0].MaxConcurrent != 0 {
|
||||
t.Fatalf("explicit zero limits = rpm %d, concurrency %d", unlimited[0].RPMLimit, unlimited[0].MaxConcurrent)
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { ChevronLeft, ChevronRight, Copy, MoreHorizontal, Pencil, Plus, Search, Trash2 } from "lucide-react";
|
||||
import { ChevronLeft, ChevronRight, CircleHelp, Copy, MoreHorizontal, Pencil, Plus, Search, Trash2 } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { Controller, useForm, useWatch } from "react-hook-form";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -31,6 +31,7 @@ import { Pagination } from "@/shared/components/pagination";
|
||||
import { SortableTableHead } from "@/shared/components/sortable-table-head";
|
||||
import { VirtualTableBody } from "@/shared/components/virtual-table-body";
|
||||
import { useDebouncedValue } from "@/shared/hooks/use-debounced-value";
|
||||
import { cn } from "@/shared/lib/cn";
|
||||
import { formatDateTime, toDateTimeLocal } from "@/shared/lib/format";
|
||||
import { nextTableSort, type SortOrder, type TableSort } from "@/shared/lib/table-sort";
|
||||
|
||||
@@ -64,20 +65,30 @@ export function ClientKeysPage() {
|
||||
const schema = z.object({
|
||||
name: z.string().min(1, t("errors.required")),
|
||||
enabled: z.boolean(),
|
||||
expiryUnlimited: z.boolean(),
|
||||
expiresAt: z.string(),
|
||||
rpmUnlimited: z.boolean(),
|
||||
rpmLimit: z.number().int().min(1, t("errors.positive")).max(100_000),
|
||||
concurrencyUnlimited: z.boolean(),
|
||||
maxConcurrent: z.number().int().min(1, t("errors.positive")).max(1_024),
|
||||
billingUnlimited: z.boolean(),
|
||||
billingLimitUsd: z.number().min(0.01, t("errors.positive")).max(MAX_BILLING_LIMIT_USD),
|
||||
allowedModelIds: z.array(z.string()),
|
||||
}).superRefine((value, context) => {
|
||||
if (!value.expiryUnlimited && !value.expiresAt) {
|
||||
context.addIssue({ code: "custom", path: ["expiresAt"], message: t("errors.required") });
|
||||
}
|
||||
});
|
||||
type KeyForm = z.infer<typeof schema>;
|
||||
const form = useForm<KeyForm>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: { name: "", enabled: true, expiresAt: "", rpmLimit: 120, maxConcurrent: 8, billingUnlimited: true, billingLimitUsd: 10, allowedModelIds: [] },
|
||||
defaultValues: { name: "", enabled: true, expiryUnlimited: true, expiresAt: "", rpmUnlimited: false, rpmLimit: 120, concurrencyUnlimited: false, maxConcurrent: 8, billingUnlimited: true, billingLimitUsd: 10, allowedModelIds: [] },
|
||||
});
|
||||
const keyEnabled = useWatch({ control: form.control, name: "enabled" });
|
||||
const selectedModels = useWatch({ control: form.control, name: "allowedModelIds" });
|
||||
const expiryUnlimited = useWatch({ control: form.control, name: "expiryUnlimited" });
|
||||
const rpmUnlimited = useWatch({ control: form.control, name: "rpmUnlimited" });
|
||||
const concurrencyUnlimited = useWatch({ control: form.control, name: "concurrencyUnlimited" });
|
||||
const billingUnlimited = useWatch({ control: form.control, name: "billingUnlimited" });
|
||||
|
||||
const keysQuery = useQuery({
|
||||
@@ -95,11 +106,11 @@ export function ClientKeysPage() {
|
||||
const body = {
|
||||
name: values.name,
|
||||
enabled: values.enabled,
|
||||
rpmLimit: values.rpmLimit,
|
||||
maxConcurrent: values.maxConcurrent,
|
||||
rpmLimit: values.rpmUnlimited ? 0 : values.rpmLimit,
|
||||
maxConcurrent: values.concurrencyUnlimited ? 0 : values.maxConcurrent,
|
||||
billingLimitUsdTicks: values.billingUnlimited ? 0 : Math.round(values.billingLimitUsd * USD_TICKS),
|
||||
allowedModelIds: values.allowedModelIds,
|
||||
expiresAt: values.expiresAt ? new Date(values.expiresAt).toISOString() : "",
|
||||
expiresAt: values.expiryUnlimited ? "" : new Date(values.expiresAt).toISOString(),
|
||||
};
|
||||
if (editing === "new") {
|
||||
return createClientKey(body);
|
||||
@@ -165,7 +176,7 @@ export function ClientKeysPage() {
|
||||
setEditing("new");
|
||||
setModelOptionsPage(1);
|
||||
setModelOptionsSearch("");
|
||||
form.reset({ name: "", enabled: true, expiresAt: "", rpmLimit: 120, maxConcurrent: 8, billingUnlimited: true, billingLimitUsd: 10, allowedModelIds: [] });
|
||||
form.reset({ name: "", enabled: true, expiryUnlimited: true, expiresAt: "", rpmUnlimited: false, rpmLimit: 120, concurrencyUnlimited: false, maxConcurrent: 8, billingUnlimited: true, billingLimitUsd: 10, allowedModelIds: [] });
|
||||
}
|
||||
|
||||
function beginEdit(key: ClientKeyDTO): void {
|
||||
@@ -175,9 +186,12 @@ export function ClientKeysPage() {
|
||||
form.reset({
|
||||
name: key.name,
|
||||
enabled: key.enabled,
|
||||
expiryUnlimited: !key.expiresAt,
|
||||
expiresAt: toDateTimeLocal(key.expiresAt),
|
||||
rpmLimit: key.rpmLimit,
|
||||
maxConcurrent: key.maxConcurrent,
|
||||
rpmUnlimited: key.rpmLimit === 0,
|
||||
rpmLimit: key.rpmLimit > 0 ? key.rpmLimit : 120,
|
||||
concurrencyUnlimited: key.maxConcurrent === 0,
|
||||
maxConcurrent: key.maxConcurrent > 0 ? key.maxConcurrent : 8,
|
||||
billingUnlimited: key.billingLimitUsdTicks === 0,
|
||||
billingLimitUsd: key.billingLimitUsdTicks > 0 ? key.billingLimitUsdTicks / USD_TICKS : 10,
|
||||
allowedModelIds: key.allowedModelIds,
|
||||
@@ -313,8 +327,8 @@ export function ClientKeysPage() {
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="text-center"><ClientKeyStatus value={key} referenceTime={statusReferenceTime} /></TableCell>
|
||||
<TableCell className="text-center text-xs tabular-nums">{key.rpmLimit}</TableCell>
|
||||
<TableCell className="text-center text-xs tabular-nums">{key.maxConcurrent}</TableCell>
|
||||
<TableCell className="text-center text-xs tabular-nums">{key.rpmLimit > 0 ? key.rpmLimit : t("keys.unlimited")}</TableCell>
|
||||
<TableCell className="text-center text-xs tabular-nums">{key.maxConcurrent > 0 ? key.maxConcurrent : t("keys.unlimited")}</TableCell>
|
||||
<TableCell><BillingUsage value={key} /></TableCell>
|
||||
<TableCell className="overflow-hidden text-ellipsis whitespace-nowrap text-xs text-muted-foreground" title={key.expiresAt ? formatDateTime(key.expiresAt, i18n.language) : t("keys.neverExpires")}>{key.expiresAt ? formatDateTime(key.expiresAt, i18n.language) : t("keys.neverExpires")}</TableCell>
|
||||
<TableCell className="overflow-hidden text-ellipsis whitespace-nowrap text-xs text-muted-foreground" title={formatDateTime(key.lastUsedAt, i18n.language)}>{formatDateTime(key.lastUsedAt, i18n.language)}</TableCell>
|
||||
@@ -336,57 +350,95 @@ export function ClientKeysPage() {
|
||||
</DataTableShell>
|
||||
|
||||
<Dialog open={editing !== null} onOpenChange={(open) => !open && setEditing(null)}>
|
||||
<DialogContent className="flex max-h-[calc(100svh-2rem)] min-h-0 flex-col gap-0 overflow-hidden p-0 sm:max-w-[520px]">
|
||||
<DialogHeader className="shrink-0 border-b px-5 py-4 pr-12">
|
||||
<DialogContent className="flex max-h-[calc(100svh-2rem)] min-h-0 flex-col gap-0 overflow-hidden p-0 text-xs sm:max-w-[560px]">
|
||||
<DialogHeader className="shrink-0 px-5 py-4 pr-12">
|
||||
<DialogTitle>{editing === "new" ? t("keys.createTitle") : t("keys.editTitle")}</DialogTitle>
|
||||
<DialogDescription>{editing === "new" ? t("keys.description") : editing?.prefix}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<form className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden" onSubmit={form.handleSubmit((values) => saveMutation.mutate(values))}>
|
||||
<div className="min-h-0 min-w-0 flex-1 space-y-4 overflow-y-auto overscroll-contain px-5 py-4">
|
||||
<div className="min-h-0 min-w-0 flex-1 space-y-3 overflow-y-auto overscroll-contain px-5 pb-4 pt-2">
|
||||
<div className="space-y-2"><Label htmlFor="key-name">{t("keys.name")}</Label><Input id="key-name" {...form.register("name")} />{form.formState.errors.name ? <p className="text-xs text-destructive">{form.formState.errors.name.message}</p> : null}</div>
|
||||
<div className="flex items-center justify-between border-b py-2"><Label htmlFor="key-enabled">{keyEnabled ? t("common.enabled") : t("common.disabled")}</Label><Switch id="key-enabled" checked={keyEnabled} onCheckedChange={(checked) => form.setValue("enabled", checked)} /></div>
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div className="space-y-2"><Label htmlFor="key-rpm">{t("keys.rpm")}</Label><Input id="key-rpm" type="number" min="1" max="100000" {...form.register("rpmLimit", { valueAsNumber: true })} /></div>
|
||||
<div className="space-y-2"><Label htmlFor="key-concurrency">{t("keys.maxConcurrent")}</Label><Input id="key-concurrency" type="number" min="1" max="1024" {...form.register("maxConcurrent", { valueAsNumber: true })} /></div>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<Label htmlFor="key-rpm">{t("keys.rpm")}</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs text-muted-foreground">{t("keys.unlimited")}</span>
|
||||
<Switch id="key-rpm-unlimited" checked={rpmUnlimited} onCheckedChange={(checked) => form.setValue("rpmUnlimited", checked, { shouldDirty: true })} />
|
||||
</div>
|
||||
</div>
|
||||
<Input id="key-rpm" type="number" min="1" max="100000" disabled={rpmUnlimited} {...form.register("rpmLimit", { valueAsNumber: true })} />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<Label htmlFor="key-concurrency">{t("keys.maxConcurrent")}</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs text-muted-foreground">{t("keys.unlimited")}</span>
|
||||
<Switch id="key-concurrency-unlimited" checked={concurrencyUnlimited} onCheckedChange={(checked) => form.setValue("concurrencyUnlimited", checked, { shouldDirty: true })} />
|
||||
</div>
|
||||
</div>
|
||||
<Input id="key-concurrency" type="number" min="1" max="1024" disabled={concurrencyUnlimited} {...form.register("maxConcurrent", { valueAsNumber: true })} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<Label htmlFor="key-billing-unlimited">{t("keys.billingLimit")}</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs text-muted-foreground">{t("keys.unlimited")}</span>
|
||||
<Switch id="key-billing-unlimited" checked={billingUnlimited} onCheckedChange={(checked) => form.setValue("billingUnlimited", checked, { shouldDirty: true })} />
|
||||
<div className="grid items-start gap-3 sm:grid-cols-2">
|
||||
<div className="space-y-2">
|
||||
<div className="flex h-5 items-center justify-between gap-3">
|
||||
<div className="flex min-w-0 items-center gap-1.5">
|
||||
<Label htmlFor="key-billing-unlimited">{t("keys.billingLimit")}</Label>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<button type="button" className="text-muted-foreground transition-colors hover:text-foreground" aria-label={t("keys.billingLimitDescription")}>
|
||||
<CircleHelp className="size-3.5" />
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent className="max-w-72">{t("keys.billingLimitDescription")}</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs text-muted-foreground">{t("keys.unlimited")}</span>
|
||||
<Switch id="key-billing-unlimited" checked={billingUnlimited} onCheckedChange={(checked) => form.setValue("billingUnlimited", checked, { shouldDirty: true })} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="relative">
|
||||
<span className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-xs text-muted-foreground">$</span>
|
||||
<Input className="pl-7" type="number" min="0.01" max={MAX_BILLING_LIMIT_USD} step="0.01" disabled={billingUnlimited} {...form.register("billingLimitUsd", { valueAsNumber: true })} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="relative">
|
||||
<span className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-xs text-muted-foreground">$</span>
|
||||
<Input className="pl-7" type="number" min="0.01" max={MAX_BILLING_LIMIT_USD} step="0.01" disabled={billingUnlimited} {...form.register("billingLimitUsd", { valueAsNumber: true })} />
|
||||
<div className="space-y-2">
|
||||
<div className="flex h-5 items-center justify-between gap-3">
|
||||
<Label htmlFor="key-expiry-unlimited">{t("keys.expires")}</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs text-muted-foreground">{t("keys.unlimited")}</span>
|
||||
<Switch id="key-expiry-unlimited" checked={expiryUnlimited} onCheckedChange={(checked) => {
|
||||
form.setValue("expiryUnlimited", checked, { shouldDirty: true });
|
||||
if (checked) form.clearErrors("expiresAt");
|
||||
}} />
|
||||
</div>
|
||||
</div>
|
||||
<Controller control={form.control} name="expiresAt" render={({ field }) => <DateTimePicker value={expiryUnlimited ? "" : field.value} onChange={field.onChange} disabled={expiryUnlimited} placeholder={expiryUnlimited ? t("keys.neverExpires") : t("keys.selectExpiry")} />} />
|
||||
{form.formState.errors.expiresAt ? <p className="text-xs text-destructive">{form.formState.errors.expiresAt.message}</p> : null}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">{t("keys.billingLimitDescription")}</p>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>{t("keys.expires")}</Label>
|
||||
<Controller control={form.control} name="expiresAt" render={({ field }) => <DateTimePicker value={field.value} onChange={field.onChange} />} />
|
||||
</div>
|
||||
<fieldset className="min-w-0 space-y-2">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<legend className="text-xs font-medium">{t("keys.models")}</legend>
|
||||
<span className="min-w-0 truncate text-xs text-muted-foreground">{selectedModels.length === 0 ? t("keys.allModels") : t("keys.selectedModels", { count: selectedModels.length })}</span>
|
||||
<Badge variant="secondary" className="min-w-0 max-w-[55%] truncate text-[10px] font-normal">{selectedModels.length === 0 ? t("keys.allModels") : t("keys.selectedModels", { count: selectedModels.length })}</Badge>
|
||||
</div>
|
||||
<div className="min-w-0 overflow-hidden rounded-md border">
|
||||
<div className="relative border-b bg-muted/25">
|
||||
<Search className="pointer-events-none absolute left-3 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input className="rounded-none border-0 bg-transparent pl-8 shadow-none focus-visible:bg-background focus-visible:ring-0" value={modelOptionsSearch} onChange={(event) => { setModelOptionsSearch(event.target.value); setModelOptionsPage(1); }} placeholder={t("keys.modelSearch")} aria-label={t("keys.modelSearch")} />
|
||||
<div className="min-w-0 overflow-hidden rounded-md bg-muted/25 p-1">
|
||||
<div className="relative">
|
||||
<Search className="pointer-events-none absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input className="bg-transparent pl-8 shadow-none focus-visible:bg-background/70" value={modelOptionsSearch} onChange={(event) => { setModelOptionsSearch(event.target.value); setModelOptionsPage(1); }} placeholder={t("keys.modelSearch")} aria-label={t("keys.modelSearch")} />
|
||||
</div>
|
||||
<div className="max-h-40 divide-y overflow-y-auto overscroll-contain sm:max-h-52">
|
||||
{modelsQuery.isPending ? <LoadingState className="min-h-24" /> : modelsQuery.data?.items.map((model) => {
|
||||
<div className="mt-1 max-h-40 overflow-y-auto overscroll-contain sm:max-h-44">
|
||||
{modelsQuery.isPending ? <LoadingState className="min-h-20" /> : modelsQuery.data?.items.map((model) => {
|
||||
const checked = selectedModels.includes(model.id);
|
||||
const controlId = `allowed-model-${model.id}`;
|
||||
return (
|
||||
<label key={model.id} htmlFor={controlId} className="flex h-9 cursor-pointer items-center gap-3 px-3 text-xs transition-colors hover:bg-accent/55">
|
||||
<label key={model.id} htmlFor={controlId} className={cn("flex h-8 cursor-pointer items-center gap-2.5 rounded-md px-2 text-xs transition-colors hover:bg-accent/40", checked && "bg-accent/55")}>
|
||||
<Checkbox id={controlId} checked={checked} onCheckedChange={() => toggleModel(model.id)} aria-label={t("common.selectItem", { name: model.publicId })} />
|
||||
<span className="min-w-0 flex-1 truncate font-medium" title={model.publicId}>{model.publicId}</span>
|
||||
<span className="hidden max-w-[42%] shrink-0 truncate text-muted-foreground sm:block" title={model.upstreamModel}>{model.upstreamModel}</span>
|
||||
{!model.enabled ? <Badge variant="outline" className="shrink-0 text-muted-foreground">{t("common.disabled")}</Badge> : null}
|
||||
<span className="min-w-0 flex-1 truncate" title={model.publicId}>{model.publicId}</span>
|
||||
<span className="hidden max-w-[42%] shrink-0 truncate text-[11px] text-muted-foreground sm:block" title={model.upstreamModel}>{model.upstreamModel}</span>
|
||||
{!model.enabled ? <Badge variant="secondary" className="shrink-0 text-[10px] font-normal text-muted-foreground">{t("common.disabled")}</Badge> : null}
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
@@ -395,8 +447,15 @@ export function ClientKeysPage() {
|
||||
{modelsQuery.data && modelsQuery.data.total > modelsQuery.data.pageSize ? <ModelOptionPagination page={modelsQuery.data.page} pageSize={modelsQuery.data.pageSize} total={modelsQuery.data.total} onPageChange={setModelOptionsPage} /> : null}
|
||||
</div>
|
||||
</fieldset>
|
||||
<section className="flex items-center justify-between gap-4 rounded-lg bg-muted/25 px-3 py-2.5">
|
||||
<div className="min-w-0">
|
||||
<Label htmlFor="key-enabled">{keyEnabled ? t("common.enabled") : t("common.disabled")}</Label>
|
||||
<p className="mt-1 text-xs leading-5 text-muted-foreground">{t("keys.enabledDescription")}</p>
|
||||
</div>
|
||||
<Switch className="shrink-0" id="key-enabled" checked={keyEnabled} onCheckedChange={(checked) => form.setValue("enabled", checked)} />
|
||||
</section>
|
||||
</div>
|
||||
<DialogFooter className="shrink-0 gap-2 border-t bg-background px-5 py-4 sm:gap-0"><Button type="button" variant="secondary" size="sm" onClick={() => setEditing(null)}>{t("common.cancel")}</Button><Button type="submit" size="sm" disabled={saveMutation.isPending}>{saveMutation.isPending ? <Spinner /> : null}{editing === "new" ? t("common.create") : t("common.save")}</Button></DialogFooter>
|
||||
<DialogFooter className="shrink-0 gap-2 bg-muted/20 px-5 py-3.5 sm:gap-0"><Button type="button" variant="secondary" size="sm" onClick={() => setEditing(null)}>{t("common.cancel")}</Button><Button type="submit" size="sm" disabled={saveMutation.isPending}>{saveMutation.isPending ? <Spinner /> : null}{editing === "new" ? t("common.create") : t("common.save")}</Button></DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { format } from "date-fns"
|
||||
import { enUS, zhCN } from "date-fns/locale"
|
||||
import { CalendarIcon, X } from "lucide-react"
|
||||
import { CalendarIcon } from "lucide-react"
|
||||
import { useRef } from "react"
|
||||
import { useTranslation } from "react-i18next"
|
||||
import { enUS as enUSDayPicker, zhCN as zhCNDayPicker } from "react-day-picker/locale"
|
||||
@@ -16,9 +16,10 @@ type DateTimePickerProps = {
|
||||
value: string
|
||||
onChange: (value: string) => void
|
||||
placeholder?: string
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
export function DateTimePicker({ value, onChange, placeholder }: DateTimePickerProps) {
|
||||
export function DateTimePicker({ value, onChange, placeholder, disabled = false }: DateTimePickerProps) {
|
||||
const { t, i18n } = useTranslation()
|
||||
const selected = parseLocalDateTime(value)
|
||||
const isChinese = i18n.language.toLowerCase().startsWith("zh")
|
||||
@@ -48,17 +49,14 @@ export function DateTimePicker({ value, onChange, placeholder }: DateTimePickerP
|
||||
|
||||
return (
|
||||
<Popover>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<PopoverTrigger asChild>
|
||||
<Button type="button" variant="outline" className={cn("h-8 min-w-0 flex-1 justify-start rounded-md bg-secondary/55 px-3 text-left font-normal", !selected && "text-muted-foreground")}>
|
||||
<CalendarIcon />
|
||||
<span className="truncate">
|
||||
{selected ? format(selected, isChinese ? "yyyy年M月d日 HH:mm:ss" : "MMM d, yyyy HH:mm:ss", { locale: isChinese ? zhCN : enUS }) : (placeholder ?? t("keys.neverExpires"))}
|
||||
</span>
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
{selected ? <Button type="button" variant="ghost" size="icon" className="size-8 shrink-0" onClick={() => onChange("")} aria-label={t("keys.clearExpiry")} title={t("keys.clearExpiry")}><X /></Button> : null}
|
||||
</div>
|
||||
<PopoverTrigger asChild>
|
||||
<Button type="button" variant="secondary" disabled={disabled} className={cn("h-8 w-full min-w-0 justify-start rounded-md bg-secondary/55 px-3 text-left font-normal", !selected && "text-muted-foreground")}>
|
||||
<CalendarIcon />
|
||||
<span className="truncate">
|
||||
{selected ? format(selected, isChinese ? "yyyy年M月d日 HH:mm:ss" : "MMM d, yyyy HH:mm:ss", { locale: isChinese ? zhCN : enUS }) : (placeholder ?? t("keys.neverExpires"))}
|
||||
</span>
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-auto overflow-hidden p-0" align="start">
|
||||
<Calendar
|
||||
mode="single"
|
||||
@@ -67,15 +65,15 @@ export function DateTimePicker({ value, onChange, placeholder }: DateTimePickerP
|
||||
onSelect={selectDate}
|
||||
locale={isChinese ? zhCNDayPicker : enUSDayPicker}
|
||||
/>
|
||||
<div className="flex items-center gap-3 border-t p-3">
|
||||
<div className="flex items-center gap-2 border-t px-3 py-2">
|
||||
<span className="text-xs text-muted-foreground">{t("keys.expiryTime")}</span>
|
||||
<div className="ml-auto flex items-center gap-1 font-mono text-xs">
|
||||
<div className="ml-auto flex items-center gap-1 text-xs">
|
||||
{timeParts.map((part, index) => (
|
||||
<div className="contents" key={index}>
|
||||
{index > 0 ? <span className="text-muted-foreground">:</span> : null}
|
||||
<Input
|
||||
aria-label={`${t("keys.expiryTime")} ${index === 0 ? "HH" : index === 1 ? "MM" : "SS"}`}
|
||||
className="h-8 w-10 bg-background px-1 text-center font-mono text-xs tabular-nums"
|
||||
className="h-7 w-9 bg-background px-1 text-center text-xs tabular-nums"
|
||||
inputMode="numeric"
|
||||
maxLength={2}
|
||||
pattern="[0-9]*"
|
||||
|
||||
@@ -621,19 +621,21 @@ const resources = {
|
||||
statusActive: "可用",
|
||||
statusExpired: "已过期",
|
||||
restrictedModels: "指定模型",
|
||||
expires: "有效期",
|
||||
expires: "截止日期",
|
||||
lastUsed: "最近使用",
|
||||
rpm: "每分钟请求",
|
||||
maxConcurrent: "最大并发",
|
||||
maxConcurrent: "最大并发数",
|
||||
rpmValue: "{{value}} RPM",
|
||||
concurrentValue: "{{value}} 并发",
|
||||
unlimited: "无限制",
|
||||
billedUsage: "已计费 {{value}}",
|
||||
billingLimitDescription: "按请求审计中的计费累计;优先使用上游实报费用,否则使用官方价格估算。",
|
||||
enabledDescription: "控制该密钥是否允许发起 API 请求。",
|
||||
allModels: "全部模型",
|
||||
modelSearch: "搜索模型,留空默认允许全部模型。",
|
||||
selectedModels: "已选择 {{count}} 个模型",
|
||||
neverExpires: "永不过期",
|
||||
selectExpiry: "选择截止日期",
|
||||
clearExpiry: "清除有效期",
|
||||
expiryTime: "到期时间",
|
||||
createTitle: "创建密钥",
|
||||
@@ -1142,7 +1144,7 @@ const resources = {
|
||||
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}}", buildRouteMode: { label: "Upstream endpoint", auto: "Automatic", build: "Build", xai: "XAI", autoDescription: "Selects an upstream based on account tier and risk status.", buildDescription: "Routes all requests to Build with XAI fallback disabled.", xaiDescription: "Routes all inference and video requests to XAI.", xaiUnconfirmedWarning: "This account has not been confirmed for XAI access; the upstream may reject requests." }, buildSuperEntitled: { label: "Mark asLine 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" },
|
||||
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.", allModels: "All models", modelSearch: "Search models. Leave blank to allow all models.", selectedModels: "{{count}} models selected", neverExpires: "Never expires", 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?" },
|
||||
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",
|
||||
description: "Successful requests store metadata only. Failed requests retain a redacted and size-limited diagnostic snapshot.",
|
||||
|
||||
Reference in new issue
Block a user