cache.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. package model
  2. import (
  3. "errors"
  4. "fmt"
  5. "math/rand"
  6. "one-api/common"
  7. "sort"
  8. "strings"
  9. "sync"
  10. "time"
  11. )
  12. var group2model2channels map[string]map[string][]*Channel
  13. var channelsIDM map[int]*Channel
  14. var channelSyncLock sync.RWMutex
  15. func InitChannelCache() {
  16. newChannelId2channel := make(map[int]*Channel)
  17. var channels []*Channel
  18. DB.Where("status = ?", common.ChannelStatusEnabled).Find(&channels)
  19. for _, channel := range channels {
  20. newChannelId2channel[channel.Id] = channel
  21. }
  22. var abilities []*Ability
  23. DB.Find(&abilities)
  24. groups := make(map[string]bool)
  25. for _, ability := range abilities {
  26. groups[ability.Group] = true
  27. }
  28. newGroup2model2channels := make(map[string]map[string][]*Channel)
  29. newChannelsIDM := make(map[int]*Channel)
  30. for group := range groups {
  31. newGroup2model2channels[group] = make(map[string][]*Channel)
  32. }
  33. for _, channel := range channels {
  34. newChannelsIDM[channel.Id] = channel
  35. groups := strings.Split(channel.Group, ",")
  36. for _, group := range groups {
  37. models := strings.Split(channel.Models, ",")
  38. for _, model := range models {
  39. if _, ok := newGroup2model2channels[group][model]; !ok {
  40. newGroup2model2channels[group][model] = make([]*Channel, 0)
  41. }
  42. newGroup2model2channels[group][model] = append(newGroup2model2channels[group][model], channel)
  43. }
  44. }
  45. }
  46. // sort by priority
  47. for group, model2channels := range newGroup2model2channels {
  48. for model, channels := range model2channels {
  49. sort.Slice(channels, func(i, j int) bool {
  50. return channels[i].GetPriority() > channels[j].GetPriority()
  51. })
  52. newGroup2model2channels[group][model] = channels
  53. }
  54. }
  55. channelSyncLock.Lock()
  56. group2model2channels = newGroup2model2channels
  57. channelsIDM = newChannelsIDM
  58. channelSyncLock.Unlock()
  59. common.SysLog("channels synced from database")
  60. }
  61. func SyncChannelCache(frequency int) {
  62. for {
  63. time.Sleep(time.Duration(frequency) * time.Second)
  64. common.SysLog("syncing channels from database")
  65. InitChannelCache()
  66. }
  67. }
  68. func CacheGetRandomSatisfiedChannel(group string, model string, retry int) (*Channel, error) {
  69. if strings.HasPrefix(model, "gpt-4-gizmo") {
  70. model = "gpt-4-gizmo-*"
  71. }
  72. if strings.HasPrefix(model, "gpt-4o-gizmo") {
  73. model = "gpt-4o-gizmo-*"
  74. }
  75. // if memory cache is disabled, get channel directly from database
  76. if !common.MemoryCacheEnabled {
  77. return GetRandomSatisfiedChannel(group, model, retry)
  78. }
  79. channelSyncLock.RLock()
  80. channels := group2model2channels[group][model]
  81. channelSyncLock.RUnlock()
  82. if len(channels) == 0 {
  83. return nil, errors.New("channel not found")
  84. }
  85. uniquePriorities := make(map[int]bool)
  86. for _, channel := range channels {
  87. uniquePriorities[int(channel.GetPriority())] = true
  88. }
  89. var sortedUniquePriorities []int
  90. for priority := range uniquePriorities {
  91. sortedUniquePriorities = append(sortedUniquePriorities, priority)
  92. }
  93. sort.Sort(sort.Reverse(sort.IntSlice(sortedUniquePriorities)))
  94. if retry >= len(uniquePriorities) {
  95. retry = len(uniquePriorities) - 1
  96. }
  97. targetPriority := int64(sortedUniquePriorities[retry])
  98. // get the priority for the given retry number
  99. var targetChannels []*Channel
  100. for _, channel := range channels {
  101. if channel.GetPriority() == targetPriority {
  102. targetChannels = append(targetChannels, channel)
  103. }
  104. }
  105. // 平滑系数
  106. smoothingFactor := 10
  107. // Calculate the total weight of all channels up to endIdx
  108. totalWeight := 0
  109. for _, channel := range targetChannels {
  110. totalWeight += channel.GetWeight() + smoothingFactor
  111. }
  112. // Generate a random value in the range [0, totalWeight)
  113. randomWeight := rand.Intn(totalWeight)
  114. // Find a channel based on its weight
  115. for _, channel := range targetChannels {
  116. randomWeight -= channel.GetWeight() + smoothingFactor
  117. if randomWeight < 0 {
  118. return channel, nil
  119. }
  120. }
  121. // return null if no channel is not found
  122. return nil, errors.New("channel not found")
  123. }
  124. func CacheGetChannel(id int) (*Channel, error) {
  125. if !common.MemoryCacheEnabled {
  126. return GetChannelById(id, true)
  127. }
  128. channelSyncLock.RLock()
  129. defer channelSyncLock.RUnlock()
  130. c, ok := channelsIDM[id]
  131. if !ok {
  132. return nil, errors.New(fmt.Sprintf("当前渠道# %d,已不存在", id))
  133. }
  134. return c, nil
  135. }
  136. func CacheUpdateChannelStatus(id int, status int) {
  137. if !common.MemoryCacheEnabled {
  138. return
  139. }
  140. channelSyncLock.Lock()
  141. defer channelSyncLock.Unlock()
  142. if channel, ok := channelsIDM[id]; ok {
  143. channel.Status = status
  144. }
  145. }