api_key_service_quota_test.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. //go:build unit
  2. package service
  3. import (
  4. "context"
  5. "testing"
  6. "time"
  7. "github.com/Wei-Shaw/sub2api/internal/pkg/pagination"
  8. "github.com/stretchr/testify/require"
  9. )
  10. type quotaStateRepoStub struct {
  11. quotaBaseAPIKeyRepoStub
  12. stateCalls int
  13. state *APIKeyQuotaUsageState
  14. stateErr error
  15. }
  16. func (s *quotaStateRepoStub) IncrementQuotaUsedAndGetState(ctx context.Context, id int64, amount float64) (*APIKeyQuotaUsageState, error) {
  17. s.stateCalls++
  18. if s.stateErr != nil {
  19. return nil, s.stateErr
  20. }
  21. if s.state == nil {
  22. return nil, nil
  23. }
  24. out := *s.state
  25. return &out, nil
  26. }
  27. type quotaStateCacheStub struct {
  28. deleteAuthKeys []string
  29. }
  30. func (s *quotaStateCacheStub) GetCreateAttemptCount(context.Context, int64) (int, error) {
  31. return 0, nil
  32. }
  33. func (s *quotaStateCacheStub) IncrementCreateAttemptCount(context.Context, int64) error {
  34. return nil
  35. }
  36. func (s *quotaStateCacheStub) DeleteCreateAttemptCount(context.Context, int64) error {
  37. return nil
  38. }
  39. func (s *quotaStateCacheStub) IncrementDailyUsage(context.Context, string) error {
  40. return nil
  41. }
  42. func (s *quotaStateCacheStub) SetDailyUsageExpiry(context.Context, string, time.Duration) error {
  43. return nil
  44. }
  45. func (s *quotaStateCacheStub) GetAuthCache(context.Context, string) (*APIKeyAuthCacheEntry, error) {
  46. return nil, nil
  47. }
  48. func (s *quotaStateCacheStub) SetAuthCache(context.Context, string, *APIKeyAuthCacheEntry, time.Duration) error {
  49. return nil
  50. }
  51. func (s *quotaStateCacheStub) DeleteAuthCache(_ context.Context, key string) error {
  52. s.deleteAuthKeys = append(s.deleteAuthKeys, key)
  53. return nil
  54. }
  55. func (s *quotaStateCacheStub) PublishAuthCacheInvalidation(context.Context, string) error {
  56. return nil
  57. }
  58. func (s *quotaStateCacheStub) SubscribeAuthCacheInvalidation(context.Context, func(string)) error {
  59. return nil
  60. }
  61. type quotaBaseAPIKeyRepoStub struct {
  62. getByIDCalls int
  63. }
  64. func (s *quotaBaseAPIKeyRepoStub) Create(context.Context, *APIKey) error {
  65. panic("unexpected Create call")
  66. }
  67. func (s *quotaBaseAPIKeyRepoStub) GetByID(context.Context, int64) (*APIKey, error) {
  68. s.getByIDCalls++
  69. return nil, nil
  70. }
  71. func (s *quotaBaseAPIKeyRepoStub) GetKeyAndOwnerID(context.Context, int64) (string, int64, error) {
  72. panic("unexpected GetKeyAndOwnerID call")
  73. }
  74. func (s *quotaBaseAPIKeyRepoStub) GetByKey(context.Context, string) (*APIKey, error) {
  75. panic("unexpected GetByKey call")
  76. }
  77. func (s *quotaBaseAPIKeyRepoStub) GetByKeyForAuth(context.Context, string) (*APIKey, error) {
  78. panic("unexpected GetByKeyForAuth call")
  79. }
  80. func (s *quotaBaseAPIKeyRepoStub) Update(context.Context, *APIKey, APIKeyUpdateFields) error {
  81. panic("unexpected Update call")
  82. }
  83. func (s *quotaBaseAPIKeyRepoStub) Delete(context.Context, int64) error {
  84. panic("unexpected Delete call")
  85. }
  86. func (s *quotaBaseAPIKeyRepoStub) DeleteWithAudit(context.Context, int64) error {
  87. panic("unexpected DeleteWithAudit call")
  88. }
  89. func (s *quotaBaseAPIKeyRepoStub) ListByUserID(context.Context, int64, pagination.PaginationParams, APIKeyListFilters) ([]APIKey, *pagination.PaginationResult, error) {
  90. panic("unexpected ListByUserID call")
  91. }
  92. func (s *quotaBaseAPIKeyRepoStub) VerifyOwnership(context.Context, int64, []int64) ([]int64, error) {
  93. panic("unexpected VerifyOwnership call")
  94. }
  95. func (s *quotaBaseAPIKeyRepoStub) CountByUserID(context.Context, int64) (int64, error) {
  96. panic("unexpected CountByUserID call")
  97. }
  98. func (s *quotaBaseAPIKeyRepoStub) ExistsByKey(context.Context, string) (bool, error) {
  99. panic("unexpected ExistsByKey call")
  100. }
  101. func (s *quotaBaseAPIKeyRepoStub) ListByGroupID(context.Context, int64, pagination.PaginationParams) ([]APIKey, *pagination.PaginationResult, error) {
  102. panic("unexpected ListByGroupID call")
  103. }
  104. func (s *quotaBaseAPIKeyRepoStub) SearchAPIKeys(context.Context, int64, string, int) ([]APIKey, error) {
  105. panic("unexpected SearchAPIKeys call")
  106. }
  107. func (s *quotaBaseAPIKeyRepoStub) ClearGroupIDByGroupID(context.Context, int64) (int64, error) {
  108. panic("unexpected ClearGroupIDByGroupID call")
  109. }
  110. func (s *quotaBaseAPIKeyRepoStub) UpdateGroupIDByUserAndGroup(context.Context, int64, int64, int64) (int64, error) {
  111. panic("unexpected UpdateGroupIDByUserAndGroup call")
  112. }
  113. func (s *quotaBaseAPIKeyRepoStub) CountByGroupID(context.Context, int64) (int64, error) {
  114. panic("unexpected CountByGroupID call")
  115. }
  116. func (s *quotaBaseAPIKeyRepoStub) ListKeysByUserID(context.Context, int64) ([]string, error) {
  117. panic("unexpected ListKeysByUserID call")
  118. }
  119. func (s *quotaBaseAPIKeyRepoStub) ListKeysByGroupID(context.Context, int64) ([]string, error) {
  120. panic("unexpected ListKeysByGroupID call")
  121. }
  122. func (s *quotaBaseAPIKeyRepoStub) IncrementQuotaUsed(context.Context, int64, float64) (float64, error) {
  123. panic("unexpected IncrementQuotaUsed call")
  124. }
  125. func (s *quotaBaseAPIKeyRepoStub) UpdateLastUsed(context.Context, int64, time.Time) error {
  126. panic("unexpected UpdateLastUsed call")
  127. }
  128. func (s *quotaBaseAPIKeyRepoStub) IncrementRateLimitUsage(context.Context, int64, float64) error {
  129. panic("unexpected IncrementRateLimitUsage call")
  130. }
  131. func (s *quotaBaseAPIKeyRepoStub) ResetRateLimitWindows(context.Context, int64) error {
  132. panic("unexpected ResetRateLimitWindows call")
  133. }
  134. func (s *quotaBaseAPIKeyRepoStub) GetRateLimitData(context.Context, int64) (*APIKeyRateLimitData, error) {
  135. panic("unexpected GetRateLimitData call")
  136. }
  137. func TestAPIKeyService_UpdateQuotaUsed_UsesAtomicStatePath(t *testing.T) {
  138. repo := &quotaStateRepoStub{
  139. state: &APIKeyQuotaUsageState{
  140. QuotaUsed: 12,
  141. Quota: 10,
  142. Key: "sk-test-quota",
  143. Status: StatusAPIKeyQuotaExhausted,
  144. },
  145. }
  146. cache := &quotaStateCacheStub{}
  147. svc := &APIKeyService{
  148. apiKeyRepo: repo,
  149. cache: cache,
  150. }
  151. err := svc.UpdateQuotaUsed(context.Background(), 101, 2)
  152. require.NoError(t, err)
  153. require.Equal(t, 1, repo.stateCalls)
  154. require.Equal(t, 0, repo.getByIDCalls, "fast path should not re-read API key by id")
  155. require.Equal(t, []string{svc.authCacheKey("sk-test-quota")}, cache.deleteAuthKeys)
  156. }
  157. func TestAPIKeyService_Update_ReactivatesQuotaExhaustedWhenQuotaUnlimited(t *testing.T) {
  158. repo := &apiKeyRepoStub{
  159. apiKey: &APIKey{
  160. ID: 10,
  161. UserID: 7,
  162. Key: "sk-test-unlimited",
  163. Status: StatusAPIKeyQuotaExhausted,
  164. Quota: 10,
  165. QuotaUsed: 12,
  166. },
  167. }
  168. svc := &APIKeyService{apiKeyRepo: repo}
  169. quota := 0.0
  170. updated, err := svc.Update(context.Background(), 10, 7, UpdateAPIKeyRequest{Quota: &quota})
  171. require.NoError(t, err)
  172. require.Equal(t, StatusActive, updated.Status)
  173. require.Equal(t, 0.0, updated.Quota)
  174. require.Len(t, repo.updatedKeys, 1)
  175. require.Equal(t, StatusActive, repo.updatedKeys[0].Status)
  176. require.Equal(t, 0.0, repo.updatedKeys[0].Quota)
  177. }