ability.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. package model
  2. import (
  3. "errors"
  4. "fmt"
  5. "one-api/common"
  6. "strings"
  7. "sync"
  8. "github.com/samber/lo"
  9. "gorm.io/gorm"
  10. "gorm.io/gorm/clause"
  11. )
  12. type Ability struct {
  13. Group string `json:"group" gorm:"type:varchar(64);primaryKey;autoIncrement:false"`
  14. Model string `json:"model" gorm:"type:varchar(255);primaryKey;autoIncrement:false"`
  15. ChannelId int `json:"channel_id" gorm:"primaryKey;autoIncrement:false;index"`
  16. Enabled bool `json:"enabled"`
  17. Priority *int64 `json:"priority" gorm:"bigint;default:0;index"`
  18. Weight uint `json:"weight" gorm:"default:0;index"`
  19. Tag *string `json:"tag" gorm:"index"`
  20. }
  21. type AbilityWithChannel struct {
  22. Ability
  23. ChannelType int `json:"channel_type"`
  24. }
  25. func GetAllEnableAbilityWithChannels() ([]AbilityWithChannel, error) {
  26. var abilities []AbilityWithChannel
  27. err := DB.Table("abilities").
  28. Select("abilities.*, channels.type as channel_type").
  29. Joins("left join channels on abilities.channel_id = channels.id").
  30. Where("abilities.enabled = ?", true).
  31. Scan(&abilities).Error
  32. return abilities, err
  33. }
  34. func GetGroupEnabledModels(group string) []string {
  35. var models []string
  36. // Find distinct models
  37. DB.Table("abilities").Where(commonGroupCol+" = ? and enabled = ?", group, true).Distinct("model").Pluck("model", &models)
  38. return models
  39. }
  40. func GetEnabledModels() []string {
  41. var models []string
  42. // Find distinct models
  43. DB.Table("abilities").Where("enabled = ?", true).Distinct("model").Pluck("model", &models)
  44. return models
  45. }
  46. func GetAllEnableAbilities() []Ability {
  47. var abilities []Ability
  48. DB.Find(&abilities, "enabled = ?", true)
  49. return abilities
  50. }
  51. func getPriority(group string, model string, retry int) (int, error) {
  52. var priorities []int
  53. err := DB.Model(&Ability{}).
  54. Select("DISTINCT(priority)").
  55. Where(commonGroupCol+" = ? and model = ? and enabled = ?", group, model, true).
  56. Order("priority DESC"). // 按优先级降序排序
  57. Pluck("priority", &priorities).Error // Pluck用于将查询的结果直接扫描到一个切片中
  58. if err != nil {
  59. // 处理错误
  60. return 0, err
  61. }
  62. if len(priorities) == 0 {
  63. // 如果没有查询到优先级,则返回错误
  64. return 0, errors.New("数据库一致性被破坏")
  65. }
  66. // 确定要使用的优先级
  67. var priorityToUse int
  68. if retry >= len(priorities) {
  69. // 如果重试次数大于优先级数,则使用最小的优先级
  70. priorityToUse = priorities[len(priorities)-1]
  71. } else {
  72. priorityToUse = priorities[retry]
  73. }
  74. return priorityToUse, nil
  75. }
  76. func getChannelQuery(group string, model string, retry int) (*gorm.DB, error) {
  77. maxPrioritySubQuery := DB.Model(&Ability{}).Select("MAX(priority)").Where(commonGroupCol+" = ? and model = ? and enabled = ?", group, model, true)
  78. channelQuery := DB.Where(commonGroupCol+" = ? and model = ? and enabled = ? and priority = (?)", group, model, true, maxPrioritySubQuery)
  79. if retry != 0 {
  80. priority, err := getPriority(group, model, retry)
  81. if err != nil {
  82. return nil, err
  83. } else {
  84. channelQuery = DB.Where(commonGroupCol+" = ? and model = ? and enabled = ? and priority = ?", group, model, true, priority)
  85. }
  86. }
  87. return channelQuery, nil
  88. }
  89. // 修改GetRandomSatisfiedChannel函数,添加渠道标签过滤参数
  90. func GetRandomSatisfiedChannel(group string, model string, retry int, channelTag *string) (*Channel, error) {
  91. var abilities []Ability
  92. var err error = nil
  93. channelQuery, err := getChannelQuery(group, model, retry)
  94. if err != nil {
  95. return nil, err
  96. }
  97. // 如果提供了渠道标签,则添加标签过滤条件
  98. if channelTag != nil && *channelTag != "" {
  99. channelQuery = channelQuery.Where("tag = ? OR tag IS NULL", *channelTag)
  100. }
  101. if common.UsingSQLite || common.UsingPostgreSQL {
  102. err = channelQuery.Order("weight DESC").Find(&abilities).Error
  103. } else {
  104. err = channelQuery.Order("weight DESC").Find(&abilities).Error
  105. }
  106. if err != nil {
  107. return nil, err
  108. }
  109. // 过滤符合标签要求的渠道
  110. var filteredAbilities []Ability
  111. for _, ability := range abilities {
  112. // 如果提供了渠道标签,只考虑匹配标签的渠道
  113. if channelTag != nil && *channelTag != "" {
  114. // 如果渠道标签不匹配,则跳过
  115. if ability.Tag != nil && *ability.Tag != "" && *ability.Tag != *channelTag {
  116. continue
  117. }
  118. }
  119. filteredAbilities = append(filteredAbilities, ability)
  120. }
  121. // 如果没有符合条件的渠道,返回错误
  122. if len(filteredAbilities) == 0 {
  123. if channelTag != nil && *channelTag != "" {
  124. return nil, fmt.Errorf("没有找到标签为 '%s' 的可用渠道", *channelTag)
  125. }
  126. return nil, errors.New("channel not found")
  127. }
  128. channel := Channel{}
  129. if len(filteredAbilities) > 0 {
  130. // Randomly choose one based on weight
  131. weightSum := uint(0)
  132. for _, ability := range filteredAbilities {
  133. weightSum += ability.Weight + 10 // 平滑系数
  134. }
  135. // 如果总权重为0,则平均分配权重
  136. if weightSum == 0 {
  137. // 随机选择一个渠道
  138. randomIndex := common.GetRandomInt(len(filteredAbilities))
  139. channel.Id = filteredAbilities[randomIndex].ChannelId
  140. } else {
  141. // 按权重随机选择
  142. randomWeight := common.GetRandomInt(int(weightSum))
  143. for _, ability := range filteredAbilities {
  144. randomWeight -= int(ability.Weight) + 10
  145. if randomWeight < 0 {
  146. channel.Id = ability.ChannelId
  147. break
  148. }
  149. }
  150. }
  151. } else {
  152. return nil, errors.New("channel not found")
  153. }
  154. err = DB.First(&channel, "id = ?", channel.Id).Error
  155. return &channel, err
  156. }
  157. func (channel *Channel) AddAbilities() error {
  158. models_ := strings.Split(channel.Models, ",")
  159. groups_ := strings.Split(channel.Group, ",")
  160. abilitySet := make(map[string]struct{})
  161. abilities := make([]Ability, 0, len(models_))
  162. for _, model := range models_ {
  163. for _, group := range groups_ {
  164. key := group + "|" + model
  165. if _, exists := abilitySet[key]; exists {
  166. continue
  167. }
  168. abilitySet[key] = struct{}{}
  169. ability := Ability{
  170. Group: group,
  171. Model: model,
  172. ChannelId: channel.Id,
  173. Enabled: channel.Status == common.ChannelStatusEnabled,
  174. Priority: channel.Priority,
  175. Weight: uint(channel.GetWeight()),
  176. Tag: channel.Tag,
  177. }
  178. abilities = append(abilities, ability)
  179. }
  180. }
  181. if len(abilities) == 0 {
  182. return nil
  183. }
  184. for _, chunk := range lo.Chunk(abilities, 50) {
  185. err := DB.Clauses(clause.OnConflict{DoNothing: true}).Create(&chunk).Error
  186. if err != nil {
  187. return err
  188. }
  189. }
  190. return nil
  191. }
  192. func (channel *Channel) DeleteAbilities() error {
  193. return DB.Where("channel_id = ?", channel.Id).Delete(&Ability{}).Error
  194. }
  195. // UpdateAbilities updates abilities of this channel.
  196. // Make sure the channel is completed before calling this function.
  197. func (channel *Channel) UpdateAbilities(tx *gorm.DB) error {
  198. isNewTx := false
  199. // 如果没有传入事务,创建新的事务
  200. if tx == nil {
  201. tx = DB.Begin()
  202. if tx.Error != nil {
  203. return tx.Error
  204. }
  205. isNewTx = true
  206. defer func() {
  207. if r := recover(); r != nil {
  208. tx.Rollback()
  209. }
  210. }()
  211. }
  212. // First delete all abilities of this channel
  213. err := tx.Where("channel_id = ?", channel.Id).Delete(&Ability{}).Error
  214. if err != nil {
  215. if isNewTx {
  216. tx.Rollback()
  217. }
  218. return err
  219. }
  220. // Then add new abilities
  221. models_ := strings.Split(channel.Models, ",")
  222. groups_ := strings.Split(channel.Group, ",")
  223. abilitySet := make(map[string]struct{})
  224. abilities := make([]Ability, 0, len(models_))
  225. for _, model := range models_ {
  226. for _, group := range groups_ {
  227. key := group + "|" + model
  228. if _, exists := abilitySet[key]; exists {
  229. continue
  230. }
  231. abilitySet[key] = struct{}{}
  232. ability := Ability{
  233. Group: group,
  234. Model: model,
  235. ChannelId: channel.Id,
  236. Enabled: channel.Status == common.ChannelStatusEnabled,
  237. Priority: channel.Priority,
  238. Weight: uint(channel.GetWeight()),
  239. Tag: channel.Tag,
  240. }
  241. abilities = append(abilities, ability)
  242. }
  243. }
  244. if len(abilities) > 0 {
  245. for _, chunk := range lo.Chunk(abilities, 50) {
  246. err = tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&chunk).Error
  247. if err != nil {
  248. if isNewTx {
  249. tx.Rollback()
  250. }
  251. return err
  252. }
  253. }
  254. }
  255. // 如果是新创建的事务,需要提交
  256. if isNewTx {
  257. return tx.Commit().Error
  258. }
  259. return nil
  260. }
  261. func UpdateAbilityStatus(channelId int, status bool) error {
  262. return DB.Model(&Ability{}).Where("channel_id = ?", channelId).Select("enabled").Update("enabled", status).Error
  263. }
  264. func UpdateAbilityStatusByTag(tag string, status bool) error {
  265. return DB.Model(&Ability{}).Where("tag = ?", tag).Select("enabled").Update("enabled", status).Error
  266. }
  267. func UpdateAbilityByTag(tag string, newTag *string, priority *int64, weight *uint) error {
  268. ability := Ability{}
  269. if newTag != nil {
  270. ability.Tag = newTag
  271. }
  272. if priority != nil {
  273. ability.Priority = priority
  274. }
  275. if weight != nil {
  276. ability.Weight = *weight
  277. }
  278. return DB.Model(&Ability{}).Where("tag = ?", tag).Updates(ability).Error
  279. }
  280. var fixLock = sync.Mutex{}
  281. func FixAbility() (int, int, error) {
  282. lock := fixLock.TryLock()
  283. if !lock {
  284. return 0, 0, errors.New("已经有一个修复任务在运行中,请稍后再试")
  285. }
  286. defer fixLock.Unlock()
  287. var channels []*Channel
  288. // Find all channels
  289. err := DB.Model(&Channel{}).Find(&channels).Error
  290. if err != nil {
  291. return 0, 0, err
  292. }
  293. if len(channels) == 0 {
  294. return 0, 0, nil
  295. }
  296. successCount := 0
  297. failCount := 0
  298. for _, chunk := range lo.Chunk(channels, 50) {
  299. ids := lo.Map(chunk, func(c *Channel, _ int) int { return c.Id })
  300. // Delete all abilities of this channel
  301. err = DB.Where("channel_id IN ?", ids).Delete(&Ability{}).Error
  302. if err != nil {
  303. common.SysError(fmt.Sprintf("Delete abilities failed: %s", err.Error()))
  304. failCount += len(chunk)
  305. continue
  306. }
  307. // Then add new abilities
  308. for _, channel := range chunk {
  309. err = channel.AddAbilities()
  310. if err != nil {
  311. common.SysError(fmt.Sprintf("Add abilities for channel %d failed: %s", channel.Id, err.Error()))
  312. failCount++
  313. } else {
  314. successCount++
  315. }
  316. }
  317. }
  318. InitChannelCache()
  319. return successCount, failCount, nil
  320. }