ability.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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, nil
  123. }
  124. err = DB.First(&channel, "id = ?", channel.Id).Error
  125. return &channel, err
  126. }
  127. func (channel *Channel) AddAbilities(tx *gorm.DB) 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. // choose DB or provided tx
  155. useDB := DB
  156. if tx != nil {
  157. useDB = tx
  158. }
  159. for _, chunk := range lo.Chunk(abilities, 50) {
  160. err := useDB.Clauses(clause.OnConflict{DoNothing: true}).Create(&chunk).Error
  161. if err != nil {
  162. return err
  163. }
  164. }
  165. return nil
  166. }
  167. func (channel *Channel) DeleteAbilities() error {
  168. return DB.Where("channel_id = ?", channel.Id).Delete(&Ability{}).Error
  169. }
  170. // UpdateAbilities updates abilities of this channel.
  171. // Make sure the channel is completed before calling this function.
  172. func (channel *Channel) UpdateAbilities(tx *gorm.DB) error {
  173. isNewTx := false
  174. // 如果没有传入事务,创建新的事务
  175. if tx == nil {
  176. tx = DB.Begin()
  177. if tx.Error != nil {
  178. return tx.Error
  179. }
  180. isNewTx = true
  181. defer func() {
  182. if r := recover(); r != nil {
  183. tx.Rollback()
  184. }
  185. }()
  186. }
  187. // First delete all abilities of this channel
  188. err := tx.Where("channel_id = ?", channel.Id).Delete(&Ability{}).Error
  189. if err != nil {
  190. if isNewTx {
  191. tx.Rollback()
  192. }
  193. return err
  194. }
  195. // Then add new abilities
  196. models_ := strings.Split(channel.Models, ",")
  197. groups_ := strings.Split(channel.Group, ",")
  198. abilitySet := make(map[string]struct{})
  199. abilities := make([]Ability, 0, len(models_))
  200. for _, model := range models_ {
  201. for _, group := range groups_ {
  202. key := group + "|" + model
  203. if _, exists := abilitySet[key]; exists {
  204. continue
  205. }
  206. abilitySet[key] = struct{}{}
  207. ability := Ability{
  208. Group: group,
  209. Model: model,
  210. ChannelId: channel.Id,
  211. Enabled: channel.Status == common.ChannelStatusEnabled,
  212. Priority: channel.Priority,
  213. Weight: uint(channel.GetWeight()),
  214. Tag: channel.Tag,
  215. }
  216. abilities = append(abilities, ability)
  217. }
  218. }
  219. if len(abilities) > 0 {
  220. for _, chunk := range lo.Chunk(abilities, 50) {
  221. err = tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&chunk).Error
  222. if err != nil {
  223. if isNewTx {
  224. tx.Rollback()
  225. }
  226. return err
  227. }
  228. }
  229. }
  230. // 如果是新创建的事务,需要提交
  231. if isNewTx {
  232. return tx.Commit().Error
  233. }
  234. return nil
  235. }
  236. func UpdateAbilityStatus(channelId int, status bool) error {
  237. return DB.Model(&Ability{}).Where("channel_id = ?", channelId).Select("enabled").Update("enabled", status).Error
  238. }
  239. func UpdateAbilityStatusByTag(tag string, status bool) error {
  240. return DB.Model(&Ability{}).Where("tag = ?", tag).Select("enabled").Update("enabled", status).Error
  241. }
  242. func UpdateAbilityByTag(tag string, newTag *string, priority *int64, weight *uint) error {
  243. ability := Ability{}
  244. if newTag != nil {
  245. ability.Tag = newTag
  246. }
  247. if priority != nil {
  248. ability.Priority = priority
  249. }
  250. if weight != nil {
  251. ability.Weight = *weight
  252. }
  253. return DB.Model(&Ability{}).Where("tag = ?", tag).Updates(ability).Error
  254. }
  255. var fixLock = sync.Mutex{}
  256. func FixAbility() (int, int, error) {
  257. lock := fixLock.TryLock()
  258. if !lock {
  259. return 0, 0, errors.New("已经有一个修复任务在运行中,请稍后再试")
  260. }
  261. defer fixLock.Unlock()
  262. // truncate abilities table
  263. if common.UsingSQLite {
  264. err := DB.Exec("DELETE FROM abilities").Error
  265. if err != nil {
  266. common.SysLog(fmt.Sprintf("Delete abilities failed: %s", err.Error()))
  267. return 0, 0, err
  268. }
  269. } else {
  270. err := DB.Exec("TRUNCATE TABLE abilities").Error
  271. if err != nil {
  272. common.SysLog(fmt.Sprintf("Truncate abilities failed: %s", err.Error()))
  273. return 0, 0, err
  274. }
  275. }
  276. var channels []*Channel
  277. // Find all channels
  278. err := DB.Model(&Channel{}).Find(&channels).Error
  279. if err != nil {
  280. return 0, 0, err
  281. }
  282. if len(channels) == 0 {
  283. return 0, 0, nil
  284. }
  285. successCount := 0
  286. failCount := 0
  287. for _, chunk := range lo.Chunk(channels, 50) {
  288. ids := lo.Map(chunk, func(c *Channel, _ int) int { return c.Id })
  289. // Delete all abilities of this channel
  290. err = DB.Where("channel_id IN ?", ids).Delete(&Ability{}).Error
  291. if err != nil {
  292. common.SysLog(fmt.Sprintf("Delete abilities failed: %s", err.Error()))
  293. failCount += len(chunk)
  294. continue
  295. }
  296. // Then add new abilities
  297. for _, channel := range chunk {
  298. err = channel.AddAbilities(nil)
  299. if err != nil {
  300. common.SysLog(fmt.Sprintf("Add abilities for channel %d failed: %s", channel.Id, err.Error()))
  301. failCount++
  302. } else {
  303. successCount++
  304. }
  305. }
  306. }
  307. InitChannelCache()
  308. return successCount, failCount, nil
  309. }