user_cache.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. package model
  2. import (
  3. "fmt"
  4. "time"
  5. "github.com/QuantumNous/new-api/common"
  6. "github.com/QuantumNous/new-api/constant"
  7. "github.com/QuantumNous/new-api/dto"
  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.SysLog("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. // InvalidateUserCache is the exported version of invalidateUserCache.
  51. // 供 controller 等上层包在用户状态变更(如禁用、删除、角色变更)后主动清理缓存。
  52. func InvalidateUserCache(userId int) error {
  53. return invalidateUserCache(userId)
  54. }
  55. // updateUserCache updates all user cache fields using hash
  56. func updateUserCache(user User) error {
  57. if !common.RedisEnabled {
  58. return nil
  59. }
  60. return common.RedisHSetObj(
  61. getUserCacheKey(user.Id),
  62. user.ToBaseUser(),
  63. time.Duration(common.RedisKeyCacheSeconds())*time.Second,
  64. )
  65. }
  66. // GetUserCache gets complete user cache from hash
  67. func GetUserCache(userId int) (userCache *UserBase, err error) {
  68. var user *User
  69. var fromDB bool
  70. defer func() {
  71. // Update Redis cache asynchronously on successful DB read
  72. if shouldUpdateRedis(fromDB, err) && user != nil {
  73. gopool.Go(func() {
  74. if err := updateUserCache(*user); err != nil {
  75. common.SysLog("failed to update user status cache: " + err.Error())
  76. }
  77. })
  78. }
  79. }()
  80. // Try getting from Redis first
  81. userCache, err = cacheGetUserBase(userId)
  82. if err == nil {
  83. return userCache, nil
  84. }
  85. // If Redis fails, get from DB
  86. fromDB = true
  87. user, err = GetUserById(userId, false)
  88. if err != nil {
  89. return nil, err // Return nil and error if DB lookup fails
  90. }
  91. // Create cache object from user data
  92. userCache = &UserBase{
  93. Id: user.Id,
  94. Group: user.Group,
  95. Quota: user.Quota,
  96. Status: user.Status,
  97. Username: user.Username,
  98. Setting: user.Setting,
  99. Email: user.Email,
  100. }
  101. return userCache, nil
  102. }
  103. func cacheGetUserBase(userId int) (*UserBase, error) {
  104. if !common.RedisEnabled {
  105. return nil, fmt.Errorf("redis is not enabled")
  106. }
  107. var userCache UserBase
  108. // Try getting from Redis first
  109. err := common.RedisHGetObj(getUserCacheKey(userId), &userCache)
  110. if err != nil {
  111. return nil, err
  112. }
  113. return &userCache, nil
  114. }
  115. // Add atomic quota operations using hash fields
  116. func cacheIncrUserQuota(userId int, delta int64) error {
  117. if !common.RedisEnabled {
  118. return nil
  119. }
  120. return common.RedisHIncrBy(getUserCacheKey(userId), "Quota", delta)
  121. }
  122. func cacheDecrUserQuota(userId int, delta int64) error {
  123. return cacheIncrUserQuota(userId, -delta)
  124. }
  125. // Helper functions to get individual fields if needed
  126. func getUserGroupCache(userId int) (string, error) {
  127. cache, err := GetUserCache(userId)
  128. if err != nil {
  129. return "", err
  130. }
  131. return cache.Group, nil
  132. }
  133. func getUserQuotaCache(userId int) (int, error) {
  134. cache, err := GetUserCache(userId)
  135. if err != nil {
  136. return 0, err
  137. }
  138. return cache.Quota, nil
  139. }
  140. func getUserStatusCache(userId int) (int, error) {
  141. cache, err := GetUserCache(userId)
  142. if err != nil {
  143. return 0, err
  144. }
  145. return cache.Status, nil
  146. }
  147. func getUserNameCache(userId int) (string, error) {
  148. cache, err := GetUserCache(userId)
  149. if err != nil {
  150. return "", err
  151. }
  152. return cache.Username, nil
  153. }
  154. func getUserSettingCache(userId int) (dto.UserSetting, error) {
  155. cache, err := GetUserCache(userId)
  156. if err != nil {
  157. return dto.UserSetting{}, 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 UpdateUserGroupCache(userId int, group string) error {
  185. return updateUserGroupCache(userId, group)
  186. }
  187. func updateUserNameCache(userId int, username string) error {
  188. if !common.RedisEnabled {
  189. return nil
  190. }
  191. return common.RedisHSetField(getUserCacheKey(userId), "Username", username)
  192. }
  193. func updateUserSettingCache(userId int, setting string) error {
  194. if !common.RedisEnabled {
  195. return nil
  196. }
  197. return common.RedisHSetField(getUserCacheKey(userId), "Setting", setting)
  198. }
  199. // GetUserLanguage returns the user's language preference from cache
  200. // Uses the existing GetUserCache mechanism for efficiency
  201. func GetUserLanguage(userId int) string {
  202. userCache, err := GetUserCache(userId)
  203. if err != nil {
  204. return ""
  205. }
  206. return userCache.GetSetting().Language
  207. }