1
0

user_cache.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. package model
  2. import (
  3. "fmt"
  4. "one-api/common"
  5. "one-api/constant"
  6. "one-api/dto"
  7. "time"
  8. "github.com/gin-gonic/gin"
  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. common.SetContextKey(c, constant.ContextKeyUserGroup, user.Group)
  23. common.SetContextKey(c, constant.ContextKeyUserQuota, user.Quota)
  24. common.SetContextKey(c, constant.ContextKeyUserStatus, user.Status)
  25. common.SetContextKey(c, constant.ContextKeyUserEmail, user.Email)
  26. common.SetContextKey(c, constant.ContextKeyUserName, user.Username)
  27. common.SetContextKey(c, constant.ContextKeyUserSetting, user.GetSetting())
  28. }
  29. func (user *UserBase) GetSetting() dto.UserSetting {
  30. setting := dto.UserSetting{}
  31. if user.Setting != "" {
  32. err := common.Unmarshal([]byte(user.Setting), &setting)
  33. if err != nil {
  34. common.SysError("failed to unmarshal setting: " + err.Error())
  35. }
  36. }
  37. return setting
  38. }
  39. // getUserCacheKey returns the key for user cache
  40. func getUserCacheKey(userId int) string {
  41. return fmt.Sprintf("user:%d", userId)
  42. }
  43. // invalidateUserCache clears user cache
  44. func invalidateUserCache(userId int) error {
  45. if !common.RedisEnabled {
  46. return nil
  47. }
  48. return common.RedisDelKey(getUserCacheKey(userId))
  49. }
  50. // updateUserCache updates all user cache fields using hash
  51. func updateUserCache(user User) error {
  52. if !common.RedisEnabled {
  53. return nil
  54. }
  55. return common.RedisHSetObj(
  56. getUserCacheKey(user.Id),
  57. user.ToBaseUser(),
  58. time.Duration(common.RedisKeyCacheSeconds())*time.Second,
  59. )
  60. }
  61. // GetUserCache gets complete user cache from hash
  62. func GetUserCache(userId int) (userCache *UserBase, err error) {
  63. var user *User
  64. var fromDB bool
  65. defer func() {
  66. // Update Redis cache asynchronously on successful DB read
  67. if shouldUpdateRedis(fromDB, err) && user != nil {
  68. gopool.Go(func() {
  69. if err := updateUserCache(*user); err != nil {
  70. common.SysError("failed to update user status cache: " + err.Error())
  71. }
  72. })
  73. }
  74. }()
  75. // Try getting from Redis first
  76. userCache, err = cacheGetUserBase(userId)
  77. if err == nil {
  78. return userCache, nil
  79. }
  80. // If Redis fails, get from DB
  81. fromDB = true
  82. user, err = GetUserById(userId, false)
  83. if err != nil {
  84. return nil, err // Return nil and error if DB lookup fails
  85. }
  86. // Create cache object from user data
  87. userCache = &UserBase{
  88. Id: user.Id,
  89. Group: user.Group,
  90. Quota: user.Quota,
  91. Status: user.Status,
  92. Username: user.Username,
  93. Setting: user.Setting,
  94. Email: user.Email,
  95. }
  96. return userCache, nil
  97. }
  98. func cacheGetUserBase(userId int) (*UserBase, error) {
  99. if !common.RedisEnabled {
  100. return nil, fmt.Errorf("redis is not enabled")
  101. }
  102. var userCache UserBase
  103. // Try getting from Redis first
  104. err := common.RedisHGetObj(getUserCacheKey(userId), &userCache)
  105. if err != nil {
  106. return nil, err
  107. }
  108. return &userCache, nil
  109. }
  110. // Add atomic quota operations using hash fields
  111. func cacheIncrUserQuota(userId int, delta int64) error {
  112. if !common.RedisEnabled {
  113. return nil
  114. }
  115. return common.RedisHIncrBy(getUserCacheKey(userId), "Quota", delta)
  116. }
  117. func cacheDecrUserQuota(userId int, delta int64) error {
  118. return cacheIncrUserQuota(userId, -delta)
  119. }
  120. // Helper functions to get individual fields if needed
  121. func getUserGroupCache(userId int) (string, error) {
  122. cache, err := GetUserCache(userId)
  123. if err != nil {
  124. return "", err
  125. }
  126. return cache.Group, nil
  127. }
  128. func getUserQuotaCache(userId int) (int, error) {
  129. cache, err := GetUserCache(userId)
  130. if err != nil {
  131. return 0, err
  132. }
  133. return cache.Quota, nil
  134. }
  135. func getUserStatusCache(userId int) (int, error) {
  136. cache, err := GetUserCache(userId)
  137. if err != nil {
  138. return 0, err
  139. }
  140. return cache.Status, nil
  141. }
  142. func getUserNameCache(userId int) (string, error) {
  143. cache, err := GetUserCache(userId)
  144. if err != nil {
  145. return "", err
  146. }
  147. return cache.Username, nil
  148. }
  149. func getUserSettingCache(userId int) (dto.UserSetting, error) {
  150. cache, err := GetUserCache(userId)
  151. if err != nil {
  152. return dto.UserSetting{}, err
  153. }
  154. return cache.GetSetting(), nil
  155. }
  156. // New functions for individual field updates
  157. func updateUserStatusCache(userId int, status bool) error {
  158. if !common.RedisEnabled {
  159. return nil
  160. }
  161. statusInt := common.UserStatusEnabled
  162. if !status {
  163. statusInt = common.UserStatusDisabled
  164. }
  165. return common.RedisHSetField(getUserCacheKey(userId), "Status", fmt.Sprintf("%d", statusInt))
  166. }
  167. func updateUserQuotaCache(userId int, quota int) error {
  168. if !common.RedisEnabled {
  169. return nil
  170. }
  171. return common.RedisHSetField(getUserCacheKey(userId), "Quota", fmt.Sprintf("%d", quota))
  172. }
  173. func updateUserGroupCache(userId int, group string) error {
  174. if !common.RedisEnabled {
  175. return nil
  176. }
  177. return common.RedisHSetField(getUserCacheKey(userId), "Group", group)
  178. }
  179. func updateUserNameCache(userId int, username string) error {
  180. if !common.RedisEnabled {
  181. return nil
  182. }
  183. return common.RedisHSetField(getUserCacheKey(userId), "Username", username)
  184. }
  185. func updateUserSettingCache(userId int, setting string) error {
  186. if !common.RedisEnabled {
  187. return nil
  188. }
  189. return common.RedisHSetField(getUserCacheKey(userId), "Setting", setting)
  190. }