ability.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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. abilitySet := make(map[string]struct{})
  121. abilities := make([]Ability, 0, len(models_))
  122. for _, model := range models_ {
  123. for _, group := range groups_ {
  124. key := strings.ToLower(group) + "|" + strings.ToLower(model)
  125. if _, exists := abilitySet[key]; exists {
  126. continue
  127. }
  128. abilitySet[key] = struct{}{}
  129. ability := Ability{
  130. Group: group,
  131. Model: model,
  132. ChannelId: channel.Id,
  133. Enabled: channel.Status == common.ChannelStatusEnabled,
  134. Priority: channel.Priority,
  135. Weight: uint(channel.GetWeight()),
  136. Tag: channel.Tag,
  137. }
  138. abilities = append(abilities, ability)
  139. }
  140. }
  141. if len(abilities) == 0 {
  142. return nil
  143. }
  144. for _, chunk := range lo.Chunk(abilities, 50) {
  145. err := DB.Create(&chunk).Error
  146. if err != nil {
  147. return err
  148. }
  149. }
  150. return nil
  151. }
  152. func (channel *Channel) DeleteAbilities() error {
  153. return DB.Where("channel_id = ?", channel.Id).Delete(&Ability{}).Error
  154. }
  155. // UpdateAbilities updates abilities of this channel.
  156. // Make sure the channel is completed before calling this function.
  157. func (channel *Channel) UpdateAbilities(tx *gorm.DB) error {
  158. isNewTx := false
  159. // 如果没有传入事务,创建新的事务
  160. if tx == nil {
  161. tx = DB.Begin()
  162. if tx.Error != nil {
  163. return tx.Error
  164. }
  165. isNewTx = true
  166. defer func() {
  167. if r := recover(); r != nil {
  168. tx.Rollback()
  169. }
  170. }()
  171. }
  172. // First delete all abilities of this channel
  173. err := tx.Where("channel_id = ?", channel.Id).Delete(&Ability{}).Error
  174. if err != nil {
  175. if isNewTx {
  176. tx.Rollback()
  177. }
  178. return err
  179. }
  180. // Then add new abilities
  181. models_ := strings.Split(channel.Models, ",")
  182. groups_ := strings.Split(channel.Group, ",")
  183. abilitySet := make(map[string]struct{})
  184. abilities := make([]Ability, 0, len(models_))
  185. for _, model := range models_ {
  186. for _, group := range groups_ {
  187. key := strings.ToLower(group) + "|" + strings.ToLower(model)
  188. if _, exists := abilitySet[key]; exists {
  189. continue
  190. }
  191. abilitySet[key] = struct{}{}
  192. ability := Ability{
  193. Group: group,
  194. Model: model,
  195. ChannelId: channel.Id,
  196. Enabled: channel.Status == common.ChannelStatusEnabled,
  197. Priority: channel.Priority,
  198. Weight: uint(channel.GetWeight()),
  199. Tag: channel.Tag,
  200. }
  201. abilities = append(abilities, ability)
  202. }
  203. }
  204. if len(abilities) > 0 {
  205. for _, chunk := range lo.Chunk(abilities, 50) {
  206. err = tx.Create(&chunk).Error
  207. if err != nil {
  208. if isNewTx {
  209. tx.Rollback()
  210. }
  211. return err
  212. }
  213. }
  214. }
  215. // 如果是新创建的事务,需要提交
  216. if isNewTx {
  217. return tx.Commit().Error
  218. }
  219. return nil
  220. }
  221. func UpdateAbilityStatus(channelId int, status bool) error {
  222. return DB.Model(&Ability{}).Where("channel_id = ?", channelId).Select("enabled").Update("enabled", status).Error
  223. }
  224. func UpdateAbilityStatusByTag(tag string, status bool) error {
  225. return DB.Model(&Ability{}).Where("tag = ?", tag).Select("enabled").Update("enabled", status).Error
  226. }
  227. func UpdateAbilityByTag(tag string, newTag *string, priority *int64, weight *uint) error {
  228. ability := Ability{}
  229. if newTag != nil {
  230. ability.Tag = newTag
  231. }
  232. if priority != nil {
  233. ability.Priority = priority
  234. }
  235. if weight != nil {
  236. ability.Weight = *weight
  237. }
  238. return DB.Model(&Ability{}).Where("tag = ?", tag).Updates(ability).Error
  239. }
  240. func FixAbility() (int, error) {
  241. var channelIds []int
  242. count := 0
  243. // Find all channel ids from channel table
  244. err := DB.Model(&Channel{}).Pluck("id", &channelIds).Error
  245. if err != nil {
  246. common.SysError(fmt.Sprintf("Get channel ids from channel table failed: %s", err.Error()))
  247. return 0, err
  248. }
  249. // Delete abilities of channels that are not in channel table - in batches to avoid too many placeholders
  250. if len(channelIds) > 0 {
  251. // Process deletion in chunks to avoid "too many placeholders" error
  252. for _, chunk := range lo.Chunk(channelIds, 100) {
  253. err = DB.Where("channel_id NOT IN (?)", chunk).Delete(&Ability{}).Error
  254. if err != nil {
  255. common.SysError(fmt.Sprintf("Delete abilities of channels (batch) that are not in channel table failed: %s", err.Error()))
  256. return 0, err
  257. }
  258. }
  259. } else {
  260. // If no channels exist, delete all abilities
  261. err = DB.Delete(&Ability{}).Error
  262. if err != nil {
  263. common.SysError(fmt.Sprintf("Delete all abilities failed: %s", err.Error()))
  264. return 0, err
  265. }
  266. common.SysLog("Delete all abilities successfully")
  267. return 0, nil
  268. }
  269. common.SysLog(fmt.Sprintf("Delete abilities of channels that are not in channel table successfully, ids: %v", channelIds))
  270. count += len(channelIds)
  271. // Use channelIds to find channel not in abilities table
  272. var abilityChannelIds []int
  273. err = DB.Table("abilities").Distinct("channel_id").Pluck("channel_id", &abilityChannelIds).Error
  274. if err != nil {
  275. common.SysError(fmt.Sprintf("Get channel ids from abilities table failed: %s", err.Error()))
  276. return count, err
  277. }
  278. var channels []Channel
  279. if len(abilityChannelIds) == 0 {
  280. err = DB.Find(&channels).Error
  281. } else {
  282. // Process query in chunks to avoid "too many placeholders" error
  283. err = nil
  284. for _, chunk := range lo.Chunk(abilityChannelIds, 100) {
  285. var channelsChunk []Channel
  286. err = DB.Where("id NOT IN (?)", chunk).Find(&channelsChunk).Error
  287. if err != nil {
  288. common.SysError(fmt.Sprintf("Find channels not in abilities table failed: %s", err.Error()))
  289. return count, err
  290. }
  291. channels = append(channels, channelsChunk...)
  292. }
  293. }
  294. for _, channel := range channels {
  295. err := channel.UpdateAbilities(nil)
  296. if err != nil {
  297. common.SysError(fmt.Sprintf("Update abilities of channel %d failed: %s", channel.Id, err.Error()))
  298. } else {
  299. common.SysLog(fmt.Sprintf("Update abilities of channel %d successfully", channel.Id))
  300. count++
  301. }
  302. }
  303. InitChannelCache()
  304. return count, nil
  305. }