You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

291 lines
8.2 KiB

  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. return GetRandomSatisfiedChannelWithFilter(group, model, retry, nil)
  90. }
  91. func GetRandomSatisfiedChannelWithFilter(group string, model string, retry int, filter ChannelFilter) (*Channel, error) {
  92. // if memory cache is disabled, get channel directly from database
  93. if !common.MemoryCacheEnabled {
  94. return GetChannelWithFilter(group, model, retry, filter)
  95. }
  96. channelSyncLock.RLock()
  97. defer channelSyncLock.RUnlock()
  98. // First, try to find channels with the exact model name.
  99. channels := group2model2channels[group][model]
  100. // If no channels found, try to find channels with the normalized model name.
  101. if len(channels) == 0 {
  102. normalizedModel := ratio_setting.FormatMatchingModelName(model)
  103. channels = group2model2channels[group][normalizedModel]
  104. }
  105. if len(channels) == 0 {
  106. return nil, nil
  107. }
  108. if len(channels) == 1 {
  109. if channel, ok := channelsIDM[channels[0]]; ok {
  110. if filter != nil {
  111. accepted, err := filter(channel)
  112. if err != nil {
  113. return nil, err
  114. }
  115. if !accepted {
  116. return nil, nil
  117. }
  118. }
  119. return channel, nil
  120. }
  121. return nil, fmt.Errorf("数据库一致性错误,渠道# %d 不存在,请联系管理员修复", channels[0])
  122. }
  123. uniquePriorities := make(map[int]bool)
  124. for _, channelId := range channels {
  125. if channel, ok := channelsIDM[channelId]; ok {
  126. uniquePriorities[int(channel.GetPriority())] = true
  127. } else {
  128. return nil, fmt.Errorf("数据库一致性错误,渠道# %d 不存在,请联系管理员修复", channelId)
  129. }
  130. }
  131. var sortedUniquePriorities []int
  132. for priority := range uniquePriorities {
  133. sortedUniquePriorities = append(sortedUniquePriorities, priority)
  134. }
  135. sort.Sort(sort.Reverse(sort.IntSlice(sortedUniquePriorities)))
  136. if retry >= len(uniquePriorities) {
  137. retry = len(uniquePriorities) - 1
  138. }
  139. targetPriority := int64(sortedUniquePriorities[retry])
  140. // get the priority for the given retry number
  141. var sumWeight = 0
  142. var targetChannels []*Channel
  143. for _, channelId := range channels {
  144. if channel, ok := channelsIDM[channelId]; ok {
  145. if channel.GetPriority() == targetPriority {
  146. if filter != nil {
  147. accepted, err := filter(channel)
  148. if err != nil {
  149. return nil, err
  150. }
  151. if !accepted {
  152. continue
  153. }
  154. }
  155. sumWeight += channel.GetWeight()
  156. targetChannels = append(targetChannels, channel)
  157. }
  158. } else {
  159. return nil, fmt.Errorf("数据库一致性错误,渠道# %d 不存在,请联系管理员修复", channelId)
  160. }
  161. }
  162. if len(targetChannels) == 0 {
  163. if filter != nil {
  164. return nil, nil
  165. }
  166. return nil, errors.New(fmt.Sprintf("no channel found, group: %s, model: %s, priority: %d", group, model, targetPriority))
  167. }
  168. // smoothing factor and adjustment
  169. smoothingFactor := 1
  170. smoothingAdjustment := 0
  171. if sumWeight == 0 {
  172. // when all channels have weight 0, set sumWeight to the number of channels and set smoothing adjustment to 100
  173. // each channel's effective weight = 100
  174. sumWeight = len(targetChannels) * 100
  175. smoothingAdjustment = 100
  176. } else if sumWeight/len(targetChannels) < 10 {
  177. // when the average weight is less than 10, set smoothing factor to 100
  178. smoothingFactor = 100
  179. }
  180. // Calculate the total weight of all channels up to endIdx
  181. totalWeight := sumWeight * smoothingFactor
  182. // Generate a random value in the range [0, totalWeight)
  183. randomWeight := rand.Intn(totalWeight)
  184. // Find a channel based on its weight
  185. for _, channel := range targetChannels {
  186. randomWeight -= channel.GetWeight()*smoothingFactor + smoothingAdjustment
  187. if randomWeight < 0 {
  188. return channel, nil
  189. }
  190. }
  191. // return null if no channel is not found
  192. return nil, errors.New("channel not found")
  193. }
  194. func CacheGetChannel(id int) (*Channel, error) {
  195. if !common.MemoryCacheEnabled {
  196. return GetChannelById(id, true)
  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, nil
  205. }
  206. func CacheGetChannelInfo(id int) (*ChannelInfo, error) {
  207. if !common.MemoryCacheEnabled {
  208. channel, err := GetChannelById(id, true)
  209. if err != nil {
  210. return nil, err
  211. }
  212. return &channel.ChannelInfo, nil
  213. }
  214. channelSyncLock.RLock()
  215. defer channelSyncLock.RUnlock()
  216. c, ok := channelsIDM[id]
  217. if !ok {
  218. return nil, fmt.Errorf("渠道# %d,已不存在", id)
  219. }
  220. return &c.ChannelInfo, nil
  221. }
  222. func CacheUpdateChannelStatus(id int, status int) {
  223. if !common.MemoryCacheEnabled {
  224. return
  225. }
  226. channelSyncLock.Lock()
  227. defer channelSyncLock.Unlock()
  228. if channel, ok := channelsIDM[id]; ok {
  229. channel.Status = status
  230. }
  231. if status != common.ChannelStatusEnabled {
  232. // delete the channel from group2model2channels
  233. for group, model2channels := range group2model2channels {
  234. for model, channels := range model2channels {
  235. for i, channelId := range channels {
  236. if channelId == id {
  237. // remove the channel from the slice
  238. group2model2channels[group][model] = append(channels[:i], channels[i+1:]...)
  239. break
  240. }
  241. }
  242. }
  243. }
  244. }
  245. }
  246. func CacheUpdateChannel(channel *Channel) {
  247. if !common.MemoryCacheEnabled {
  248. return
  249. }
  250. channelSyncLock.Lock()
  251. defer channelSyncLock.Unlock()
  252. if channel == nil {
  253. return
  254. }
  255. println("CacheUpdateChannel:", channel.Id, channel.Name, channel.Status, channel.ChannelInfo.MultiKeyPollingIndex)
  256. println("before:", channelsIDM[channel.Id].ChannelInfo.MultiKeyPollingIndex)
  257. channelsIDM[channel.Id] = channel
  258. println("after :", channelsIDM[channel.Id].ChannelInfo.MultiKeyPollingIndex)
  259. }