ability.go 8.6 KB

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