channel_cache.go 7.6 KB

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