ability.go 9.1 KB

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