cache.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  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. const (
  14. TokenCacheSeconds = 60 * 60
  15. UserId2GroupCacheSeconds = 60 * 60
  16. UserId2QuotaCacheSeconds = 10 * 60
  17. UserId2StatusCacheSeconds = 60 * 60
  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), 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, 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), 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 CacheIsUserEnabled(userId int) bool {
  81. if !common.RedisEnabled {
  82. return IsUserEnabled(userId)
  83. }
  84. enabled, err := common.RedisGet(fmt.Sprintf("user_enabled:%d", userId))
  85. if err != nil {
  86. status := common.UserStatusDisabled
  87. if IsUserEnabled(userId) {
  88. status = common.UserStatusEnabled
  89. }
  90. enabled = fmt.Sprintf("%d", status)
  91. err = common.RedisSet(fmt.Sprintf("user_enabled:%d", userId), enabled, UserId2StatusCacheSeconds*time.Second)
  92. if err != nil {
  93. common.SysError("Redis set user enabled error: " + err.Error())
  94. }
  95. }
  96. return enabled == "1"
  97. }
  98. var group2model2channels map[string]map[string][]*Channel
  99. var channelSyncLock sync.RWMutex
  100. func InitChannelCache() {
  101. newChannelId2channel := make(map[int]*Channel)
  102. var channels []*Channel
  103. DB.Find(&channels)
  104. for _, channel := range channels {
  105. newChannelId2channel[channel.Id] = channel
  106. }
  107. var abilities []*Ability
  108. DB.Find(&abilities)
  109. groups := make(map[string]bool)
  110. for _, ability := range abilities {
  111. groups[ability.Group] = true
  112. }
  113. newGroup2model2channels := make(map[string]map[string][]*Channel)
  114. for group := range groups {
  115. newGroup2model2channels[group] = make(map[string][]*Channel)
  116. }
  117. for _, channel := range channels {
  118. groups := strings.Split(channel.Group, ",")
  119. for _, group := range groups {
  120. models := strings.Split(channel.Models, ",")
  121. for _, model := range models {
  122. if _, ok := newGroup2model2channels[group][model]; !ok {
  123. newGroup2model2channels[group][model] = make([]*Channel, 0)
  124. }
  125. newGroup2model2channels[group][model] = append(newGroup2model2channels[group][model], channel)
  126. }
  127. }
  128. }
  129. channelSyncLock.Lock()
  130. group2model2channels = newGroup2model2channels
  131. channelSyncLock.Unlock()
  132. common.SysLog("Channels synced from database")
  133. }
  134. func SyncChannelCache(frequency int) {
  135. for {
  136. time.Sleep(time.Duration(frequency) * time.Second)
  137. common.SysLog("Syncing channels from database")
  138. InitChannelCache()
  139. }
  140. }
  141. func CacheGetRandomSatisfiedChannel(group string, model string) (*Channel, error) {
  142. if !common.RedisEnabled {
  143. return GetRandomSatisfiedChannel(group, model)
  144. }
  145. channelSyncLock.RLock()
  146. defer channelSyncLock.RUnlock()
  147. channels := group2model2channels[group][model]
  148. if len(channels) == 0 {
  149. return nil, errors.New("channel not found")
  150. }
  151. idx := rand.Intn(len(channels))
  152. return channels[idx], nil
  153. }