cache.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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 channelsIDM map[int]*Channel
  127. var channelSyncLock sync.RWMutex
  128. func InitChannelCache() {
  129. newChannelId2channel := make(map[int]*Channel)
  130. var channels []*Channel
  131. DB.Where("status = ?", common.ChannelStatusEnabled).Find(&channels)
  132. for _, channel := range channels {
  133. newChannelId2channel[channel.Id] = channel
  134. }
  135. var abilities []*Ability
  136. DB.Find(&abilities)
  137. groups := make(map[string]bool)
  138. for _, ability := range abilities {
  139. groups[ability.Group] = true
  140. }
  141. newGroup2model2channels := make(map[string]map[string][]*Channel)
  142. newChannelsIDM := make(map[int]*Channel)
  143. for group := range groups {
  144. newGroup2model2channels[group] = make(map[string][]*Channel)
  145. }
  146. for _, channel := range channels {
  147. newChannelsIDM[channel.Id] = channel
  148. groups := strings.Split(channel.Group, ",")
  149. for _, group := range groups {
  150. models := strings.Split(channel.Models, ",")
  151. for _, model := range models {
  152. if _, ok := newGroup2model2channels[group][model]; !ok {
  153. newGroup2model2channels[group][model] = make([]*Channel, 0)
  154. }
  155. newGroup2model2channels[group][model] = append(newGroup2model2channels[group][model], channel)
  156. }
  157. }
  158. }
  159. // sort by priority
  160. for group, model2channels := range newGroup2model2channels {
  161. for model, channels := range model2channels {
  162. sort.Slice(channels, func(i, j int) bool {
  163. return channels[i].GetPriority() > channels[j].GetPriority()
  164. })
  165. newGroup2model2channels[group][model] = channels
  166. }
  167. }
  168. channelSyncLock.Lock()
  169. group2model2channels = newGroup2model2channels
  170. channelsIDM = newChannelsIDM
  171. channelSyncLock.Unlock()
  172. common.SysLog("channels synced from database")
  173. }
  174. func SyncChannelCache(frequency int) {
  175. for {
  176. time.Sleep(time.Duration(frequency) * time.Second)
  177. common.SysLog("syncing channels from database")
  178. InitChannelCache()
  179. }
  180. }
  181. func CacheGetRandomSatisfiedChannel(group string, model string) (*Channel, error) {
  182. if strings.HasPrefix(model, "gpt-4-gizmo") {
  183. model = "gpt-4-gizmo-*"
  184. }
  185. if !common.MemoryCacheEnabled {
  186. return GetRandomSatisfiedChannel(group, model)
  187. }
  188. channelSyncLock.RLock()
  189. defer channelSyncLock.RUnlock()
  190. channels := group2model2channels[group][model]
  191. if len(channels) == 0 {
  192. return nil, errors.New("channel not found")
  193. }
  194. endIdx := len(channels)
  195. // choose by priority
  196. firstChannel := channels[0]
  197. if firstChannel.GetPriority() > 0 {
  198. for i := range channels {
  199. if channels[i].GetPriority() != firstChannel.GetPriority() {
  200. endIdx = i
  201. break
  202. }
  203. }
  204. }
  205. idx := rand.Intn(endIdx)
  206. return channels[idx], nil
  207. }
  208. func CacheGetChannel(id int) (*Channel, error) {
  209. if !common.MemoryCacheEnabled {
  210. return GetChannelById(id, true)
  211. }
  212. channelSyncLock.RLock()
  213. defer channelSyncLock.RUnlock()
  214. c, ok := channelsIDM[id]
  215. if !ok {
  216. return nil, errors.New(fmt.Sprintf("当前渠道# %d,已不存在", id))
  217. }
  218. return c, nil
  219. }