Merge pull request #3533 from Pluviobyte/codex/fix-api-key-unlimited-quota

fix(keys): reactivate exhausted keys set to unlimited
This commit is contained in:
Wesley Liddick
2026-06-29 09:19:53 +08:00
committed by GitHub
4 changed files with 46 additions and 7 deletions
+2 -2
View File
@@ -574,8 +574,8 @@ func (s *APIKeyService) Update(ctx context.Context, id int64, userID int64, req
// Update quota fields
if req.Quota != nil {
apiKey.Quota = *req.Quota
// If quota is increased and status was quota_exhausted, reactivate
if apiKey.Status == StatusAPIKeyQuotaExhausted && *req.Quota > apiKey.QuotaUsed {
// If quota now has room, or is changed to unlimited, reactivate exhausted keys.
if apiKey.Status == StatusAPIKeyQuotaExhausted && (*req.Quota <= 0 || *req.Quota > apiKey.QuotaUsed) {
apiKey.Status = StatusActive
}
}
@@ -27,7 +27,9 @@ type apiKeyRepoStub struct {
apiKey *APIKey // GetKeyAndOwnerID 的返回值
getByIDErr error // GetKeyAndOwnerID 的错误返回值
deleteErr error // Delete 的错误返回值
updateErr error // Update 的错误返回值
deletedIDs []int64 // 记录已删除的 API Key ID 列表
updatedKeys []APIKey
allowListByUserID bool
listByUserIDKeys []APIKey
listByUserIDErr error
@@ -74,7 +76,10 @@ func (s *apiKeyRepoStub) GetByKeyForAuth(ctx context.Context, key string) (*APIK
}
func (s *apiKeyRepoStub) Update(ctx context.Context, key *APIKey) error {
panic("unexpected Update call")
if key != nil {
s.updatedKeys = append(s.updatedKeys, *key)
}
return s.updateErr
}
// Delete 记录被删除的 API Key ID 并返回预设的错误。
@@ -174,3 +174,27 @@ func TestAPIKeyService_UpdateQuotaUsed_UsesAtomicStatePath(t *testing.T) {
require.Equal(t, 0, repo.getByIDCalls, "fast path should not re-read API key by id")
require.Equal(t, []string{svc.authCacheKey("sk-test-quota")}, cache.deleteAuthKeys)
}
func TestAPIKeyService_Update_ReactivatesQuotaExhaustedWhenQuotaUnlimited(t *testing.T) {
repo := &apiKeyRepoStub{
apiKey: &APIKey{
ID: 10,
UserID: 7,
Key: "sk-test-unlimited",
Status: StatusAPIKeyQuotaExhausted,
Quota: 10,
QuotaUsed: 12,
},
}
svc := &APIKeyService{apiKeyRepo: repo}
quota := 0.0
updated, err := svc.Update(context.Background(), 10, 7, UpdateAPIKeyRequest{Quota: &quota})
require.NoError(t, err)
require.Equal(t, StatusActive, updated.Status)
require.Equal(t, 0.0, updated.Quota)
require.Len(t, repo.updatedKeys, 1)
require.Equal(t, StatusActive, repo.updatedKeys[0].Status)
require.Equal(t, 0.0, repo.updatedKeys[0].Quota)
}