overload_cooldown_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. //go:build unit
  2. package service
  3. import (
  4. "context"
  5. "encoding/json"
  6. "testing"
  7. "time"
  8. "github.com/Wei-Shaw/sub2api/internal/config"
  9. "github.com/stretchr/testify/require"
  10. )
  11. // ---------------------------------------------------------------------------
  12. // errSettingRepo: a SettingRepository that always returns errors on read
  13. // ---------------------------------------------------------------------------
  14. type errSettingRepo struct {
  15. mockSettingRepo // embed the existing mock from backup_service_test.go
  16. readErr error
  17. }
  18. func (r *errSettingRepo) GetValue(_ context.Context, _ string) (string, error) {
  19. return "", r.readErr
  20. }
  21. func (r *errSettingRepo) Get(_ context.Context, _ string) (*Setting, error) {
  22. return nil, r.readErr
  23. }
  24. // ---------------------------------------------------------------------------
  25. // overloadAccountRepoStub: records SetOverloaded calls
  26. // ---------------------------------------------------------------------------
  27. type overloadAccountRepoStub struct {
  28. mockAccountRepoForGemini
  29. overloadCalls int
  30. errorCalls int
  31. lastOverloadID int64
  32. lastOverloadEnd time.Time
  33. }
  34. func (r *overloadAccountRepoStub) SetError(_ context.Context, _ int64, _ string) error {
  35. r.errorCalls++
  36. return nil
  37. }
  38. func (r *overloadAccountRepoStub) SetOverloaded(_ context.Context, id int64, until time.Time) error {
  39. r.overloadCalls++
  40. r.lastOverloadID = id
  41. r.lastOverloadEnd = until
  42. return nil
  43. }
  44. // ===========================================================================
  45. // SettingService: GetOverloadCooldownSettings
  46. // ===========================================================================
  47. func TestGetOverloadCooldownSettings_DefaultsWhenNotSet(t *testing.T) {
  48. repo := newMockSettingRepo()
  49. svc := NewSettingService(repo, &config.Config{})
  50. settings, err := svc.GetOverloadCooldownSettings(context.Background())
  51. require.NoError(t, err)
  52. require.True(t, settings.Enabled)
  53. require.Equal(t, 10, settings.CooldownMinutes)
  54. }
  55. func TestGetOverloadCooldownSettings_ReadsFromDB(t *testing.T) {
  56. repo := newMockSettingRepo()
  57. data, _ := json.Marshal(OverloadCooldownSettings{Enabled: false, CooldownMinutes: 30})
  58. repo.data[SettingKeyOverloadCooldownSettings] = string(data)
  59. svc := NewSettingService(repo, &config.Config{})
  60. settings, err := svc.GetOverloadCooldownSettings(context.Background())
  61. require.NoError(t, err)
  62. require.False(t, settings.Enabled)
  63. require.Equal(t, 30, settings.CooldownMinutes)
  64. }
  65. func TestGetOverloadCooldownSettings_ClampsMinValue(t *testing.T) {
  66. repo := newMockSettingRepo()
  67. data, _ := json.Marshal(OverloadCooldownSettings{Enabled: true, CooldownMinutes: 0})
  68. repo.data[SettingKeyOverloadCooldownSettings] = string(data)
  69. svc := NewSettingService(repo, &config.Config{})
  70. settings, err := svc.GetOverloadCooldownSettings(context.Background())
  71. require.NoError(t, err)
  72. require.Equal(t, 1, settings.CooldownMinutes)
  73. }
  74. func TestGetOverloadCooldownSettings_ClampsMaxValue(t *testing.T) {
  75. repo := newMockSettingRepo()
  76. data, _ := json.Marshal(OverloadCooldownSettings{Enabled: true, CooldownMinutes: 999})
  77. repo.data[SettingKeyOverloadCooldownSettings] = string(data)
  78. svc := NewSettingService(repo, &config.Config{})
  79. settings, err := svc.GetOverloadCooldownSettings(context.Background())
  80. require.NoError(t, err)
  81. require.Equal(t, 120, settings.CooldownMinutes)
  82. }
  83. func TestGetOverloadCooldownSettings_InvalidJSON_ReturnsDefaults(t *testing.T) {
  84. repo := newMockSettingRepo()
  85. repo.data[SettingKeyOverloadCooldownSettings] = "not-json"
  86. svc := NewSettingService(repo, &config.Config{})
  87. settings, err := svc.GetOverloadCooldownSettings(context.Background())
  88. require.NoError(t, err)
  89. require.True(t, settings.Enabled)
  90. require.Equal(t, 10, settings.CooldownMinutes)
  91. }
  92. func TestGetOverloadCooldownSettings_EmptyValue_ReturnsDefaults(t *testing.T) {
  93. repo := newMockSettingRepo()
  94. repo.data[SettingKeyOverloadCooldownSettings] = ""
  95. svc := NewSettingService(repo, &config.Config{})
  96. settings, err := svc.GetOverloadCooldownSettings(context.Background())
  97. require.NoError(t, err)
  98. require.True(t, settings.Enabled)
  99. require.Equal(t, 10, settings.CooldownMinutes)
  100. }
  101. // ===========================================================================
  102. // SettingService: SetOverloadCooldownSettings
  103. // ===========================================================================
  104. func TestSetOverloadCooldownSettings_Success(t *testing.T) {
  105. repo := newMockSettingRepo()
  106. svc := NewSettingService(repo, &config.Config{})
  107. err := svc.SetOverloadCooldownSettings(context.Background(), &OverloadCooldownSettings{
  108. Enabled: false,
  109. CooldownMinutes: 25,
  110. })
  111. require.NoError(t, err)
  112. // Verify round-trip
  113. settings, err := svc.GetOverloadCooldownSettings(context.Background())
  114. require.NoError(t, err)
  115. require.False(t, settings.Enabled)
  116. require.Equal(t, 25, settings.CooldownMinutes)
  117. }
  118. func TestSetOverloadCooldownSettings_RejectsNil(t *testing.T) {
  119. svc := NewSettingService(newMockSettingRepo(), &config.Config{})
  120. err := svc.SetOverloadCooldownSettings(context.Background(), nil)
  121. require.Error(t, err)
  122. }
  123. func TestSetOverloadCooldownSettings_EnabledRejectsOutOfRange(t *testing.T) {
  124. svc := NewSettingService(newMockSettingRepo(), &config.Config{})
  125. for _, minutes := range []int{0, -1, 121, 999} {
  126. err := svc.SetOverloadCooldownSettings(context.Background(), &OverloadCooldownSettings{
  127. Enabled: true, CooldownMinutes: minutes,
  128. })
  129. require.Error(t, err, "should reject enabled=true + cooldown_minutes=%d", minutes)
  130. require.Contains(t, err.Error(), "cooldown_minutes must be between 1-120")
  131. }
  132. }
  133. func TestSetOverloadCooldownSettings_DisabledNormalizesOutOfRange(t *testing.T) {
  134. repo := newMockSettingRepo()
  135. svc := NewSettingService(repo, &config.Config{})
  136. // enabled=false + cooldown_minutes=0 应该保存成功,值被归一化为10
  137. err := svc.SetOverloadCooldownSettings(context.Background(), &OverloadCooldownSettings{
  138. Enabled: false, CooldownMinutes: 0,
  139. })
  140. require.NoError(t, err, "disabled with invalid minutes should NOT be rejected")
  141. // 验证持久化后读回来的值
  142. settings, err := svc.GetOverloadCooldownSettings(context.Background())
  143. require.NoError(t, err)
  144. require.False(t, settings.Enabled)
  145. require.Equal(t, 10, settings.CooldownMinutes, "should be normalized to default")
  146. }
  147. func TestSetOverloadCooldownSettings_AcceptsBoundaries(t *testing.T) {
  148. svc := NewSettingService(newMockSettingRepo(), &config.Config{})
  149. for _, minutes := range []int{1, 60, 120} {
  150. err := svc.SetOverloadCooldownSettings(context.Background(), &OverloadCooldownSettings{
  151. Enabled: true, CooldownMinutes: minutes,
  152. })
  153. require.NoError(t, err, "should accept cooldown_minutes=%d", minutes)
  154. }
  155. }
  156. // ===========================================================================
  157. // RateLimitService: handle529 behaviour
  158. // ===========================================================================
  159. func TestHandle529_EnabledFromDB_PausesAccount(t *testing.T) {
  160. accountRepo := &overloadAccountRepoStub{}
  161. settingRepo := newMockSettingRepo()
  162. data, _ := json.Marshal(OverloadCooldownSettings{Enabled: true, CooldownMinutes: 15})
  163. settingRepo.data[SettingKeyOverloadCooldownSettings] = string(data)
  164. settingSvc := NewSettingService(settingRepo, &config.Config{})
  165. svc := NewRateLimitService(accountRepo, nil, &config.Config{}, nil, nil)
  166. svc.SetSettingService(settingSvc)
  167. account := &Account{ID: 42, Platform: PlatformAnthropic, Type: AccountTypeOAuth}
  168. before := time.Now()
  169. svc.handle529(context.Background(), account)
  170. require.Equal(t, 1, accountRepo.overloadCalls)
  171. require.Equal(t, int64(42), accountRepo.lastOverloadID)
  172. require.WithinDuration(t, before.Add(15*time.Minute), accountRepo.lastOverloadEnd, 2*time.Second)
  173. }
  174. func TestHandle529_DisabledFromDB_SkipsAccount(t *testing.T) {
  175. accountRepo := &overloadAccountRepoStub{}
  176. settingRepo := newMockSettingRepo()
  177. data, _ := json.Marshal(OverloadCooldownSettings{Enabled: false, CooldownMinutes: 15})
  178. settingRepo.data[SettingKeyOverloadCooldownSettings] = string(data)
  179. settingSvc := NewSettingService(settingRepo, &config.Config{})
  180. svc := NewRateLimitService(accountRepo, nil, &config.Config{}, nil, nil)
  181. svc.SetSettingService(settingSvc)
  182. account := &Account{ID: 42, Platform: PlatformAnthropic, Type: AccountTypeOAuth}
  183. svc.handle529(context.Background(), account)
  184. require.Equal(t, 0, accountRepo.overloadCalls, "should NOT pause when disabled")
  185. }
  186. func TestHandle529_NilSettingService_FallsBackToConfig(t *testing.T) {
  187. accountRepo := &overloadAccountRepoStub{}
  188. cfg := &config.Config{}
  189. cfg.RateLimit.OverloadCooldownMinutes = 20
  190. svc := NewRateLimitService(accountRepo, nil, cfg, nil, nil)
  191. // NOT calling SetSettingService — remains nil
  192. account := &Account{ID: 77, Platform: PlatformAnthropic, Type: AccountTypeOAuth}
  193. before := time.Now()
  194. svc.handle529(context.Background(), account)
  195. require.Equal(t, 1, accountRepo.overloadCalls)
  196. require.WithinDuration(t, before.Add(20*time.Minute), accountRepo.lastOverloadEnd, 2*time.Second)
  197. }
  198. func TestHandle529_NilSettingService_ZeroConfig_DefaultsTen(t *testing.T) {
  199. accountRepo := &overloadAccountRepoStub{}
  200. svc := NewRateLimitService(accountRepo, nil, &config.Config{}, nil, nil)
  201. account := &Account{ID: 88, Platform: PlatformAnthropic, Type: AccountTypeOAuth}
  202. before := time.Now()
  203. svc.handle529(context.Background(), account)
  204. require.Equal(t, 1, accountRepo.overloadCalls)
  205. require.WithinDuration(t, before.Add(10*time.Minute), accountRepo.lastOverloadEnd, 2*time.Second)
  206. }
  207. func TestHandle529_DBReadError_FallsBackToConfig(t *testing.T) {
  208. accountRepo := &overloadAccountRepoStub{}
  209. errRepo := &errSettingRepo{readErr: context.DeadlineExceeded}
  210. errRepo.data = make(map[string]string)
  211. cfg := &config.Config{}
  212. cfg.RateLimit.OverloadCooldownMinutes = 7
  213. settingSvc := NewSettingService(errRepo, cfg)
  214. svc := NewRateLimitService(accountRepo, nil, cfg, nil, nil)
  215. svc.SetSettingService(settingSvc)
  216. account := &Account{ID: 99, Platform: PlatformAnthropic, Type: AccountTypeOAuth}
  217. before := time.Now()
  218. svc.handle529(context.Background(), account)
  219. require.Equal(t, 1, accountRepo.overloadCalls)
  220. require.WithinDuration(t, before.Add(7*time.Minute), accountRepo.lastOverloadEnd, 2*time.Second)
  221. }
  222. func TestHandleUpstreamError_529RespectsAccountPolicies(t *testing.T) {
  223. tests := []struct {
  224. name string
  225. credentials map[string]any
  226. }{
  227. {
  228. name: "pool mode",
  229. credentials: map[string]any{"pool_mode": true},
  230. },
  231. {
  232. name: "custom code filter excludes 529",
  233. credentials: map[string]any{
  234. "custom_error_codes_enabled": true,
  235. "custom_error_codes": []any{float64(429)},
  236. },
  237. },
  238. }
  239. for _, tt := range tests {
  240. t.Run(tt.name, func(t *testing.T) {
  241. repo := &overloadAccountRepoStub{}
  242. svc := NewRateLimitService(repo, nil, &config.Config{}, nil, nil)
  243. account := &Account{
  244. ID: 101,
  245. Platform: PlatformOpenAI,
  246. Type: AccountTypeAPIKey,
  247. Credentials: tt.credentials,
  248. }
  249. shouldDisable := svc.HandleUpstreamError(context.Background(), account, 529, nil, []byte(`{"error":{"message":"overloaded"}}`))
  250. require.False(t, shouldDisable)
  251. require.Zero(t, repo.overloadCalls)
  252. require.Zero(t, repo.errorCalls)
  253. })
  254. }
  255. }
  256. func TestHandleUpstreamError_529CustomCodeDisablesInsteadOfOverloadCooldown(t *testing.T) {
  257. repo := &overloadAccountRepoStub{}
  258. svc := NewRateLimitService(repo, nil, &config.Config{}, nil, nil)
  259. account := &Account{
  260. ID: 102,
  261. Platform: PlatformOpenAI,
  262. Type: AccountTypeAPIKey,
  263. Credentials: map[string]any{
  264. "custom_error_codes_enabled": true,
  265. "custom_error_codes": []any{float64(529)},
  266. },
  267. }
  268. shouldDisable := svc.HandleUpstreamError(context.Background(), account, 529, nil, []byte(`{"error":{"message":"overloaded"}}`))
  269. require.True(t, shouldDisable)
  270. require.Equal(t, 1, repo.errorCalls)
  271. require.Zero(t, repo.overloadCalls)
  272. }
  273. // ===========================================================================
  274. // Model: defaults & JSON round-trip
  275. // ===========================================================================
  276. func TestDefaultOverloadCooldownSettings(t *testing.T) {
  277. d := DefaultOverloadCooldownSettings()
  278. require.True(t, d.Enabled)
  279. require.Equal(t, 10, d.CooldownMinutes)
  280. }
  281. func TestOverloadCooldownSettings_JSONRoundTrip(t *testing.T) {
  282. original := OverloadCooldownSettings{Enabled: false, CooldownMinutes: 42}
  283. data, err := json.Marshal(original)
  284. require.NoError(t, err)
  285. var decoded OverloadCooldownSettings
  286. require.NoError(t, json.Unmarshal(data, &decoded))
  287. require.Equal(t, original, decoded)
  288. // Verify JSON uses snake_case field names
  289. var raw map[string]any
  290. require.NoError(t, json.Unmarshal(data, &raw))
  291. _, hasEnabled := raw["enabled"]
  292. _, hasCooldown := raw["cooldown_minutes"]
  293. require.True(t, hasEnabled, "JSON must use 'enabled'")
  294. require.True(t, hasCooldown, "JSON must use 'cooldown_minutes'")
  295. }