user_cache.go 5.3 KB

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