ability.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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. func GetRandomSatisfiedChannel(group string, model string, retry int) (*Channel, error) {
  90. var abilities []Ability
  91. var err error = nil
  92. channelQuery, err := getChannelQuery(group, model, retry)
  93. if err != nil {
  94. return nil, err
  95. }
  96. if common.UsingSQLite || common.UsingPostgreSQL {
  97. err = channelQuery.Order("weight DESC").Find(&abilities).Error
  98. } else {
  99. err = channelQuery.Order("weight DESC").Find(&abilities).Error
  100. }
  101. if err != nil {
  102. return nil, err
  103. }
  104. channel := Channel{}
  105. if len(abilities) > 0 {
  106. // Randomly choose one
  107. weightSum := uint(0)
  108. for _, ability_ := range abilities {
  109. weightSum += ability_.Weight + 10
  110. }
  111. // Randomly choose one
  112. weight := common.GetRandomInt(int(weightSum))
  113. for _, ability_ := range abilities {
  114. weight -= int(ability_.Weight) + 10
  115. //log.Printf("weight: %d, ability weight: %d", weight, *ability_.Weight)
  116. if weight <= 0 {
  117. channel.Id = ability_.ChannelId
  118. break
  119. }
  120. }
  121. } else {
  122. return nil, errors.New("channel not found")
  123. }
  124. err = DB.First(&channel, "id = ?", channel.Id).Error
  125. return &channel, err
  126. }
  127. func (channel *Channel) AddAbilities() error {
  128. models_ := strings.Split(channel.Models, ",")
  129. groups_ := strings.Split(channel.Group, ",")
  130. abilitySet := make(map[string]struct{})
  131. abilities := make([]Ability, 0, len(models_))
  132. for _, model := range models_ {
  133. for _, group := range groups_ {
  134. key := group + "|" + model
  135. if _, exists := abilitySet[key]; exists {
  136. continue
  137. }
  138. abilitySet[key] = struct{}{}
  139. ability := Ability{
  140. Group: group,
  141. Model: model,
  142. ChannelId: channel.Id,
  143. Enabled: channel.Status == common.ChannelStatusEnabled,
  144. Priority: channel.Priority,
  145. Weight: uint(channel.GetWeight()),
  146. Tag: channel.Tag,
  147. }
  148. abilities = append(abilities, ability)
  149. }
  150. }
  151. if len(abilities) == 0 {
  152. return nil
  153. }
  154. for _, chunk := range lo.Chunk(abilities, 50) {
  155. err := DB.Clauses(clause.OnConflict{DoNothing: true}).Create(&chunk).Error
  156. if err != nil {
  157. return err
  158. }
  159. }
  160. return nil
  161. }
  162. func (channel *Channel) DeleteAbilities() error {
  163. return DB.Where("channel_id = ?", channel.Id).Delete(&Ability{}).Error
  164. }
  165. // UpdateAbilities updates abilities of this channel.
  166. // Make sure the channel is completed before calling this function.
  167. func (channel *Channel) UpdateAbilities(tx *gorm.DB) error {
  168. isNewTx := false
  169. // 如果没有传入事务,创建新的事务
  170. if tx == nil {
  171. tx = DB.Begin()
  172. if tx.Error != nil {
  173. return tx.Error
  174. }
  175. isNewTx = true
  176. defer func() {
  177. if r := recover(); r != nil {
  178. tx.Rollback()
  179. }
  180. }()
  181. }
  182. // First delete all abilities of this channel
  183. err := tx.Where("channel_id = ?", channel.Id).Delete(&Ability{}).Error
  184. if err != nil {
  185. if isNewTx {
  186. tx.Rollback()
  187. }
  188. return err
  189. }
  190. // Then add new abilities
  191. models_ := strings.Split(channel.Models, ",")
  192. groups_ := strings.Split(channel.Group, ",")
  193. abilitySet := make(map[string]struct{})
  194. abilities := make([]Ability, 0, len(models_))
  195. for _, model := range models_ {
  196. for _, group := range groups_ {
  197. key := group + "|" + model
  198. if _, exists := abilitySet[key]; exists {
  199. continue
  200. }
  201. abilitySet[key] = struct{}{}
  202. ability := Ability{
  203. Group: group,
  204. Model: model,
  205. ChannelId: channel.Id,
  206. Enabled: channel.Status == common.ChannelStatusEnabled,
  207. Priority: channel.Priority,
  208. Weight: uint(channel.GetWeight()),
  209. Tag: channel.Tag,
  210. }
  211. abilities = append(abilities, ability)
  212. }
  213. }
  214. if len(abilities) > 0 {
  215. for _, chunk := range lo.Chunk(abilities, 50) {
  216. err = tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&chunk).Error
  217. if err != nil {
  218. if isNewTx {
  219. tx.Rollback()
  220. }
  221. return err
  222. }
  223. }
  224. }
  225. // 如果是新创建的事务,需要提交
  226. if isNewTx {
  227. return tx.Commit().Error
  228. }
  229. return nil
  230. }
  231. func UpdateAbilityStatus(channelId int, status bool) error {
  232. return DB.Model(&Ability{}).Where("channel_id = ?", channelId).Select("enabled").Update("enabled", status).Error
  233. }
  234. func UpdateAbilityStatusByTag(tag string, status bool) error {
  235. return DB.Model(&Ability{}).Where("tag = ?", tag).Select("enabled").Update("enabled", status).Error
  236. }
  237. func UpdateAbilityByTag(tag string, newTag *string, priority *int64, weight *uint) error {
  238. ability := Ability{}
  239. if newTag != nil {
  240. ability.Tag = newTag
  241. }
  242. if priority != nil {
  243. ability.Priority = priority
  244. }
  245. if weight != nil {
  246. ability.Weight = *weight
  247. }
  248. return DB.Model(&Ability{}).Where("tag = ?", tag).Updates(ability).Error
  249. }
  250. var fixLock = sync.Mutex{}
  251. func FixAbility() (int, int, error) {
  252. lock := fixLock.TryLock()
  253. if !lock {
  254. return 0, 0, errors.New("已经有一个修复任务在运行中,请稍后再试")
  255. }
  256. defer fixLock.Unlock()
  257. var channels []*Channel
  258. // Find all channels
  259. err := DB.Model(&Channel{}).Find(&channels).Error
  260. if err != nil {
  261. return 0, 0, err
  262. }
  263. if len(channels) == 0 {
  264. return 0, 0, nil
  265. }
  266. successCount := 0
  267. failCount := 0
  268. for _, chunk := range lo.Chunk(channels, 50) {
  269. ids := lo.Map(chunk, func(c *Channel, _ int) int { return c.Id })
  270. // Delete all abilities of this channel
  271. err = DB.Where("channel_id IN ?", ids).Delete(&Ability{}).Error
  272. if err != nil {
  273. common.SysError(fmt.Sprintf("Delete abilities failed: %s", err.Error()))
  274. failCount += len(chunk)
  275. continue
  276. }
  277. // Then add new abilities
  278. for _, channel := range chunk {
  279. err = channel.AddAbilities()
  280. if err != nil {
  281. common.SysError(fmt.Sprintf("Add abilities for channel %d failed: %s", channel.Id, err.Error()))
  282. failCount++
  283. } else {
  284. successCount++
  285. }
  286. }
  287. }
  288. InitChannelCache()
  289. return successCount, failCount, nil
  290. }