channel.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. package model
  2. import (
  3. "encoding/json"
  4. "one-api/common"
  5. "strings"
  6. "sync"
  7. "gorm.io/gorm"
  8. )
  9. type Channel struct {
  10. Id int `json:"id"`
  11. Type int `json:"type" gorm:"default:0"`
  12. Key string `json:"key" gorm:"not null"`
  13. OpenAIOrganization *string `json:"openai_organization"`
  14. TestModel *string `json:"test_model"`
  15. Status int `json:"status" gorm:"default:1"`
  16. Name string `json:"name" gorm:"index"`
  17. Weight *uint `json:"weight" gorm:"default:0"`
  18. CreatedTime int64 `json:"created_time" gorm:"bigint"`
  19. TestTime int64 `json:"test_time" gorm:"bigint"`
  20. ResponseTime int `json:"response_time"` // in milliseconds
  21. BaseURL *string `json:"base_url" gorm:"column:base_url;default:''"`
  22. Other string `json:"other"`
  23. Balance float64 `json:"balance"` // in USD
  24. BalanceUpdatedTime int64 `json:"balance_updated_time" gorm:"bigint"`
  25. Models string `json:"models"`
  26. Group string `json:"group" gorm:"type:varchar(64);default:'default'"`
  27. UsedQuota int64 `json:"used_quota" gorm:"bigint;default:0"`
  28. ModelMapping *string `json:"model_mapping" gorm:"type:text"`
  29. //MaxInputTokens *int `json:"max_input_tokens" gorm:"default:0"`
  30. StatusCodeMapping *string `json:"status_code_mapping" gorm:"type:varchar(1024);default:''"`
  31. Priority *int64 `json:"priority" gorm:"bigint;default:0"`
  32. AutoBan *int `json:"auto_ban" gorm:"default:1"`
  33. OtherInfo string `json:"other_info"`
  34. Tag *string `json:"tag" gorm:"index"`
  35. Setting *string `json:"setting" gorm:"type:text"`
  36. }
  37. func (channel *Channel) GetModels() []string {
  38. if channel.Models == "" {
  39. return []string{}
  40. }
  41. return strings.Split(strings.Trim(channel.Models, ","), ",")
  42. }
  43. func (channel *Channel) GetOtherInfo() map[string]interface{} {
  44. otherInfo := make(map[string]interface{})
  45. if channel.OtherInfo != "" {
  46. err := json.Unmarshal([]byte(channel.OtherInfo), &otherInfo)
  47. if err != nil {
  48. common.SysError("failed to unmarshal other info: " + err.Error())
  49. }
  50. }
  51. return otherInfo
  52. }
  53. func (channel *Channel) SetOtherInfo(otherInfo map[string]interface{}) {
  54. otherInfoBytes, err := json.Marshal(otherInfo)
  55. if err != nil {
  56. common.SysError("failed to marshal other info: " + err.Error())
  57. return
  58. }
  59. channel.OtherInfo = string(otherInfoBytes)
  60. }
  61. func (channel *Channel) GetTag() string {
  62. if channel.Tag == nil {
  63. return ""
  64. }
  65. return *channel.Tag
  66. }
  67. func (channel *Channel) SetTag(tag string) {
  68. channel.Tag = &tag
  69. }
  70. func (channel *Channel) GetAutoBan() bool {
  71. if channel.AutoBan == nil {
  72. return false
  73. }
  74. return *channel.AutoBan == 1
  75. }
  76. func (channel *Channel) Save() error {
  77. return DB.Save(channel).Error
  78. }
  79. func GetAllChannels(startIdx int, num int, selectAll bool, idSort bool) ([]*Channel, error) {
  80. var channels []*Channel
  81. var err error
  82. order := "priority desc"
  83. if idSort {
  84. order = "id desc"
  85. }
  86. if selectAll {
  87. err = DB.Order(order).Find(&channels).Error
  88. } else {
  89. err = DB.Order(order).Limit(num).Offset(startIdx).Omit("key").Find(&channels).Error
  90. }
  91. return channels, err
  92. }
  93. func GetChannelsByTag(tag string, idSort bool) ([]*Channel, error) {
  94. var channels []*Channel
  95. order := "priority desc"
  96. if idSort {
  97. order = "id desc"
  98. }
  99. err := DB.Where("tag = ?", tag).Order(order).Find(&channels).Error
  100. return channels, err
  101. }
  102. func SearchChannels(keyword string, group string, model string, idSort bool) ([]*Channel, error) {
  103. var channels []*Channel
  104. modelsCol := "`models`"
  105. // 如果是 PostgreSQL,使用双引号
  106. if common.UsingPostgreSQL {
  107. keyCol = `"key"`
  108. modelsCol = `"models"`
  109. }
  110. order := "priority desc"
  111. if idSort {
  112. order = "id desc"
  113. }
  114. // 构造基础查询
  115. baseQuery := DB.Model(&Channel{}).Omit(keyCol)
  116. // 构造WHERE子句
  117. var whereClause string
  118. var args []interface{}
  119. if group != "" && group != "null" {
  120. var groupCondition string
  121. if common.UsingMySQL {
  122. groupCondition = `CONCAT(',', ` + groupCol + `, ',') LIKE ?`
  123. } else {
  124. // sqlite, PostgreSQL
  125. groupCondition = `(',' || ` + groupCol + ` || ',') LIKE ?`
  126. }
  127. whereClause = "(id = ? OR name LIKE ? OR " + keyCol + " = ?) AND " + modelsCol + ` LIKE ? AND ` + groupCondition
  128. args = append(args, common.String2Int(keyword), "%"+keyword+"%", keyword, "%"+model+"%", "%,"+group+",%")
  129. } else {
  130. whereClause = "(id = ? OR name LIKE ? OR " + keyCol + " = ?) AND " + modelsCol + " LIKE ?"
  131. args = append(args, common.String2Int(keyword), "%"+keyword+"%", keyword, "%"+model+"%")
  132. }
  133. // 执行查询
  134. err := baseQuery.Where(whereClause, args...).Order(order).Find(&channels).Error
  135. if err != nil {
  136. return nil, err
  137. }
  138. return channels, nil
  139. }
  140. func GetChannelById(id int, selectAll bool) (*Channel, error) {
  141. channel := Channel{Id: id}
  142. var err error = nil
  143. if selectAll {
  144. err = DB.First(&channel, "id = ?", id).Error
  145. } else {
  146. err = DB.Omit("key").First(&channel, "id = ?", id).Error
  147. }
  148. return &channel, err
  149. }
  150. func BatchInsertChannels(channels []Channel) error {
  151. var err error
  152. err = DB.Create(&channels).Error
  153. if err != nil {
  154. return err
  155. }
  156. for _, channel_ := range channels {
  157. err = channel_.AddAbilities()
  158. if err != nil {
  159. return err
  160. }
  161. }
  162. return nil
  163. }
  164. func BatchDeleteChannels(ids []int) error {
  165. //使用事务 删除channel表和channel_ability表
  166. tx := DB.Begin()
  167. err := tx.Where("id in (?)", ids).Delete(&Channel{}).Error
  168. if err != nil {
  169. // 回滚事务
  170. tx.Rollback()
  171. return err
  172. }
  173. err = tx.Where("channel_id in (?)", ids).Delete(&Ability{}).Error
  174. if err != nil {
  175. // 回滚事务
  176. tx.Rollback()
  177. return err
  178. }
  179. // 提交事务
  180. tx.Commit()
  181. return err
  182. }
  183. func (channel *Channel) GetPriority() int64 {
  184. if channel.Priority == nil {
  185. return 0
  186. }
  187. return *channel.Priority
  188. }
  189. func (channel *Channel) GetWeight() int {
  190. if channel.Weight == nil {
  191. return 0
  192. }
  193. return int(*channel.Weight)
  194. }
  195. func (channel *Channel) GetBaseURL() string {
  196. if channel.BaseURL == nil {
  197. return ""
  198. }
  199. return *channel.BaseURL
  200. }
  201. func (channel *Channel) GetModelMapping() string {
  202. if channel.ModelMapping == nil {
  203. return ""
  204. }
  205. return *channel.ModelMapping
  206. }
  207. func (channel *Channel) GetStatusCodeMapping() string {
  208. if channel.StatusCodeMapping == nil {
  209. return ""
  210. }
  211. return *channel.StatusCodeMapping
  212. }
  213. func (channel *Channel) Insert() error {
  214. var err error
  215. err = DB.Create(channel).Error
  216. if err != nil {
  217. return err
  218. }
  219. err = channel.AddAbilities()
  220. return err
  221. }
  222. func (channel *Channel) Update() error {
  223. var err error
  224. err = DB.Model(channel).Updates(channel).Error
  225. if err != nil {
  226. return err
  227. }
  228. DB.Model(channel).First(channel, "id = ?", channel.Id)
  229. err = channel.UpdateAbilities(nil)
  230. return err
  231. }
  232. func (channel *Channel) UpdateResponseTime(responseTime int64) {
  233. err := DB.Model(channel).Select("response_time", "test_time").Updates(Channel{
  234. TestTime: common.GetTimestamp(),
  235. ResponseTime: int(responseTime),
  236. }).Error
  237. if err != nil {
  238. common.SysError("failed to update response time: " + err.Error())
  239. }
  240. }
  241. func (channel *Channel) UpdateBalance(balance float64) {
  242. err := DB.Model(channel).Select("balance_updated_time", "balance").Updates(Channel{
  243. BalanceUpdatedTime: common.GetTimestamp(),
  244. Balance: balance,
  245. }).Error
  246. if err != nil {
  247. common.SysError("failed to update balance: " + err.Error())
  248. }
  249. }
  250. func (channel *Channel) Delete() error {
  251. var err error
  252. err = DB.Delete(channel).Error
  253. if err != nil {
  254. return err
  255. }
  256. err = channel.DeleteAbilities()
  257. return err
  258. }
  259. var channelStatusLock sync.Mutex
  260. func UpdateChannelStatusById(id int, status int, reason string) bool {
  261. if common.MemoryCacheEnabled {
  262. channelStatusLock.Lock()
  263. defer channelStatusLock.Unlock()
  264. channelCache, _ := CacheGetChannel(id)
  265. // 如果缓存渠道存在,且状态已是目标状态,直接返回
  266. if channelCache != nil && channelCache.Status == status {
  267. return false
  268. }
  269. // 如果缓存渠道不存在(说明已经被禁用),且要设置的状态不为启用,直接返回
  270. if channelCache == nil && status != common.ChannelStatusEnabled {
  271. return false
  272. }
  273. CacheUpdateChannelStatus(id, status)
  274. }
  275. err := UpdateAbilityStatus(id, status == common.ChannelStatusEnabled)
  276. if err != nil {
  277. common.SysError("failed to update ability status: " + err.Error())
  278. return false
  279. }
  280. channel, err := GetChannelById(id, true)
  281. if err != nil {
  282. // find channel by id error, directly update status
  283. result := DB.Model(&Channel{}).Where("id = ?", id).Update("status", status)
  284. if result.Error != nil {
  285. common.SysError("failed to update channel status: " + result.Error.Error())
  286. return false
  287. }
  288. if result.RowsAffected == 0 {
  289. return false
  290. }
  291. } else {
  292. if channel.Status == status {
  293. return false
  294. }
  295. // find channel by id success, update status and other info
  296. info := channel.GetOtherInfo()
  297. info["status_reason"] = reason
  298. info["status_time"] = common.GetTimestamp()
  299. channel.SetOtherInfo(info)
  300. channel.Status = status
  301. err = channel.Save()
  302. if err != nil {
  303. common.SysError("failed to update channel status: " + err.Error())
  304. return false
  305. }
  306. }
  307. return true
  308. }
  309. func EnableChannelByTag(tag string) error {
  310. err := DB.Model(&Channel{}).Where("tag = ?", tag).Update("status", common.ChannelStatusEnabled).Error
  311. if err != nil {
  312. return err
  313. }
  314. err = UpdateAbilityStatusByTag(tag, true)
  315. return err
  316. }
  317. func DisableChannelByTag(tag string) error {
  318. err := DB.Model(&Channel{}).Where("tag = ?", tag).Update("status", common.ChannelStatusManuallyDisabled).Error
  319. if err != nil {
  320. return err
  321. }
  322. err = UpdateAbilityStatusByTag(tag, false)
  323. return err
  324. }
  325. func EditChannelByTag(tag string, newTag *string, modelMapping *string, models *string, group *string, priority *int64, weight *uint) error {
  326. updateData := Channel{}
  327. shouldReCreateAbilities := false
  328. updatedTag := tag
  329. // 如果 newTag 不为空且不等于 tag,则更新 tag
  330. if newTag != nil && *newTag != tag {
  331. updateData.Tag = newTag
  332. updatedTag = *newTag
  333. }
  334. if modelMapping != nil && *modelMapping != "" {
  335. updateData.ModelMapping = modelMapping
  336. }
  337. if models != nil && *models != "" {
  338. shouldReCreateAbilities = true
  339. updateData.Models = *models
  340. }
  341. if group != nil && *group != "" {
  342. shouldReCreateAbilities = true
  343. updateData.Group = *group
  344. }
  345. if priority != nil {
  346. updateData.Priority = priority
  347. }
  348. if weight != nil {
  349. updateData.Weight = weight
  350. }
  351. err := DB.Model(&Channel{}).Where("tag = ?", tag).Updates(updateData).Error
  352. if err != nil {
  353. return err
  354. }
  355. if shouldReCreateAbilities {
  356. channels, err := GetChannelsByTag(updatedTag, false)
  357. if err == nil {
  358. for _, channel := range channels {
  359. err = channel.UpdateAbilities(nil)
  360. if err != nil {
  361. common.SysError("failed to update abilities: " + err.Error())
  362. }
  363. }
  364. }
  365. } else {
  366. err := UpdateAbilityByTag(tag, newTag, priority, weight)
  367. if err != nil {
  368. return err
  369. }
  370. }
  371. return nil
  372. }
  373. func UpdateChannelUsedQuota(id int, quota int) {
  374. if common.BatchUpdateEnabled {
  375. addNewRecord(BatchUpdateTypeChannelUsedQuota, id, quota)
  376. return
  377. }
  378. updateChannelUsedQuota(id, quota)
  379. }
  380. func updateChannelUsedQuota(id int, quota int) {
  381. err := DB.Model(&Channel{}).Where("id = ?", id).Update("used_quota", gorm.Expr("used_quota + ?", quota)).Error
  382. if err != nil {
  383. common.SysError("failed to update channel used quota: " + err.Error())
  384. }
  385. }
  386. func DeleteChannelByStatus(status int64) (int64, error) {
  387. result := DB.Where("status = ?", status).Delete(&Channel{})
  388. return result.RowsAffected, result.Error
  389. }
  390. func DeleteDisabledChannel() (int64, error) {
  391. result := DB.Where("status = ? or status = ?", common.ChannelStatusAutoDisabled, common.ChannelStatusManuallyDisabled).Delete(&Channel{})
  392. return result.RowsAffected, result.Error
  393. }
  394. func GetPaginatedTags(offset int, limit int) ([]*string, error) {
  395. var tags []*string
  396. err := DB.Model(&Channel{}).Select("DISTINCT tag").Where("tag != ''").Offset(offset).Limit(limit).Find(&tags).Error
  397. return tags, err
  398. }
  399. func SearchTags(keyword string, group string, model string, idSort bool) ([]*string, error) {
  400. var tags []*string
  401. modelsCol := "`models`"
  402. // 如果是 PostgreSQL,使用双引号
  403. if common.UsingPostgreSQL {
  404. modelsCol = `"models"`
  405. }
  406. order := "priority desc"
  407. if idSort {
  408. order = "id desc"
  409. }
  410. // 构造基础查询
  411. baseQuery := DB.Model(&Channel{}).Omit(keyCol)
  412. // 构造WHERE子句
  413. var whereClause string
  414. var args []interface{}
  415. if group != "" && group != "null" {
  416. var groupCondition string
  417. if common.UsingMySQL {
  418. groupCondition = `CONCAT(',', ` + groupCol + `, ',') LIKE ?`
  419. } else {
  420. // sqlite, PostgreSQL
  421. groupCondition = `(',' || ` + groupCol + ` || ',') LIKE ?`
  422. }
  423. whereClause = "(id = ? OR name LIKE ? OR " + keyCol + " = ?) AND " + modelsCol + ` LIKE ? AND ` + groupCondition
  424. args = append(args, common.String2Int(keyword), "%"+keyword+"%", keyword, "%"+model+"%", "%,"+group+",%")
  425. } else {
  426. whereClause = "(id = ? OR name LIKE ? OR " + keyCol + " = ?) AND " + modelsCol + " LIKE ?"
  427. args = append(args, common.String2Int(keyword), "%"+keyword+"%", keyword, "%"+model+"%")
  428. }
  429. subQuery := baseQuery.Where(whereClause, args...).
  430. Select("tag").
  431. Where("tag != ''").
  432. Order(order)
  433. err := DB.Table("(?) as sub", subQuery).
  434. Select("DISTINCT tag").
  435. Find(&tags).Error
  436. if err != nil {
  437. return nil, err
  438. }
  439. return tags, nil
  440. }
  441. func (channel *Channel) GetSetting() map[string]interface{} {
  442. setting := make(map[string]interface{})
  443. if channel.Setting != nil && *channel.Setting != "" {
  444. err := json.Unmarshal([]byte(*channel.Setting), &setting)
  445. if err != nil {
  446. common.SysError("failed to unmarshal setting: " + err.Error())
  447. }
  448. }
  449. return setting
  450. }
  451. func (channel *Channel) SetSetting(setting map[string]interface{}) {
  452. settingBytes, err := json.Marshal(setting)
  453. if err != nil {
  454. common.SysError("failed to marshal setting: " + err.Error())
  455. return
  456. }
  457. channel.Setting = common.GetPointer[string](string(settingBytes))
  458. }
  459. func GetChannelsByIds(ids []int) ([]*Channel, error) {
  460. var channels []*Channel
  461. err := DB.Where("id in (?)", ids).Find(&channels).Error
  462. return channels, err
  463. }
  464. func BatchSetChannelTag(ids []int, tag *string) error {
  465. // 开启事务
  466. tx := DB.Begin()
  467. if tx.Error != nil {
  468. return tx.Error
  469. }
  470. // 更新标签
  471. err := tx.Model(&Channel{}).Where("id in (?)", ids).Update("tag", tag).Error
  472. if err != nil {
  473. tx.Rollback()
  474. return err
  475. }
  476. // update ability status
  477. channels, err := GetChannelsByIds(ids)
  478. if err != nil {
  479. tx.Rollback()
  480. return err
  481. }
  482. for _, channel := range channels {
  483. err = channel.UpdateAbilities(tx)
  484. if err != nil {
  485. tx.Rollback()
  486. return err
  487. }
  488. }
  489. // 提交事务
  490. return tx.Commit().Error
  491. }