notify-limit.go 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. package service
  2. import (
  3. "fmt"
  4. "github.com/bytedance/gopkg/util/gopool"
  5. "one-api/common"
  6. "one-api/constant"
  7. "strconv"
  8. "sync"
  9. "time"
  10. )
  11. // notifyLimitStore is used for in-memory rate limiting when Redis is disabled
  12. var (
  13. notifyLimitStore sync.Map
  14. cleanupOnce sync.Once
  15. )
  16. type limitCount struct {
  17. Count int
  18. Timestamp time.Time
  19. }
  20. func getDuration() time.Duration {
  21. minute := constant.NotificationLimitDurationMinute
  22. return time.Duration(minute) * time.Minute
  23. }
  24. // startCleanupTask starts a background task to clean up expired entries
  25. func startCleanupTask() {
  26. gopool.Go(func() {
  27. for {
  28. time.Sleep(time.Hour)
  29. now := time.Now()
  30. notifyLimitStore.Range(func(key, value interface{}) bool {
  31. if limit, ok := value.(limitCount); ok {
  32. if now.Sub(limit.Timestamp) >= getDuration() {
  33. notifyLimitStore.Delete(key)
  34. }
  35. }
  36. return true
  37. })
  38. }
  39. })
  40. }
  41. // CheckNotificationLimit checks if the user has exceeded their notification limit
  42. // Returns true if the user can send notification, false if limit exceeded
  43. func CheckNotificationLimit(userId int, notifyType string) (bool, error) {
  44. if common.RedisEnabled {
  45. return checkRedisLimit(userId, notifyType)
  46. }
  47. return checkMemoryLimit(userId, notifyType)
  48. }
  49. func checkRedisLimit(userId int, notifyType string) (bool, error) {
  50. key := fmt.Sprintf("notify_limit:%d:%s:%s", userId, notifyType, time.Now().Format("2006010215"))
  51. // Get current count
  52. count, err := common.RedisGet(key)
  53. if err != nil && err.Error() != "redis: nil" {
  54. return false, fmt.Errorf("failed to get notification count: %w", err)
  55. }
  56. // If key doesn't exist, initialize it
  57. if count == "" {
  58. err = common.RedisSet(key, "1", getDuration())
  59. return true, err
  60. }
  61. currentCount, _ := strconv.Atoi(count)
  62. limit := constant.NotifyLimitCount
  63. // Check if limit is already reached
  64. if currentCount >= limit {
  65. return false, nil
  66. }
  67. // Only increment if under limit
  68. err = common.RedisIncr(key, 1)
  69. if err != nil {
  70. return false, fmt.Errorf("failed to increment notification count: %w", err)
  71. }
  72. return true, nil
  73. }
  74. func checkMemoryLimit(userId int, notifyType string) (bool, error) {
  75. // Ensure cleanup task is started
  76. cleanupOnce.Do(startCleanupTask)
  77. key := fmt.Sprintf("%d:%s:%s", userId, notifyType, time.Now().Format("2006010215"))
  78. now := time.Now()
  79. // Get current limit count or initialize new one
  80. var currentLimit limitCount
  81. if value, ok := notifyLimitStore.Load(key); ok {
  82. currentLimit = value.(limitCount)
  83. // Check if the entry has expired
  84. if now.Sub(currentLimit.Timestamp) >= getDuration() {
  85. currentLimit = limitCount{Count: 0, Timestamp: now}
  86. }
  87. } else {
  88. currentLimit = limitCount{Count: 0, Timestamp: now}
  89. }
  90. // Increment count
  91. currentLimit.Count++
  92. // Check against limits
  93. limit := constant.NotifyLimitCount
  94. // Store updated count
  95. notifyLimitStore.Store(key, currentLimit)
  96. return currentLimit.Count <= limit, nil
  97. }