user_cache.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. package model
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "one-api/common"
  6. "one-api/constant"
  7. "time"
  8. "github.com/bytedance/gopkg/util/gopool"
  9. )
  10. // UserBase struct remains the same as it represents the cached data structure
  11. type UserBase struct {
  12. Id int `json:"id"`
  13. Group string `json:"group"`
  14. Email string `json:"email"`
  15. Quota int `json:"quota"`
  16. Status int `json:"status"`
  17. Username string `json:"username"`
  18. Setting string `json:"setting"`
  19. }
  20. func (user *UserBase) GetSetting() map[string]interface{} {
  21. if user.Setting == "" {
  22. return nil
  23. }
  24. return common.StrToMap(user.Setting)
  25. }
  26. func (user *UserBase) SetSetting(setting map[string]interface{}) {
  27. settingBytes, err := json.Marshal(setting)
  28. if err != nil {
  29. common.SysError("failed to marshal setting: " + err.Error())
  30. return
  31. }
  32. user.Setting = string(settingBytes)
  33. }
  34. // getUserCacheKey returns the key for user cache
  35. func getUserCacheKey(userId int) string {
  36. return fmt.Sprintf("user:%d", userId)
  37. }
  38. // invalidateUserCache clears user cache
  39. func invalidateUserCache(userId int) error {
  40. if !common.RedisEnabled {
  41. return nil
  42. }
  43. return common.RedisHDelObj(getUserCacheKey(userId))
  44. }
  45. // updateUserCache updates all user cache fields using hash
  46. func updateUserCache(user User) error {
  47. if !common.RedisEnabled {
  48. return nil
  49. }
  50. return common.RedisHSetObj(
  51. getUserCacheKey(user.Id),
  52. user.ToBaseUser(),
  53. time.Duration(constant.UserId2QuotaCacheSeconds)*time.Second,
  54. )
  55. }
  56. // GetUserCache gets complete user cache from hash
  57. func GetUserCache(userId int) (userCache *UserBase, err error) {
  58. var user *User
  59. var fromDB bool
  60. defer func() {
  61. // Update Redis cache asynchronously on successful DB read
  62. if shouldUpdateRedis(fromDB, err) && user != nil {
  63. gopool.Go(func() {
  64. if err := updateUserCache(*user); err != nil {
  65. common.SysError("failed to update user status cache: " + err.Error())
  66. }
  67. })
  68. }
  69. }()
  70. // Try getting from Redis first
  71. err = common.RedisHGetObj(getUserCacheKey(userId), &userCache)
  72. if err == nil {
  73. return userCache, nil
  74. }
  75. // If Redis fails, get from DB
  76. fromDB = true
  77. user, err = GetUserById(userId, false)
  78. if err != nil {
  79. return nil, err // Return nil and error if DB lookup fails
  80. }
  81. // Create cache object from user data
  82. userCache = &UserBase{
  83. Id: user.Id,
  84. Group: user.Group,
  85. Quota: user.Quota,
  86. Status: user.Status,
  87. Username: user.Username,
  88. Setting: user.Setting,
  89. Email: user.Email,
  90. }
  91. return userCache, nil
  92. }
  93. // Add atomic quota operations using hash fields
  94. func cacheIncrUserQuota(userId int, delta int64) error {
  95. if !common.RedisEnabled {
  96. return nil
  97. }
  98. return common.RedisHIncrBy(getUserCacheKey(userId), "Quota", delta)
  99. }
  100. func cacheDecrUserQuota(userId int, delta int64) error {
  101. return cacheIncrUserQuota(userId, -delta)
  102. }
  103. // Helper functions to get individual fields if needed
  104. func getUserGroupCache(userId int) (string, error) {
  105. cache, err := GetUserCache(userId)
  106. if err != nil {
  107. return "", err
  108. }
  109. return cache.Group, nil
  110. }
  111. func getUserQuotaCache(userId int) (int, error) {
  112. cache, err := GetUserCache(userId)
  113. if err != nil {
  114. return 0, err
  115. }
  116. return cache.Quota, nil
  117. }
  118. func getUserStatusCache(userId int) (int, error) {
  119. cache, err := GetUserCache(userId)
  120. if err != nil {
  121. return 0, err
  122. }
  123. return cache.Status, nil
  124. }
  125. func getUserNameCache(userId int) (string, error) {
  126. cache, err := GetUserCache(userId)
  127. if err != nil {
  128. return "", err
  129. }
  130. return cache.Username, nil
  131. }
  132. func getUserSettingCache(userId int) (map[string]interface{}, error) {
  133. setting := make(map[string]interface{})
  134. cache, err := GetUserCache(userId)
  135. if err != nil {
  136. return setting, err
  137. }
  138. return cache.GetSetting(), nil
  139. }
  140. // New functions for individual field updates
  141. func updateUserStatusCache(userId int, status bool) error {
  142. if !common.RedisEnabled {
  143. return nil
  144. }
  145. statusInt := common.UserStatusEnabled
  146. if !status {
  147. statusInt = common.UserStatusDisabled
  148. }
  149. return common.RedisHSetField(getUserCacheKey(userId), "Status", fmt.Sprintf("%d", statusInt))
  150. }
  151. func updateUserQuotaCache(userId int, quota int) error {
  152. if !common.RedisEnabled {
  153. return nil
  154. }
  155. return common.RedisHSetField(getUserCacheKey(userId), "Quota", fmt.Sprintf("%d", quota))
  156. }
  157. func updateUserGroupCache(userId int, group string) error {
  158. if !common.RedisEnabled {
  159. return nil
  160. }
  161. return common.RedisHSetField(getUserCacheKey(userId), "Group", group)
  162. }
  163. func updateUserNameCache(userId int, username string) error {
  164. if !common.RedisEnabled {
  165. return nil
  166. }
  167. return common.RedisHSetField(getUserCacheKey(userId), "Username", username)
  168. }
  169. func updateUserSettingCache(userId int, setting string) error {
  170. if !common.RedisEnabled {
  171. return nil
  172. }
  173. return common.RedisHSetField(getUserCacheKey(userId), "Setting", setting)
  174. }