user_cache.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  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. // UserCache struct remains the same as it represents the cached data structure
  11. type UserCache 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 *UserCache) GetSetting() map[string]interface{} {
  21. if user.Setting == "" {
  22. return nil
  23. }
  24. return common.StrToMap(user.Setting)
  25. }
  26. func (user *UserCache) 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. cache := &UserCache{
  51. Id: user.Id,
  52. Group: user.Group,
  53. Quota: user.Quota,
  54. Status: user.Status,
  55. Username: user.Username,
  56. Setting: user.Setting,
  57. Email: user.Email,
  58. }
  59. return common.RedisHSetObj(
  60. getUserCacheKey(user.Id),
  61. cache,
  62. time.Duration(constant.UserId2QuotaCacheSeconds)*time.Second,
  63. )
  64. }
  65. // GetUserCache gets complete user cache from hash
  66. func GetUserCache(userId int) (userCache *UserCache, err error) {
  67. var user *User
  68. var fromDB bool
  69. defer func() {
  70. // Update Redis cache asynchronously on successful DB read
  71. if shouldUpdateRedis(fromDB, err) && user != nil {
  72. gopool.Go(func() {
  73. if err := updateUserCache(*user); err != nil {
  74. common.SysError("failed to update user status cache: " + err.Error())
  75. }
  76. })
  77. }
  78. }()
  79. // Try getting from Redis first
  80. err = common.RedisHGetObj(getUserCacheKey(userId), &userCache)
  81. if err == nil {
  82. return userCache, nil
  83. }
  84. // If Redis fails, get from DB
  85. fromDB = true
  86. user, err = GetUserById(userId, false)
  87. if err != nil {
  88. return nil, err // Return nil and error if DB lookup fails
  89. }
  90. // Create cache object from user data
  91. userCache = &UserCache{
  92. Id: user.Id,
  93. Group: user.Group,
  94. Quota: user.Quota,
  95. Status: user.Status,
  96. Username: user.Username,
  97. Setting: user.Setting,
  98. Email: user.Email,
  99. }
  100. return userCache, nil
  101. }
  102. // Add atomic quota operations using hash fields
  103. func cacheIncrUserQuota(userId int, delta int64) error {
  104. if !common.RedisEnabled {
  105. return nil
  106. }
  107. return common.RedisHIncrBy(getUserCacheKey(userId), "Quota", delta)
  108. }
  109. func cacheDecrUserQuota(userId int, delta int64) error {
  110. return cacheIncrUserQuota(userId, -delta)
  111. }
  112. // Helper functions to get individual fields if needed
  113. func getUserGroupCache(userId int) (string, error) {
  114. cache, err := GetUserCache(userId)
  115. if err != nil {
  116. return "", err
  117. }
  118. return cache.Group, nil
  119. }
  120. func getUserQuotaCache(userId int) (int, error) {
  121. cache, err := GetUserCache(userId)
  122. if err != nil {
  123. return 0, err
  124. }
  125. return cache.Quota, nil
  126. }
  127. func getUserStatusCache(userId int) (int, error) {
  128. cache, err := GetUserCache(userId)
  129. if err != nil {
  130. return 0, err
  131. }
  132. return cache.Status, nil
  133. }
  134. func getUserNameCache(userId int) (string, error) {
  135. cache, err := GetUserCache(userId)
  136. if err != nil {
  137. return "", err
  138. }
  139. return cache.Username, nil
  140. }
  141. func getUserSettingCache(userId int) (map[string]interface{}, error) {
  142. setting := make(map[string]interface{})
  143. cache, err := GetUserCache(userId)
  144. if err != nil {
  145. return setting, err
  146. }
  147. return cache.GetSetting(), nil
  148. }
  149. // New functions for individual field updates
  150. func updateUserStatusCache(userId int, status bool) error {
  151. if !common.RedisEnabled {
  152. return nil
  153. }
  154. statusInt := common.UserStatusEnabled
  155. if !status {
  156. statusInt = common.UserStatusDisabled
  157. }
  158. return common.RedisHSetField(getUserCacheKey(userId), "Status", fmt.Sprintf("%d", statusInt))
  159. }
  160. func updateUserQuotaCache(userId int, quota int) error {
  161. if !common.RedisEnabled {
  162. return nil
  163. }
  164. return common.RedisHSetField(getUserCacheKey(userId), "Quota", fmt.Sprintf("%d", quota))
  165. }
  166. func updateUserGroupCache(userId int, group string) error {
  167. if !common.RedisEnabled {
  168. return nil
  169. }
  170. return common.RedisHSetField(getUserCacheKey(userId), "Group", group)
  171. }
  172. func updateUserNameCache(userId int, username string) error {
  173. if !common.RedisEnabled {
  174. return nil
  175. }
  176. return common.RedisHSetField(getUserCacheKey(userId), "Username", username)
  177. }
  178. func updateUserSettingCache(userId int, setting string) error {
  179. if !common.RedisEnabled {
  180. return nil
  181. }
  182. return common.RedisHSetField(getUserCacheKey(userId), "Setting", setting)
  183. }