user_cache.go 5.6 KB

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