channel_cache.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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. channelSyncLock.Unlock()
  66. common.SysLog("channels synced from database")
  67. }
  68. func SyncChannelCache(frequency int) {
  69. for {
  70. time.Sleep(time.Duration(frequency) * time.Second)
  71. common.SysLog("syncing channels from database")
  72. InitChannelCache()
  73. }
  74. }
  75. func CacheGetRandomSatisfiedChannel(c *gin.Context, group string, model string, retry int) (*Channel, string, error) {
  76. var channel *Channel
  77. var err error
  78. selectGroup := group
  79. // 获取令牌渠道标签
  80. tokenChannelTag := common.GetContextKeyString(c, constant.ContextKeyTokenChannelTag)
  81. var channelTag *string = nil
  82. if tokenChannelTag != "" {
  83. channelTag = &tokenChannelTag
  84. }
  85. if group == "auto" {
  86. if len(setting.AutoGroups) == 0 {
  87. return nil, selectGroup, errors.New("auto groups is not enabled")
  88. }
  89. for _, autoGroup := range setting.AutoGroups {
  90. if common.DebugEnabled {
  91. println("autoGroup:", autoGroup)
  92. }
  93. channel, _ = getRandomSatisfiedChannel(autoGroup, model, retry)
  94. if channel == nil {
  95. continue
  96. } else {
  97. c.Set("auto_group", autoGroup)
  98. selectGroup = autoGroup
  99. if common.DebugEnabled {
  100. println("selectGroup:", selectGroup)
  101. }
  102. break
  103. }
  104. }
  105. } else {
  106. // 传递channelTag参数给getRandomSatisfiedChannel
  107. channel, err = getRandomSatisfiedChannelWithTag(group, model, retry, channelTag)
  108. if err != nil {
  109. return nil, group, err
  110. }
  111. }
  112. if channel == nil {
  113. return nil, group, errors.New("channel not found")
  114. }
  115. return channel, selectGroup, nil
  116. }
  117. // 新增带标签过滤的渠道选择函数
  118. func getRandomSatisfiedChannelWithTag(group string, model string, retry int, channelTag *string) (*Channel, error) {
  119. if strings.HasPrefix(model, "gpt-4-gizmo") {
  120. model = "gpt-4-gizmo-*"
  121. }
  122. if strings.HasPrefix(model, "gpt-4o-gizmo") {
  123. model = "gpt-4o-gizmo-*"
  124. }
  125. // if memory cache is disabled, get channel directly from database
  126. if !common.MemoryCacheEnabled {
  127. return GetRandomSatisfiedChannel(group, model, retry, channelTag)
  128. }
  129. channelSyncLock.RLock()
  130. defer channelSyncLock.RUnlock()
  131. channels := group2model2channels[group][model]
  132. if len(channels) == 0 {
  133. return nil, errors.New("channel not found")
  134. }
  135. // 过滤符合标签要求的渠道
  136. var filteredChannels []int
  137. for _, channelId := range channels {
  138. if channel, ok := channelsIDM[channelId]; ok {
  139. // 如果没有指定标签要求,则所有渠道都符合
  140. if channelTag == nil || *channelTag == "" {
  141. filteredChannels = append(filteredChannels, channelId)
  142. } else {
  143. // 如果指定了标签要求,则只选择匹配标签的渠道
  144. channelTagStr := channel.GetTag()
  145. if channelTagStr == *channelTag {
  146. filteredChannels = append(filteredChannels, channelId)
  147. }
  148. }
  149. }
  150. }
  151. // 如果没有符合标签要求的渠道,返回错误
  152. if len(filteredChannels) == 0 {
  153. if channelTag != nil && *channelTag != "" {
  154. return nil, fmt.Errorf("没有找到标签为 '%s' 的可用渠道", *channelTag)
  155. }
  156. return nil, errors.New("channel not found")
  157. }
  158. if len(filteredChannels) == 1 {
  159. if channel, ok := channelsIDM[filteredChannels[0]]; ok {
  160. return channel, nil
  161. }
  162. return nil, fmt.Errorf("数据库一致性错误,渠道# %d 不存在,请联系管理员修复", filteredChannels[0])
  163. }
  164. uniquePriorities := make(map[int]bool)
  165. for _, channelId := range filteredChannels {
  166. if channel, ok := channelsIDM[channelId]; ok {
  167. uniquePriorities[int(channel.GetPriority())] = true
  168. } else {
  169. return nil, fmt.Errorf("数据库一致性错误,渠道# %d 不存在,请联系管理员修复", channelId)
  170. }
  171. }
  172. var sortedUniquePriorities []int
  173. for priority := range uniquePriorities {
  174. sortedUniquePriorities = append(sortedUniquePriorities, priority)
  175. }
  176. sort.Sort(sort.Reverse(sort.IntSlice(sortedUniquePriorities)))
  177. if retry >= len(uniquePriorities) {
  178. retry = len(uniquePriorities) - 1
  179. }
  180. targetPriority := int64(sortedUniquePriorities[retry])
  181. // get the priority for the given retry number
  182. var targetChannels []*Channel
  183. for _, channelId := range filteredChannels {
  184. if channel, ok := channelsIDM[channelId]; ok {
  185. if channel.GetPriority() == targetPriority {
  186. targetChannels = append(targetChannels, channel)
  187. }
  188. } else {
  189. return nil, fmt.Errorf("数据库一致性错误,渠道# %d 不存在,请联系管理员修复", channelId)
  190. }
  191. }
  192. // 如果只有一个符合条件的渠道,直接返回
  193. if len(targetChannels) == 1 {
  194. return targetChannels[0], nil
  195. }
  196. // 平滑系数
  197. smoothingFactor := 10
  198. // Calculate the total weight of all channels up to endIdx
  199. totalWeight := 0
  200. for _, channel := range targetChannels {
  201. totalWeight += channel.GetWeight() + smoothingFactor
  202. }
  203. // 如果总权重为0,则平均分配权重
  204. if totalWeight == 0 {
  205. // 随机选择一个渠道
  206. randomIndex := common.GetRandomInt(len(targetChannels))
  207. return targetChannels[randomIndex], nil
  208. }
  209. // Generate a random value in the range [0, totalWeight)
  210. randomWeight := common.GetRandomInt(totalWeight)
  211. // Find a channel based on its weight
  212. for _, channel := range targetChannels {
  213. randomWeight -= channel.GetWeight() + smoothingFactor
  214. if randomWeight < 0 {
  215. return channel, nil
  216. }
  217. }
  218. // 如果循环结束还没有找到,则返回第一个渠道(兜底)
  219. return targetChannels[0], nil
  220. }
  221. func getRandomSatisfiedChannel(group string, model string, retry int) (*Channel, error) {
  222. if strings.HasPrefix(model, "gpt-4-gizmo") {
  223. model = "gpt-4-gizmo-*"
  224. }
  225. if strings.HasPrefix(model, "gpt-4o-gizmo") {
  226. model = "gpt-4o-gizmo-*"
  227. }
  228. // if memory cache is disabled, get channel directly from database
  229. if !common.MemoryCacheEnabled {
  230. return GetRandomSatisfiedChannel(group, model, retry, nil)
  231. }
  232. channelSyncLock.RLock()
  233. defer channelSyncLock.RUnlock()
  234. channels := group2model2channels[group][model]
  235. if len(channels) == 0 {
  236. return nil, errors.New("channel not found")
  237. }
  238. if len(channels) == 1 {
  239. if channel, ok := channelsIDM[channels[0]]; ok {
  240. return channel, nil
  241. }
  242. return nil, fmt.Errorf("数据库一致性错误,渠道# %d 不存在,请联系管理员修复", channels[0])
  243. }
  244. uniquePriorities := make(map[int]bool)
  245. for _, channelId := range channels {
  246. if channel, ok := channelsIDM[channelId]; ok {
  247. uniquePriorities[int(channel.GetPriority())] = true
  248. } else {
  249. return nil, fmt.Errorf("数据库一致性错误,渠道# %d 不存在,请联系管理员修复", channelId)
  250. }
  251. }
  252. var sortedUniquePriorities []int
  253. for priority := range uniquePriorities {
  254. sortedUniquePriorities = append(sortedUniquePriorities, priority)
  255. }
  256. sort.Sort(sort.Reverse(sort.IntSlice(sortedUniquePriorities)))
  257. if retry >= len(uniquePriorities) {
  258. retry = len(uniquePriorities) - 1
  259. }
  260. targetPriority := int64(sortedUniquePriorities[retry])
  261. // get the priority for the given retry number
  262. var targetChannels []*Channel
  263. for _, channelId := range channels {
  264. if channel, ok := channelsIDM[channelId]; ok {
  265. if channel.GetPriority() == targetPriority {
  266. targetChannels = append(targetChannels, channel)
  267. }
  268. } else {
  269. return nil, fmt.Errorf("数据库一致性错误,渠道# %d 不存在,请联系管理员修复", channelId)
  270. }
  271. }
  272. // 平滑系数
  273. smoothingFactor := 10
  274. // Calculate the total weight of all channels up to endIdx
  275. totalWeight := 0
  276. for _, channel := range targetChannels {
  277. totalWeight += channel.GetWeight() + smoothingFactor
  278. }
  279. // Generate a random value in the range [0, totalWeight)
  280. randomWeight := rand.Intn(totalWeight)
  281. // Find a channel based on its weight
  282. for _, channel := range targetChannels {
  283. randomWeight -= channel.GetWeight() + smoothingFactor
  284. if randomWeight < 0 {
  285. return channel, nil
  286. }
  287. }
  288. // return null if no channel is not found
  289. return nil, errors.New("channel not found")
  290. }
  291. func CacheGetChannel(id int) (*Channel, error) {
  292. if !common.MemoryCacheEnabled {
  293. return GetChannelById(id, true)
  294. }
  295. channelSyncLock.RLock()
  296. defer channelSyncLock.RUnlock()
  297. c, ok := channelsIDM[id]
  298. if !ok {
  299. return nil, fmt.Errorf("渠道# %d,已不存在", id)
  300. }
  301. if c.Status != common.ChannelStatusEnabled {
  302. return nil, fmt.Errorf("渠道# %d,已被禁用", id)
  303. }
  304. return c, nil
  305. }
  306. func CacheGetChannelInfo(id int) (*ChannelInfo, error) {
  307. if !common.MemoryCacheEnabled {
  308. channel, err := GetChannelById(id, true)
  309. if err != nil {
  310. return nil, err
  311. }
  312. return &channel.ChannelInfo, nil
  313. }
  314. channelSyncLock.RLock()
  315. defer channelSyncLock.RUnlock()
  316. c, ok := channelsIDM[id]
  317. if !ok {
  318. return nil, fmt.Errorf("渠道# %d,已不存在", id)
  319. }
  320. if c.Status != common.ChannelStatusEnabled {
  321. return nil, fmt.Errorf("渠道# %d,已被禁用", id)
  322. }
  323. return &c.ChannelInfo, nil
  324. }
  325. func CacheUpdateChannelStatus(id int, status int) {
  326. if !common.MemoryCacheEnabled {
  327. return
  328. }
  329. channelSyncLock.Lock()
  330. defer channelSyncLock.Unlock()
  331. if channel, ok := channelsIDM[id]; ok {
  332. channel.Status = status
  333. }
  334. }
  335. func CacheUpdateChannel(channel *Channel) {
  336. if !common.MemoryCacheEnabled {
  337. return
  338. }
  339. channelSyncLock.Lock()
  340. defer channelSyncLock.Unlock()
  341. if channel == nil {
  342. return
  343. }
  344. println("CacheUpdateChannel:", channel.Id, channel.Name, channel.Status, channel.ChannelInfo.MultiKeyPollingIndex)
  345. println("before:", channelsIDM[channel.Id].ChannelInfo.MultiKeyPollingIndex)
  346. channelsIDM[channel.Id] = channel
  347. println("after :", channelsIDM[channel.Id].ChannelInfo.MultiKeyPollingIndex)
  348. }