channel_cache.go 7.0 KB

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