cache.go 5.0 KB

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