cache.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  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 CacheDecreaseUserQuota(id int, quota int) error {
  92. if !common.RedisEnabled {
  93. return nil
  94. }
  95. err := common.RedisDecrease(fmt.Sprintf("user_quota:%d", id), int64(quota))
  96. return err
  97. }
  98. func CacheIsUserEnabled(userId int) bool {
  99. if !common.RedisEnabled {
  100. return IsUserEnabled(userId)
  101. }
  102. enabled, err := common.RedisGet(fmt.Sprintf("user_enabled:%d", userId))
  103. if err != nil {
  104. status := common.UserStatusDisabled
  105. if IsUserEnabled(userId) {
  106. status = common.UserStatusEnabled
  107. }
  108. enabled = fmt.Sprintf("%d", status)
  109. err = common.RedisSet(fmt.Sprintf("user_enabled:%d", userId), enabled, time.Duration(UserId2StatusCacheSeconds)*time.Second)
  110. if err != nil {
  111. common.SysError("Redis set user enabled error: " + err.Error())
  112. }
  113. }
  114. return enabled == "1"
  115. }
  116. var group2model2channels map[string]map[string][]*Channel
  117. var channelSyncLock sync.RWMutex
  118. func InitChannelCache() {
  119. newChannelId2channel := make(map[int]*Channel)
  120. var channels []*Channel
  121. DB.Where("status = ?", common.ChannelStatusEnabled).Find(&channels)
  122. for _, channel := range channels {
  123. newChannelId2channel[channel.Id] = channel
  124. }
  125. var abilities []*Ability
  126. DB.Find(&abilities)
  127. groups := make(map[string]bool)
  128. for _, ability := range abilities {
  129. groups[ability.Group] = true
  130. }
  131. newGroup2model2channels := make(map[string]map[string][]*Channel)
  132. for group := range groups {
  133. newGroup2model2channels[group] = make(map[string][]*Channel)
  134. }
  135. for _, channel := range channels {
  136. groups := strings.Split(channel.Group, ",")
  137. for _, group := range groups {
  138. models := strings.Split(channel.Models, ",")
  139. for _, model := range models {
  140. if _, ok := newGroup2model2channels[group][model]; !ok {
  141. newGroup2model2channels[group][model] = make([]*Channel, 0)
  142. }
  143. newGroup2model2channels[group][model] = append(newGroup2model2channels[group][model], channel)
  144. }
  145. }
  146. }
  147. channelSyncLock.Lock()
  148. group2model2channels = newGroup2model2channels
  149. channelSyncLock.Unlock()
  150. common.SysLog("channels synced from database")
  151. }
  152. func SyncChannelCache(frequency int) {
  153. for {
  154. time.Sleep(time.Duration(frequency) * time.Second)
  155. common.SysLog("syncing channels from database")
  156. InitChannelCache()
  157. }
  158. }
  159. func CacheGetRandomSatisfiedChannel(group string, model string) (*Channel, error) {
  160. if !common.RedisEnabled {
  161. return GetRandomSatisfiedChannel(group, model)
  162. }
  163. channelSyncLock.RLock()
  164. defer channelSyncLock.RUnlock()
  165. channels := group2model2channels[group][model]
  166. if len(channels) == 0 {
  167. return nil, errors.New("channel not found")
  168. }
  169. idx := rand.Intn(len(channels))
  170. return channels[idx], nil
  171. }