cache.go 5.4 KB

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