cache.go 5.6 KB

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