channel_cache.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. package model
  2. import (
  3. "errors"
  4. "fmt"
  5. "math/rand"
  6. "one-api/common"
  7. "one-api/setting"
  8. "sort"
  9. "strings"
  10. "sync"
  11. "time"
  12. "github.com/gin-gonic/gin"
  13. )
  14. var group2model2channels map[string]map[string][]int
  15. var channelsIDM map[int]*Channel
  16. var channelSyncLock sync.RWMutex
  17. func InitChannelCache() {
  18. if !common.MemoryCacheEnabled {
  19. return
  20. }
  21. newChannelId2channel := make(map[int]*Channel)
  22. var channels []*Channel
  23. DB.Where("status = ?", common.ChannelStatusEnabled).Find(&channels)
  24. for _, channel := range channels {
  25. newChannelId2channel[channel.Id] = channel
  26. }
  27. var abilities []*Ability
  28. DB.Find(&abilities)
  29. groups := make(map[string]bool)
  30. for _, ability := range abilities {
  31. groups[ability.Group] = true
  32. }
  33. newGroup2model2channels := make(map[string]map[string][]int)
  34. newChannelsIDM := make(map[int]*Channel)
  35. for group := range groups {
  36. newGroup2model2channels[group] = make(map[string][]int)
  37. }
  38. for _, channel := range channels {
  39. newChannelsIDM[channel.Id] = channel
  40. groups := strings.Split(channel.Group, ",")
  41. for _, group := range groups {
  42. models := strings.Split(channel.Models, ",")
  43. for _, model := range models {
  44. if _, ok := newGroup2model2channels[group][model]; !ok {
  45. newGroup2model2channels[group][model] = make([]int, 0)
  46. }
  47. newGroup2model2channels[group][model] = append(newGroup2model2channels[group][model], channel.Id)
  48. }
  49. }
  50. }
  51. // sort by priority
  52. for group, model2channels := range newGroup2model2channels {
  53. for model, channels := range model2channels {
  54. sort.Slice(channels, func(i, j int) bool {
  55. return newChannelsIDM[channels[i]].GetPriority() > newChannelsIDM[channels[j]].GetPriority()
  56. })
  57. newGroup2model2channels[group][model] = channels
  58. }
  59. }
  60. channelSyncLock.Lock()
  61. group2model2channels = newGroup2model2channels
  62. channelsIDM = newChannelsIDM
  63. channelSyncLock.Unlock()
  64. common.SysLog("channels synced from database")
  65. }
  66. func SyncChannelCache(frequency int) {
  67. for {
  68. time.Sleep(time.Duration(frequency) * time.Second)
  69. common.SysLog("syncing channels from database")
  70. InitChannelCache()
  71. }
  72. }
  73. func CacheGetRandomSatisfiedChannel(c *gin.Context, group string, model string, retry int) (*Channel, string, error) {
  74. var channel *Channel
  75. var err error
  76. selectGroup := group
  77. if group == "auto" {
  78. if len(setting.AutoGroups) == 0 {
  79. return nil, selectGroup, errors.New("auto groups is not enabled")
  80. }
  81. for _, autoGroup := range setting.AutoGroups {
  82. if common.DebugEnabled {
  83. println("autoGroup:", autoGroup)
  84. }
  85. channel, _ = getRandomSatisfiedChannel(autoGroup, model, retry)
  86. if channel == nil {
  87. continue
  88. } else {
  89. c.Set("auto_group", autoGroup)
  90. selectGroup = autoGroup
  91. if common.DebugEnabled {
  92. println("selectGroup:", selectGroup)
  93. }
  94. break
  95. }
  96. }
  97. } else {
  98. channel, err = getRandomSatisfiedChannel(group, model, retry)
  99. if err != nil {
  100. return nil, group, err
  101. }
  102. }
  103. if channel == nil {
  104. return nil, group, errors.New("channel not found")
  105. }
  106. return channel, selectGroup, nil
  107. }
  108. func getRandomSatisfiedChannel(group string, model string, retry int) (*Channel, error) {
  109. if strings.HasPrefix(model, "gpt-4-gizmo") {
  110. model = "gpt-4-gizmo-*"
  111. }
  112. if strings.HasPrefix(model, "gpt-4o-gizmo") {
  113. model = "gpt-4o-gizmo-*"
  114. }
  115. // if memory cache is disabled, get channel directly from database
  116. if !common.MemoryCacheEnabled {
  117. return GetRandomSatisfiedChannel(group, model, retry)
  118. }
  119. channelSyncLock.RLock()
  120. defer channelSyncLock.RUnlock()
  121. channels := group2model2channels[group][model]
  122. if len(channels) == 0 {
  123. return nil, errors.New("channel not found")
  124. }
  125. if len(channels) == 1 {
  126. if channel, ok := channelsIDM[channels[0]]; ok {
  127. return channel, nil
  128. }
  129. return nil, fmt.Errorf("数据库一致性错误,渠道# %d 不存在,请联系管理员修复", channels[0])
  130. }
  131. uniquePriorities := make(map[int]bool)
  132. for _, channelId := range channels {
  133. if channel, ok := channelsIDM[channelId]; ok {
  134. uniquePriorities[int(channel.GetPriority())] = true
  135. } else {
  136. return nil, fmt.Errorf("数据库一致性错误,渠道# %d 不存在,请联系管理员修复", channelId)
  137. }
  138. }
  139. var sortedUniquePriorities []int
  140. for priority := range uniquePriorities {
  141. sortedUniquePriorities = append(sortedUniquePriorities, priority)
  142. }
  143. sort.Sort(sort.Reverse(sort.IntSlice(sortedUniquePriorities)))
  144. if retry >= len(uniquePriorities) {
  145. retry = len(uniquePriorities) - 1
  146. }
  147. targetPriority := int64(sortedUniquePriorities[retry])
  148. // get the priority for the given retry number
  149. var targetChannels []*Channel
  150. for _, channelId := range channels {
  151. if channel, ok := channelsIDM[channelId]; ok {
  152. if channel.GetPriority() == targetPriority {
  153. targetChannels = append(targetChannels, channel)
  154. }
  155. } else {
  156. return nil, fmt.Errorf("数据库一致性错误,渠道# %d 不存在,请联系管理员修复", channelId)
  157. }
  158. }
  159. // 平滑系数
  160. smoothingFactor := 10
  161. // Calculate the total weight of all channels up to endIdx
  162. totalWeight := 0
  163. for _, channel := range targetChannels {
  164. totalWeight += channel.GetWeight() + smoothingFactor
  165. }
  166. // Generate a random value in the range [0, totalWeight)
  167. randomWeight := rand.Intn(totalWeight)
  168. // Find a channel based on its weight
  169. for _, channel := range targetChannels {
  170. randomWeight -= channel.GetWeight() + smoothingFactor
  171. if randomWeight < 0 {
  172. return channel, nil
  173. }
  174. }
  175. // return null if no channel is not found
  176. return nil, errors.New("channel not found")
  177. }
  178. func CacheGetChannel(id int) (*Channel, error) {
  179. if !common.MemoryCacheEnabled {
  180. return GetChannelById(id, true)
  181. }
  182. channelSyncLock.RLock()
  183. defer channelSyncLock.RUnlock()
  184. c, ok := channelsIDM[id]
  185. if !ok {
  186. return nil, fmt.Errorf("当前渠道# %d,已不存在", id)
  187. }
  188. return c, nil
  189. }
  190. func CacheUpdateChannelStatus(id int, status int) {
  191. if !common.MemoryCacheEnabled {
  192. return
  193. }
  194. channelSyncLock.Lock()
  195. defer channelSyncLock.Unlock()
  196. if channel, ok := channelsIDM[id]; ok {
  197. channel.Status = status
  198. }
  199. }
  200. func CacheUpdateChannel(channel *Channel) {
  201. if !common.MemoryCacheEnabled {
  202. return
  203. }
  204. channelSyncLock.Lock()
  205. defer channelSyncLock.Unlock()
  206. if channel == nil {
  207. return
  208. }
  209. println("CacheUpdateChannel:", channel.Id, channel.Name, channel.Status, channel.ChannelInfo.MultiKeyPollingIndex)
  210. println("before:", channelsIDM[channel.Id].ChannelInfo.MultiKeyPollingIndex)
  211. channelsIDM[channel.Id] = channel
  212. println("after :", channelsIDM[channel.Id].ChannelInfo.MultiKeyPollingIndex)
  213. }