user_cache.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. package model
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/gin-gonic/gin"
  6. "one-api/common"
  7. "one-api/constant"
  8. "time"
  9. "github.com/bytedance/gopkg/util/gopool"
  10. )
  11. // UserBase struct remains the same as it represents the cached data structure
  12. type UserBase struct {
  13. Id int `json:"id"`
  14. Group string `json:"group"`
  15. Email string `json:"email"`
  16. Quota int `json:"quota"`
  17. Status int `json:"status"`
  18. Username string `json:"username"`
  19. Setting string `json:"setting"`
  20. }
  21. func (user *UserBase) WriteContext(c *gin.Context) {
  22. c.Set(constant.ContextKeyUserGroup, user.Group)
  23. c.Set(constant.ContextKeyUserQuota, user.Quota)
  24. c.Set(constant.ContextKeyUserStatus, user.Status)
  25. c.Set(constant.ContextKeyUserEmail, user.Email)
  26. c.Set("username", user.Username)
  27. c.Set(constant.ContextKeyUserSetting, user.GetSetting())
  28. }
  29. func (user *UserBase) GetSetting() map[string]interface{} {
  30. if user.Setting == "" {
  31. return nil
  32. }
  33. return common.StrToMap(user.Setting)
  34. }
  35. func (user *UserBase) SetSetting(setting map[string]interface{}) {
  36. settingBytes, err := json.Marshal(setting)
  37. if err != nil {
  38. common.SysError("failed to marshal setting: " + err.Error())
  39. return
  40. }
  41. user.Setting = string(settingBytes)
  42. }
  43. // getUserCacheKey returns the key for user cache
  44. func getUserCacheKey(userId int) string {
  45. return fmt.Sprintf("user:%d", userId)
  46. }
  47. // invalidateUserCache clears user cache
  48. func invalidateUserCache(userId int) error {
  49. if !common.RedisEnabled {
  50. return nil
  51. }
  52. return common.RedisHDelObj(getUserCacheKey(userId))
  53. }
  54. // updateUserCache updates all user cache fields using hash
  55. func updateUserCache(user User) error {
  56. if !common.RedisEnabled {
  57. return nil
  58. }
  59. return common.RedisHSetObj(
  60. getUserCacheKey(user.Id),
  61. user.ToBaseUser(),
  62. time.Duration(constant.UserId2QuotaCacheSeconds)*time.Second,
  63. )
  64. }
  65. // GetUserCache gets complete user cache from hash
  66. func GetUserCache(userId int) (userCache *UserBase, 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. userCache, err = cacheGetUserBase(userId)
  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 = &UserBase{
  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. func cacheGetUserBase(userId int) (*UserBase, error) {
  103. if !common.RedisEnabled {
  104. return nil, fmt.Errorf("redis is not enabled")
  105. }
  106. var userCache UserBase
  107. // Try getting from Redis first
  108. err := common.RedisHGetObj(getUserCacheKey(userId), &userCache)
  109. if err != nil {
  110. return nil, err
  111. }
  112. return &userCache, nil
  113. }
  114. // Add atomic quota operations using hash fields
  115. func cacheIncrUserQuota(userId int, delta int64) error {
  116. if !common.RedisEnabled {
  117. return nil
  118. }
  119. return common.RedisHIncrBy(getUserCacheKey(userId), "Quota", delta)
  120. }
  121. func cacheDecrUserQuota(userId int, delta int64) error {
  122. return cacheIncrUserQuota(userId, -delta)
  123. }
  124. // Helper functions to get individual fields if needed
  125. func getUserGroupCache(userId int) (string, error) {
  126. cache, err := GetUserCache(userId)
  127. if err != nil {
  128. return "", err
  129. }
  130. return cache.Group, nil
  131. }
  132. func getUserQuotaCache(userId int) (int, error) {
  133. cache, err := GetUserCache(userId)
  134. if err != nil {
  135. return 0, err
  136. }
  137. return cache.Quota, nil
  138. }
  139. func getUserStatusCache(userId int) (int, error) {
  140. cache, err := GetUserCache(userId)
  141. if err != nil {
  142. return 0, err
  143. }
  144. return cache.Status, nil
  145. }
  146. func getUserNameCache(userId int) (string, error) {
  147. cache, err := GetUserCache(userId)
  148. if err != nil {
  149. return "", err
  150. }
  151. return cache.Username, nil
  152. }
  153. func getUserSettingCache(userId int) (map[string]interface{}, error) {
  154. setting := make(map[string]interface{})
  155. cache, err := GetUserCache(userId)
  156. if err != nil {
  157. return setting, err
  158. }
  159. return cache.GetSetting(), nil
  160. }
  161. // New functions for individual field updates
  162. func updateUserStatusCache(userId int, status bool) error {
  163. if !common.RedisEnabled {
  164. return nil
  165. }
  166. statusInt := common.UserStatusEnabled
  167. if !status {
  168. statusInt = common.UserStatusDisabled
  169. }
  170. return common.RedisHSetField(getUserCacheKey(userId), "Status", fmt.Sprintf("%d", statusInt))
  171. }
  172. func updateUserQuotaCache(userId int, quota int) error {
  173. if !common.RedisEnabled {
  174. return nil
  175. }
  176. return common.RedisHSetField(getUserCacheKey(userId), "Quota", fmt.Sprintf("%d", quota))
  177. }
  178. func updateUserGroupCache(userId int, group string) error {
  179. if !common.RedisEnabled {
  180. return nil
  181. }
  182. return common.RedisHSetField(getUserCacheKey(userId), "Group", group)
  183. }
  184. func updateUserNameCache(userId int, username string) error {
  185. if !common.RedisEnabled {
  186. return nil
  187. }
  188. return common.RedisHSetField(getUserCacheKey(userId), "Username", username)
  189. }
  190. func updateUserSettingCache(userId int, setting string) error {
  191. if !common.RedisEnabled {
  192. return nil
  193. }
  194. return common.RedisHSetField(getUserCacheKey(userId), "Setting", setting)
  195. }