channel_cache.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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 // 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. channelSyncLock.Unlock()
  65. common.SysLog("channels synced from database")
  66. }
  67. func SyncChannelCache(frequency int) {
  68. for {
  69. time.Sleep(time.Duration(frequency) * time.Second)
  70. common.SysLog("syncing channels from database")
  71. InitChannelCache()
  72. }
  73. }
  74. func CacheGetRandomSatisfiedChannel(c *gin.Context, group string, model string, retry int) (*Channel, string, error) {
  75. var channel *Channel
  76. var err error
  77. selectGroup := group
  78. if group == "auto" {
  79. if len(setting.AutoGroups) == 0 {
  80. return nil, selectGroup, errors.New("auto groups is not enabled")
  81. }
  82. for _, autoGroup := range setting.AutoGroups {
  83. if common.DebugEnabled {
  84. println("autoGroup:", autoGroup)
  85. }
  86. channel, _ = getRandomSatisfiedChannel(autoGroup, model, retry)
  87. if channel == nil {
  88. continue
  89. } else {
  90. c.Set("auto_group", autoGroup)
  91. selectGroup = autoGroup
  92. if common.DebugEnabled {
  93. println("selectGroup:", selectGroup)
  94. }
  95. break
  96. }
  97. }
  98. } else {
  99. channel, err = getRandomSatisfiedChannel(group, model, retry)
  100. if err != nil {
  101. return nil, group, err
  102. }
  103. }
  104. return channel, selectGroup, nil
  105. }
  106. func getRandomSatisfiedChannel(group string, model string, retry int) (*Channel, error) {
  107. if strings.HasPrefix(model, "gpt-4-gizmo") {
  108. model = "gpt-4-gizmo-*"
  109. }
  110. if strings.HasPrefix(model, "gpt-4o-gizmo") {
  111. model = "gpt-4o-gizmo-*"
  112. }
  113. // if memory cache is disabled, get channel directly from database
  114. if !common.MemoryCacheEnabled {
  115. return GetRandomSatisfiedChannel(group, model, retry)
  116. }
  117. channelSyncLock.RLock()
  118. defer channelSyncLock.RUnlock()
  119. channels := group2model2channels[group][model]
  120. if len(channels) == 0 {
  121. return nil, nil
  122. }
  123. if len(channels) == 1 {
  124. if channel, ok := channelsIDM[channels[0]]; ok {
  125. return channel, nil
  126. }
  127. return nil, fmt.Errorf("数据库一致性错误,渠道# %d 不存在,请联系管理员修复", channels[0])
  128. }
  129. uniquePriorities := make(map[int]bool)
  130. for _, channelId := range channels {
  131. if channel, ok := channelsIDM[channelId]; ok {
  132. uniquePriorities[int(channel.GetPriority())] = true
  133. } else {
  134. return nil, fmt.Errorf("数据库一致性错误,渠道# %d 不存在,请联系管理员修复", channelId)
  135. }
  136. }
  137. var sortedUniquePriorities []int
  138. for priority := range uniquePriorities {
  139. sortedUniquePriorities = append(sortedUniquePriorities, priority)
  140. }
  141. sort.Sort(sort.Reverse(sort.IntSlice(sortedUniquePriorities)))
  142. if retry >= len(uniquePriorities) {
  143. retry = len(uniquePriorities) - 1
  144. }
  145. targetPriority := int64(sortedUniquePriorities[retry])
  146. // get the priority for the given retry number
  147. var targetChannels []*Channel
  148. for _, channelId := range channels {
  149. if channel, ok := channelsIDM[channelId]; ok {
  150. if channel.GetPriority() == targetPriority {
  151. targetChannels = append(targetChannels, channel)
  152. }
  153. } else {
  154. return nil, fmt.Errorf("数据库一致性错误,渠道# %d 不存在,请联系管理员修复", channelId)
  155. }
  156. }
  157. // 平滑系数
  158. smoothingFactor := 10
  159. // Calculate the total weight of all channels up to endIdx
  160. totalWeight := 0
  161. for _, channel := range targetChannels {
  162. totalWeight += channel.GetWeight() + smoothingFactor
  163. }
  164. // Generate a random value in the range [0, totalWeight)
  165. randomWeight := rand.Intn(totalWeight)
  166. // Find a channel based on its weight
  167. for _, channel := range targetChannels {
  168. randomWeight -= channel.GetWeight() + smoothingFactor
  169. if randomWeight < 0 {
  170. return channel, nil
  171. }
  172. }
  173. // return null if no channel is not found
  174. return nil, errors.New("channel not found")
  175. }
  176. func CacheGetChannel(id int) (*Channel, error) {
  177. if !common.MemoryCacheEnabled {
  178. return GetChannelById(id, true)
  179. }
  180. channelSyncLock.RLock()
  181. defer channelSyncLock.RUnlock()
  182. c, ok := channelsIDM[id]
  183. if !ok {
  184. return nil, fmt.Errorf("渠道# %d,已不存在", id)
  185. }
  186. if c.Status != common.ChannelStatusEnabled {
  187. return nil, fmt.Errorf("渠道# %d,已被禁用", id)
  188. }
  189. return c, nil
  190. }
  191. func CacheGetChannelInfo(id int) (*ChannelInfo, error) {
  192. if !common.MemoryCacheEnabled {
  193. channel, err := GetChannelById(id, true)
  194. if err != nil {
  195. return nil, err
  196. }
  197. return &channel.ChannelInfo, nil
  198. }
  199. channelSyncLock.RLock()
  200. defer channelSyncLock.RUnlock()
  201. c, ok := channelsIDM[id]
  202. if !ok {
  203. return nil, fmt.Errorf("渠道# %d,已不存在", id)
  204. }
  205. if c.Status != common.ChannelStatusEnabled {
  206. return nil, fmt.Errorf("渠道# %d,已被禁用", id)
  207. }
  208. return &c.ChannelInfo, nil
  209. }
  210. func CacheUpdateChannelStatus(id int, status int) {
  211. if !common.MemoryCacheEnabled {
  212. return
  213. }
  214. channelSyncLock.Lock()
  215. defer channelSyncLock.Unlock()
  216. if channel, ok := channelsIDM[id]; ok {
  217. channel.Status = status
  218. }
  219. }
  220. func CacheUpdateChannel(channel *Channel) {
  221. if !common.MemoryCacheEnabled {
  222. return
  223. }
  224. channelSyncLock.Lock()
  225. defer channelSyncLock.Unlock()
  226. if channel == nil {
  227. return
  228. }
  229. println("CacheUpdateChannel:", channel.Id, channel.Name, channel.Status, channel.ChannelInfo.MultiKeyPollingIndex)
  230. println("before:", channelsIDM[channel.Id].ChannelInfo.MultiKeyPollingIndex)
  231. channelsIDM[channel.Id] = channel
  232. println("after :", channelsIDM[channel.Id].ChannelInfo.MultiKeyPollingIndex)
  233. }