channel_cache.go 7.7 KB

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