channel_cache.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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 sumWeight = 0
  130. var targetChannels []*Channel
  131. for _, channelId := range channels {
  132. if channel, ok := channelsIDM[channelId]; ok {
  133. if channel.GetPriority() == targetPriority {
  134. sumWeight += channel.GetWeight()
  135. targetChannels = append(targetChannels, channel)
  136. }
  137. } else {
  138. return nil, fmt.Errorf("数据库一致性错误,渠道# %d 不存在,请联系管理员修复", channelId)
  139. }
  140. }
  141. if len(targetChannels) == 0 {
  142. return nil, errors.New(fmt.Sprintf("no channel found, group: %s, model: %s, priority: %d", group, model, targetPriority))
  143. }
  144. // smoothing factor and adjustment
  145. smoothingFactor := 1
  146. smoothingAdjustment := 0
  147. if sumWeight == 0 {
  148. // when all channels have weight 0, set sumWeight to the number of channels and set smoothing adjustment to 100
  149. // each channel's effective weight = 100
  150. sumWeight = len(targetChannels) * 100
  151. smoothingAdjustment = 100
  152. } else if sumWeight/len(targetChannels) < 10 {
  153. // when the average weight is less than 10, set smoothing factor to 100
  154. smoothingFactor = 100
  155. }
  156. // Calculate the total weight of all channels up to endIdx
  157. totalWeight := sumWeight * smoothingFactor
  158. // Generate a random value in the range [0, totalWeight)
  159. randomWeight := rand.Intn(totalWeight)
  160. // Find a channel based on its weight
  161. for _, channel := range targetChannels {
  162. randomWeight -= channel.GetWeight()*smoothingFactor + smoothingAdjustment
  163. if randomWeight < 0 {
  164. return channel, nil
  165. }
  166. }
  167. // return null if no channel is not found
  168. return nil, errors.New("channel not found")
  169. }
  170. func CacheGetChannel(id int) (*Channel, error) {
  171. if !common.MemoryCacheEnabled {
  172. return GetChannelById(id, true)
  173. }
  174. channelSyncLock.RLock()
  175. defer channelSyncLock.RUnlock()
  176. c, ok := channelsIDM[id]
  177. if !ok {
  178. return nil, fmt.Errorf("渠道# %d,已不存在", id)
  179. }
  180. return c, nil
  181. }
  182. func CacheGetChannelInfo(id int) (*ChannelInfo, error) {
  183. if !common.MemoryCacheEnabled {
  184. channel, err := GetChannelById(id, true)
  185. if err != nil {
  186. return nil, err
  187. }
  188. return &channel.ChannelInfo, nil
  189. }
  190. channelSyncLock.RLock()
  191. defer channelSyncLock.RUnlock()
  192. c, ok := channelsIDM[id]
  193. if !ok {
  194. return nil, fmt.Errorf("渠道# %d,已不存在", id)
  195. }
  196. return &c.ChannelInfo, nil
  197. }
  198. func CacheUpdateChannelStatus(id int, status int) {
  199. if !common.MemoryCacheEnabled {
  200. return
  201. }
  202. channelSyncLock.Lock()
  203. defer channelSyncLock.Unlock()
  204. if channel, ok := channelsIDM[id]; ok {
  205. channel.Status = status
  206. }
  207. if status != common.ChannelStatusEnabled {
  208. // delete the channel from group2model2channels
  209. for group, model2channels := range group2model2channels {
  210. for model, channels := range model2channels {
  211. for i, channelId := range channels {
  212. if channelId == id {
  213. // remove the channel from the slice
  214. group2model2channels[group][model] = append(channels[:i], channels[i+1:]...)
  215. break
  216. }
  217. }
  218. }
  219. }
  220. }
  221. }
  222. func CacheUpdateChannel(channel *Channel) {
  223. if !common.MemoryCacheEnabled {
  224. return
  225. }
  226. channelSyncLock.Lock()
  227. defer channelSyncLock.Unlock()
  228. if channel == nil {
  229. return
  230. }
  231. println("CacheUpdateChannel:", channel.Id, channel.Name, channel.Status, channel.ChannelInfo.MultiKeyPollingIndex)
  232. println("before:", channelsIDM[channel.Id].ChannelInfo.MultiKeyPollingIndex)
  233. channelsIDM[channel.Id] = channel
  234. println("after :", channelsIDM[channel.Id].ChannelInfo.MultiKeyPollingIndex)
  235. }