channel_cache.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. package model
  2. import (
  3. "errors"
  4. "fmt"
  5. "math/rand"
  6. "sort"
  7. "strings"
  8. "sync"
  9. "time"
  10. "github.com/QuantumNous/new-api/common"
  11. "github.com/QuantumNous/new-api/constant"
  12. "github.com/QuantumNous/new-api/setting/ratio_setting"
  13. )
  14. var group2model2channels map[string]map[string][]int // enabled channel
  15. var channelsIDM map[int]*Channel // all channels include disabled
  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.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. for group := range groups {
  35. newGroup2model2channels[group] = make(map[string][]int)
  36. }
  37. for _, channel := range channels {
  38. if channel.Status != common.ChannelStatusEnabled {
  39. continue // skip disabled channels
  40. }
  41. groups := strings.Split(channel.Group, ",")
  42. for _, group := range groups {
  43. models := strings.Split(channel.Models, ",")
  44. for _, model := range models {
  45. if _, ok := newGroup2model2channels[group][model]; !ok {
  46. newGroup2model2channels[group][model] = make([]int, 0)
  47. }
  48. newGroup2model2channels[group][model] = append(newGroup2model2channels[group][model], channel.Id)
  49. }
  50. }
  51. }
  52. // sort by priority
  53. for group, model2channels := range newGroup2model2channels {
  54. for model, channels := range model2channels {
  55. sort.Slice(channels, func(i, j int) bool {
  56. return newChannelId2channel[channels[i]].GetPriority() > newChannelId2channel[channels[j]].GetPriority()
  57. })
  58. newGroup2model2channels[group][model] = channels
  59. }
  60. }
  61. channelSyncLock.Lock()
  62. group2model2channels = newGroup2model2channels
  63. //channelsIDM = newChannelId2channel
  64. for i, channel := range newChannelId2channel {
  65. if channel.ChannelInfo.IsMultiKey {
  66. channel.Keys = channel.GetKeys()
  67. if channel.ChannelInfo.MultiKeyMode == constant.MultiKeyModePolling {
  68. if oldChannel, ok := channelsIDM[i]; ok {
  69. // 存在旧的渠道,如果是多key且轮询,保留轮询索引信息
  70. if oldChannel.ChannelInfo.IsMultiKey && oldChannel.ChannelInfo.MultiKeyMode == constant.MultiKeyModePolling {
  71. channel.ChannelInfo.MultiKeyPollingIndex = oldChannel.ChannelInfo.MultiKeyPollingIndex
  72. }
  73. }
  74. }
  75. }
  76. }
  77. channelsIDM = newChannelId2channel
  78. channelSyncLock.Unlock()
  79. common.SysLog("channels synced from database")
  80. }
  81. func SyncChannelCache(frequency int) {
  82. for {
  83. time.Sleep(time.Duration(frequency) * time.Second)
  84. common.SysLog("syncing channels from database")
  85. InitChannelCache()
  86. }
  87. }
  88. func GetRandomSatisfiedChannel(group string, model string, retry int) (*Channel, error) {
  89. // if memory cache is disabled, get channel directly from database
  90. if !common.MemoryCacheEnabled {
  91. return GetChannel(group, model, retry)
  92. }
  93. channelSyncLock.RLock()
  94. defer channelSyncLock.RUnlock()
  95. // First, try to find channels with the exact model name.
  96. channels := group2model2channels[group][model]
  97. // If no channels found, try to find channels with the normalized model name.
  98. if len(channels) == 0 {
  99. normalizedModel := ratio_setting.FormatMatchingModelName(model)
  100. channels = group2model2channels[group][normalizedModel]
  101. }
  102. if len(channels) == 0 {
  103. return nil, nil
  104. }
  105. if len(channels) == 1 {
  106. if channel, ok := channelsIDM[channels[0]]; ok {
  107. return channel, nil
  108. }
  109. return nil, fmt.Errorf("数据库一致性错误,渠道# %d 不存在,请联系管理员修复", channels[0])
  110. }
  111. uniquePriorities := make(map[int]bool)
  112. for _, channelId := range channels {
  113. if channel, ok := channelsIDM[channelId]; ok {
  114. uniquePriorities[int(channel.GetPriority())] = true
  115. } else {
  116. return nil, fmt.Errorf("数据库一致性错误,渠道# %d 不存在,请联系管理员修复", channelId)
  117. }
  118. }
  119. var sortedUniquePriorities []int
  120. for priority := range uniquePriorities {
  121. sortedUniquePriorities = append(sortedUniquePriorities, priority)
  122. }
  123. sort.Sort(sort.Reverse(sort.IntSlice(sortedUniquePriorities)))
  124. if retry >= len(uniquePriorities) {
  125. retry = len(uniquePriorities) - 1
  126. }
  127. targetPriority := int64(sortedUniquePriorities[retry])
  128. // get the priority for the given retry number
  129. var shouldSmooth = false
  130. var sumWeight = 0
  131. var targetChannels []*Channel
  132. for _, channelId := range channels {
  133. if channel, ok := channelsIDM[channelId]; ok {
  134. if channel.GetPriority() == targetPriority {
  135. sumWeight += channel.GetWeight()
  136. targetChannels = append(targetChannels, channel)
  137. }
  138. } else {
  139. return nil, fmt.Errorf("数据库一致性错误,渠道# %d 不存在,请联系管理员修复", channelId)
  140. }
  141. }
  142. if sumWeight/len(targetChannels) < 10 {
  143. shouldSmooth = true
  144. }
  145. // 平滑系数
  146. smoothingFactor := 1
  147. if shouldSmooth {
  148. smoothingFactor = 100
  149. }
  150. // Calculate the total weight of all channels up to endIdx
  151. totalWeight := sumWeight * smoothingFactor
  152. // totalWeight 小于等于0时,给每个渠道加100的权重,然后进行随机选择
  153. if totalWeight <= 0 {
  154. if len(targetChannels) > 0 {
  155. totalWeight = len(targetChannels) * 100
  156. randomWeight := rand.Intn(totalWeight)
  157. for _, channel := range targetChannels {
  158. randomWeight -= 100
  159. if randomWeight <= 0 {
  160. return channel, nil
  161. }
  162. }
  163. }
  164. return nil, errors.New("no available channels")
  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 CacheGetChannelInfo(id int) (*ChannelInfo, error) {
  191. if !common.MemoryCacheEnabled {
  192. channel, err := GetChannelById(id, true)
  193. if err != nil {
  194. return nil, err
  195. }
  196. return &channel.ChannelInfo, nil
  197. }
  198. channelSyncLock.RLock()
  199. defer channelSyncLock.RUnlock()
  200. c, ok := channelsIDM[id]
  201. if !ok {
  202. return nil, fmt.Errorf("渠道# %d,已不存在", id)
  203. }
  204. return &c.ChannelInfo, nil
  205. }
  206. func CacheUpdateChannelStatus(id int, status int) {
  207. if !common.MemoryCacheEnabled {
  208. return
  209. }
  210. channelSyncLock.Lock()
  211. defer channelSyncLock.Unlock()
  212. if channel, ok := channelsIDM[id]; ok {
  213. channel.Status = status
  214. }
  215. if status != common.ChannelStatusEnabled {
  216. // delete the channel from group2model2channels
  217. for group, model2channels := range group2model2channels {
  218. for model, channels := range model2channels {
  219. for i, channelId := range channels {
  220. if channelId == id {
  221. // remove the channel from the slice
  222. group2model2channels[group][model] = append(channels[:i], channels[i+1:]...)
  223. break
  224. }
  225. }
  226. }
  227. }
  228. }
  229. }
  230. func CacheUpdateChannel(channel *Channel) {
  231. if !common.MemoryCacheEnabled {
  232. return
  233. }
  234. channelSyncLock.Lock()
  235. defer channelSyncLock.Unlock()
  236. if channel == nil {
  237. return
  238. }
  239. println("CacheUpdateChannel:", channel.Id, channel.Name, channel.Status, channel.ChannelInfo.MultiKeyPollingIndex)
  240. println("before:", channelsIDM[channel.Id].ChannelInfo.MultiKeyPollingIndex)
  241. channelsIDM[channel.Id] = channel
  242. println("after :", channelsIDM[channel.Id].ChannelInfo.MultiKeyPollingIndex)
  243. }