channel_cache.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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"
  13. "github.com/QuantumNous/new-api/setting/ratio_setting"
  14. "github.com/gin-gonic/gin"
  15. )
  16. var group2model2channels map[string]map[string][]int // enabled channel
  17. var channelsIDM map[int]*Channel // all channels include disabled
  18. var channelSyncLock sync.RWMutex
  19. func InitChannelCache() {
  20. if !common.MemoryCacheEnabled {
  21. return
  22. }
  23. newChannelId2channel := make(map[int]*Channel)
  24. var channels []*Channel
  25. DB.Find(&channels)
  26. for _, channel := range channels {
  27. newChannelId2channel[channel.Id] = channel
  28. }
  29. var abilities []*Ability
  30. DB.Find(&abilities)
  31. groups := make(map[string]bool)
  32. for _, ability := range abilities {
  33. groups[ability.Group] = true
  34. }
  35. newGroup2model2channels := make(map[string]map[string][]int)
  36. for group := range groups {
  37. newGroup2model2channels[group] = make(map[string][]int)
  38. }
  39. for _, channel := range channels {
  40. if channel.Status != common.ChannelStatusEnabled {
  41. continue // skip disabled channels
  42. }
  43. groups := strings.Split(channel.Group, ",")
  44. for _, group := range groups {
  45. models := strings.Split(channel.Models, ",")
  46. for _, model := range models {
  47. if _, ok := newGroup2model2channels[group][model]; !ok {
  48. newGroup2model2channels[group][model] = make([]int, 0)
  49. }
  50. newGroup2model2channels[group][model] = append(newGroup2model2channels[group][model], channel.Id)
  51. }
  52. }
  53. }
  54. // sort by priority
  55. for group, model2channels := range newGroup2model2channels {
  56. for model, channels := range model2channels {
  57. sort.Slice(channels, func(i, j int) bool {
  58. return newChannelId2channel[channels[i]].GetPriority() > newChannelId2channel[channels[j]].GetPriority()
  59. })
  60. newGroup2model2channels[group][model] = channels
  61. }
  62. }
  63. channelSyncLock.Lock()
  64. group2model2channels = newGroup2model2channels
  65. //channelsIDM = newChannelId2channel
  66. for i, channel := range newChannelId2channel {
  67. if channel.ChannelInfo.IsMultiKey {
  68. channel.Keys = channel.GetKeys()
  69. if channel.ChannelInfo.MultiKeyMode == constant.MultiKeyModePolling {
  70. if oldChannel, ok := channelsIDM[i]; ok {
  71. // 存在旧的渠道,如果是多key且轮询,保留轮询索引信息
  72. if oldChannel.ChannelInfo.IsMultiKey && oldChannel.ChannelInfo.MultiKeyMode == constant.MultiKeyModePolling {
  73. channel.ChannelInfo.MultiKeyPollingIndex = oldChannel.ChannelInfo.MultiKeyPollingIndex
  74. }
  75. }
  76. }
  77. }
  78. }
  79. channelsIDM = newChannelId2channel
  80. channelSyncLock.Unlock()
  81. common.SysLog("channels synced from database")
  82. }
  83. func SyncChannelCache(frequency int) {
  84. for {
  85. time.Sleep(time.Duration(frequency) * time.Second)
  86. common.SysLog("syncing channels from database")
  87. InitChannelCache()
  88. }
  89. }
  90. func CacheGetRandomSatisfiedChannel(c *gin.Context, group string, model string, retry int) (*Channel, string, error) {
  91. var channel *Channel
  92. var err error
  93. selectGroup := group
  94. if group == "auto" {
  95. if len(setting.AutoGroups) == 0 {
  96. return nil, selectGroup, errors.New("auto groups is not enabled")
  97. }
  98. for _, autoGroup := range setting.AutoGroups {
  99. if common.DebugEnabled {
  100. println("autoGroup:", autoGroup)
  101. }
  102. channel, _ = getRandomSatisfiedChannel(autoGroup, model, retry)
  103. if channel == nil {
  104. continue
  105. } else {
  106. c.Set("auto_group", autoGroup)
  107. selectGroup = autoGroup
  108. if common.DebugEnabled {
  109. println("selectGroup:", selectGroup)
  110. }
  111. break
  112. }
  113. }
  114. } else {
  115. channel, err = getRandomSatisfiedChannel(group, model, retry)
  116. if err != nil {
  117. return nil, group, err
  118. }
  119. }
  120. return channel, selectGroup, nil
  121. }
  122. func getRandomSatisfiedChannel(group string, model string, retry int) (*Channel, error) {
  123. // if memory cache is disabled, get channel directly from database
  124. if !common.MemoryCacheEnabled {
  125. return GetRandomSatisfiedChannel(group, model, retry)
  126. }
  127. channelSyncLock.RLock()
  128. defer channelSyncLock.RUnlock()
  129. // First, try to find channels with the exact model name.
  130. channels := group2model2channels[group][model]
  131. // If no channels found, try to find channels with the normalized model name.
  132. if len(channels) == 0 {
  133. normalizedModel := ratio_setting.FormatMatchingModelName(model)
  134. channels = group2model2channels[group][normalizedModel]
  135. }
  136. if len(channels) == 0 {
  137. return nil, nil
  138. }
  139. if len(channels) == 1 {
  140. if channel, ok := channelsIDM[channels[0]]; ok {
  141. return channel, nil
  142. }
  143. return nil, fmt.Errorf("数据库一致性错误,渠道# %d 不存在,请联系管理员修复", channels[0])
  144. }
  145. uniquePriorities := make(map[int]bool)
  146. for _, channelId := range channels {
  147. if channel, ok := channelsIDM[channelId]; ok {
  148. uniquePriorities[int(channel.GetPriority())] = true
  149. } else {
  150. return nil, fmt.Errorf("数据库一致性错误,渠道# %d 不存在,请联系管理员修复", channelId)
  151. }
  152. }
  153. var sortedUniquePriorities []int
  154. for priority := range uniquePriorities {
  155. sortedUniquePriorities = append(sortedUniquePriorities, priority)
  156. }
  157. sort.Sort(sort.Reverse(sort.IntSlice(sortedUniquePriorities)))
  158. if retry >= len(uniquePriorities) {
  159. retry = len(uniquePriorities) - 1
  160. }
  161. targetPriority := int64(sortedUniquePriorities[retry])
  162. // get the priority for the given retry number
  163. var targetChannels []*Channel
  164. for _, channelId := range channels {
  165. if channel, ok := channelsIDM[channelId]; ok {
  166. if channel.GetPriority() == targetPriority {
  167. targetChannels = append(targetChannels, channel)
  168. }
  169. } else {
  170. return nil, fmt.Errorf("数据库一致性错误,渠道# %d 不存在,请联系管理员修复", channelId)
  171. }
  172. }
  173. // 平滑系数
  174. smoothingFactor := 10
  175. // Calculate the total weight of all channels up to endIdx
  176. totalWeight := 0
  177. for _, channel := range targetChannels {
  178. totalWeight += channel.GetWeight() + smoothingFactor
  179. }
  180. // Generate a random value in the range [0, totalWeight)
  181. randomWeight := rand.Intn(totalWeight)
  182. // Find a channel based on its weight
  183. for _, channel := range targetChannels {
  184. randomWeight -= channel.GetWeight() + smoothingFactor
  185. if randomWeight < 0 {
  186. return channel, nil
  187. }
  188. }
  189. // return null if no channel is not found
  190. return nil, errors.New("channel not found")
  191. }
  192. func CacheGetChannel(id int) (*Channel, error) {
  193. if !common.MemoryCacheEnabled {
  194. return GetChannelById(id, true)
  195. }
  196. channelSyncLock.RLock()
  197. defer channelSyncLock.RUnlock()
  198. c, ok := channelsIDM[id]
  199. if !ok {
  200. return nil, fmt.Errorf("渠道# %d,已不存在", id)
  201. }
  202. return c, nil
  203. }
  204. func CacheGetChannelInfo(id int) (*ChannelInfo, error) {
  205. if !common.MemoryCacheEnabled {
  206. channel, err := GetChannelById(id, true)
  207. if err != nil {
  208. return nil, err
  209. }
  210. return &channel.ChannelInfo, nil
  211. }
  212. channelSyncLock.RLock()
  213. defer channelSyncLock.RUnlock()
  214. c, ok := channelsIDM[id]
  215. if !ok {
  216. return nil, fmt.Errorf("渠道# %d,已不存在", id)
  217. }
  218. return &c.ChannelInfo, nil
  219. }
  220. func CacheUpdateChannelStatus(id int, status int) {
  221. if !common.MemoryCacheEnabled {
  222. return
  223. }
  224. channelSyncLock.Lock()
  225. defer channelSyncLock.Unlock()
  226. if channel, ok := channelsIDM[id]; ok {
  227. channel.Status = status
  228. }
  229. if status != common.ChannelStatusEnabled {
  230. // delete the channel from group2model2channels
  231. for group, model2channels := range group2model2channels {
  232. for model, channels := range model2channels {
  233. for i, channelId := range channels {
  234. if channelId == id {
  235. // remove the channel from the slice
  236. group2model2channels[group][model] = append(channels[:i], channels[i+1:]...)
  237. break
  238. }
  239. }
  240. }
  241. }
  242. }
  243. }
  244. func CacheUpdateChannel(channel *Channel) {
  245. if !common.MemoryCacheEnabled {
  246. return
  247. }
  248. channelSyncLock.Lock()
  249. defer channelSyncLock.Unlock()
  250. if channel == nil {
  251. return
  252. }
  253. println("CacheUpdateChannel:", channel.Id, channel.Name, channel.Status, channel.ChannelInfo.MultiKeyPollingIndex)
  254. println("before:", channelsIDM[channel.Id].ChannelInfo.MultiKeyPollingIndex)
  255. channelsIDM[channel.Id] = channel
  256. println("after :", channelsIDM[channel.Id].ChannelInfo.MultiKeyPollingIndex)
  257. }