ability.go 9.6 KB

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