cache.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. package model
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "math/rand"
  7. "one-api/common"
  8. "strconv"
  9. "strings"
  10. "sync"
  11. "time"
  12. )
  13. var (
  14. TokenCacheSeconds = common.SyncFrequency
  15. UserId2GroupCacheSeconds = common.SyncFrequency
  16. UserId2QuotaCacheSeconds = common.SyncFrequency
  17. UserId2StatusCacheSeconds = common.SyncFrequency
  18. )
  19. func CacheGetTokenByKey(key string) (*Token, error) {
  20. var token Token
  21. if !common.RedisEnabled {
  22. err := DB.Where("`key` = ?", key).First(&token).Error
  23. return &token, err
  24. }
  25. tokenObjectString, err := common.RedisGet(fmt.Sprintf("token:%s", key))
  26. if err != nil {
  27. err := DB.Where("`key` = ?", key).First(&token).Error
  28. if err != nil {
  29. return nil, err
  30. }
  31. jsonBytes, err := json.Marshal(token)
  32. if err != nil {
  33. return nil, err
  34. }
  35. err = common.RedisSet(fmt.Sprintf("token:%s", key), string(jsonBytes), time.Duration(TokenCacheSeconds)*time.Second)
  36. if err != nil {
  37. common.SysError("Redis set token error: " + err.Error())
  38. }
  39. return &token, nil
  40. }
  41. err = json.Unmarshal([]byte(tokenObjectString), &token)
  42. return &token, err
  43. }
  44. func CacheGetUserGroup(id int) (group string, err error) {
  45. if !common.RedisEnabled {
  46. return GetUserGroup(id)
  47. }
  48. group, err = common.RedisGet(fmt.Sprintf("user_group:%d", id))
  49. if err != nil {
  50. group, err = GetUserGroup(id)
  51. if err != nil {
  52. return "", err
  53. }
  54. err = common.RedisSet(fmt.Sprintf("user_group:%d", id), group, time.Duration(UserId2GroupCacheSeconds)*time.Second)
  55. if err != nil {
  56. common.SysError("Redis set user group error: " + err.Error())
  57. }
  58. }
  59. return group, err
  60. }
  61. func CacheGetUserQuota(id int) (quota int, err error) {
  62. if !common.RedisEnabled {
  63. return GetUserQuota(id)
  64. }
  65. quotaString, err := common.RedisGet(fmt.Sprintf("user_quota:%d", id))
  66. if err != nil {
  67. quota, err = GetUserQuota(id)
  68. if err != nil {
  69. return 0, err
  70. }
  71. err = common.RedisSet(fmt.Sprintf("user_quota:%d", id), fmt.Sprintf("%d", quota), time.Duration(UserId2QuotaCacheSeconds)*time.Second)
  72. if err != nil {
  73. common.SysError("Redis set user quota error: " + err.Error())
  74. }
  75. return quota, err
  76. }
  77. quota, err = strconv.Atoi(quotaString)
  78. return quota, err
  79. }
  80. func CacheUpdateUserQuota(id int) error {
  81. if !common.RedisEnabled {
  82. return nil
  83. }
  84. quota, err := GetUserQuota(id)
  85. if err != nil {
  86. return err
  87. }
  88. err = common.RedisSet(fmt.Sprintf("user_quota:%d", id), fmt.Sprintf("%d", quota), time.Duration(UserId2QuotaCacheSeconds)*time.Second)
  89. return err
  90. }
  91. func CacheIsUserEnabled(userId int) bool {
  92. if !common.RedisEnabled {
  93. return IsUserEnabled(userId)
  94. }
  95. enabled, err := common.RedisGet(fmt.Sprintf("user_enabled:%d", userId))
  96. if err != nil {
  97. status := common.UserStatusDisabled
  98. if IsUserEnabled(userId) {
  99. status = common.UserStatusEnabled
  100. }
  101. enabled = fmt.Sprintf("%d", status)
  102. err = common.RedisSet(fmt.Sprintf("user_enabled:%d", userId), enabled, time.Duration(UserId2StatusCacheSeconds)*time.Second)
  103. if err != nil {
  104. common.SysError("Redis set user enabled error: " + err.Error())
  105. }
  106. }
  107. return enabled == "1"
  108. }
  109. var group2model2channels map[string]map[string][]*Channel
  110. var channelSyncLock sync.RWMutex
  111. func InitChannelCache() {
  112. newChannelId2channel := make(map[int]*Channel)
  113. var channels []*Channel
  114. DB.Where("status = ?", common.ChannelStatusEnabled).Find(&channels)
  115. for _, channel := range channels {
  116. newChannelId2channel[channel.Id] = channel
  117. }
  118. var abilities []*Ability
  119. DB.Find(&abilities)
  120. groups := make(map[string]bool)
  121. for _, ability := range abilities {
  122. groups[ability.Group] = true
  123. }
  124. newGroup2model2channels := make(map[string]map[string][]*Channel)
  125. for group := range groups {
  126. newGroup2model2channels[group] = make(map[string][]*Channel)
  127. }
  128. for _, channel := range channels {
  129. groups := strings.Split(channel.Group, ",")
  130. for _, group := range groups {
  131. models := strings.Split(channel.Models, ",")
  132. for _, model := range models {
  133. if _, ok := newGroup2model2channels[group][model]; !ok {
  134. newGroup2model2channels[group][model] = make([]*Channel, 0)
  135. }
  136. newGroup2model2channels[group][model] = append(newGroup2model2channels[group][model], channel)
  137. }
  138. }
  139. }
  140. channelSyncLock.Lock()
  141. group2model2channels = newGroup2model2channels
  142. channelSyncLock.Unlock()
  143. common.SysLog("channels synced from database")
  144. }
  145. func SyncChannelCache(frequency int) {
  146. for {
  147. time.Sleep(time.Duration(frequency) * time.Second)
  148. common.SysLog("syncing channels from database")
  149. InitChannelCache()
  150. }
  151. }
  152. func CacheGetRandomSatisfiedChannel(group string, model string) (*Channel, error) {
  153. if !common.RedisEnabled {
  154. return GetRandomSatisfiedChannel(group, model)
  155. }
  156. channelSyncLock.RLock()
  157. defer channelSyncLock.RUnlock()
  158. channels := group2model2channels[group][model]
  159. if len(channels) == 0 {
  160. return nil, errors.New("channel not found")
  161. }
  162. idx := rand.Intn(len(channels))
  163. return channels[idx], nil
  164. }