channel.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005
  1. package model
  2. import (
  3. "database/sql/driver"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "math/rand"
  8. "strings"
  9. "sync"
  10. "github.com/QuantumNous/new-api/common"
  11. "github.com/QuantumNous/new-api/constant"
  12. "github.com/QuantumNous/new-api/dto"
  13. "github.com/QuantumNous/new-api/types"
  14. "github.com/samber/lo"
  15. "gorm.io/gorm"
  16. )
  17. type Channel struct {
  18. Id int `json:"id"`
  19. Type int `json:"type" gorm:"default:0"`
  20. Key string `json:"key" gorm:"not null"`
  21. OpenAIOrganization *string `json:"openai_organization"`
  22. TestModel *string `json:"test_model"`
  23. Status int `json:"status" gorm:"default:1"`
  24. Name string `json:"name" gorm:"index"`
  25. Weight *uint `json:"weight" gorm:"default:0"`
  26. CreatedTime int64 `json:"created_time" gorm:"bigint"`
  27. TestTime int64 `json:"test_time" gorm:"bigint"`
  28. ResponseTime int `json:"response_time"` // in milliseconds
  29. BaseURL *string `json:"base_url" gorm:"column:base_url;default:''"`
  30. Other string `json:"other"`
  31. Balance float64 `json:"balance"` // in USD
  32. BalanceUpdatedTime int64 `json:"balance_updated_time" gorm:"bigint"`
  33. Models string `json:"models"`
  34. Group string `json:"group" gorm:"type:varchar(64);default:'default'"`
  35. UsedQuota int64 `json:"used_quota" gorm:"bigint;default:0"`
  36. ModelMapping *string `json:"model_mapping" gorm:"type:text"`
  37. //MaxInputTokens *int `json:"max_input_tokens" gorm:"default:0"`
  38. StatusCodeMapping *string `json:"status_code_mapping" gorm:"type:varchar(1024);default:''"`
  39. Priority *int64 `json:"priority" gorm:"bigint;default:0"`
  40. AutoBan *int `json:"auto_ban" gorm:"default:1"`
  41. OtherInfo string `json:"other_info"`
  42. Tag *string `json:"tag" gorm:"index"`
  43. Setting *string `json:"setting" gorm:"type:text"` // 渠道额外设置
  44. ParamOverride *string `json:"param_override" gorm:"type:text"`
  45. HeaderOverride *string `json:"header_override" gorm:"type:text"`
  46. Remark *string `json:"remark" gorm:"type:varchar(255)" validate:"max=255"`
  47. // add after v0.8.5
  48. ChannelInfo ChannelInfo `json:"channel_info" gorm:"type:json"`
  49. OtherSettings string `json:"settings" gorm:"column:settings"` // 其他设置,存储azure版本等不需要检索的信息,详见dto.ChannelOtherSettings
  50. // cache info
  51. Keys []string `json:"-" gorm:"-"`
  52. }
  53. type ChannelInfo struct {
  54. IsMultiKey bool `json:"is_multi_key"` // 是否多Key模式
  55. MultiKeySize int `json:"multi_key_size"` // 多Key模式下的Key数量
  56. MultiKeyStatusList map[int]int `json:"multi_key_status_list"` // key状态列表,key index -> status
  57. MultiKeyDisabledReason map[int]string `json:"multi_key_disabled_reason,omitempty"` // key禁用原因列表,key index -> reason
  58. MultiKeyDisabledTime map[int]int64 `json:"multi_key_disabled_time,omitempty"` // key禁用时间列表,key index -> time
  59. MultiKeyPollingIndex int `json:"multi_key_polling_index"` // 多Key模式下轮询的key索引
  60. MultiKeyMode constant.MultiKeyMode `json:"multi_key_mode"`
  61. }
  62. // Value implements driver.Valuer interface
  63. func (c ChannelInfo) Value() (driver.Value, error) {
  64. return common.Marshal(&c)
  65. }
  66. // Scan implements sql.Scanner interface
  67. func (c *ChannelInfo) Scan(value interface{}) error {
  68. bytesValue, _ := value.([]byte)
  69. return common.Unmarshal(bytesValue, c)
  70. }
  71. func (channel *Channel) GetKeys() []string {
  72. if channel.Key == "" {
  73. return []string{}
  74. }
  75. if len(channel.Keys) > 0 {
  76. return channel.Keys
  77. }
  78. trimmed := strings.TrimSpace(channel.Key)
  79. // If the key starts with '[', try to parse it as a JSON array (e.g., for Vertex AI scenarios)
  80. if strings.HasPrefix(trimmed, "[") {
  81. var arr []json.RawMessage
  82. if err := common.Unmarshal([]byte(trimmed), &arr); err == nil {
  83. res := make([]string, len(arr))
  84. for i, v := range arr {
  85. res[i] = string(v)
  86. }
  87. return res
  88. }
  89. }
  90. // Otherwise, fall back to splitting by newline
  91. keys := strings.Split(strings.Trim(channel.Key, "\n"), "\n")
  92. return keys
  93. }
  94. func (channel *Channel) GetNextEnabledKey() (string, int, *types.NewAPIError) {
  95. // If not in multi-key mode, return the original key string directly.
  96. if !channel.ChannelInfo.IsMultiKey {
  97. return channel.Key, 0, nil
  98. }
  99. // Obtain all keys (split by \n)
  100. keys := channel.GetKeys()
  101. if len(keys) == 0 {
  102. // No keys available, return error, should disable the channel
  103. return "", 0, types.NewError(errors.New("no keys available"), types.ErrorCodeChannelNoAvailableKey)
  104. }
  105. lock := GetChannelPollingLock(channel.Id)
  106. lock.Lock()
  107. defer lock.Unlock()
  108. statusList := channel.ChannelInfo.MultiKeyStatusList
  109. // helper to get key status, default to enabled when missing
  110. getStatus := func(idx int) int {
  111. if statusList == nil {
  112. return common.ChannelStatusEnabled
  113. }
  114. if status, ok := statusList[idx]; ok {
  115. return status
  116. }
  117. return common.ChannelStatusEnabled
  118. }
  119. // Collect indexes of enabled keys
  120. enabledIdx := make([]int, 0, len(keys))
  121. for i := range keys {
  122. if getStatus(i) == common.ChannelStatusEnabled {
  123. enabledIdx = append(enabledIdx, i)
  124. }
  125. }
  126. // If no specific status list or none enabled, return an explicit error so caller can
  127. // properly handle a channel with no available keys (e.g. mark channel disabled).
  128. // Returning the first key here caused requests to keep using an already-disabled key.
  129. if len(enabledIdx) == 0 {
  130. return "", 0, types.NewError(errors.New("no enabled keys"), types.ErrorCodeChannelNoAvailableKey)
  131. }
  132. switch channel.ChannelInfo.MultiKeyMode {
  133. case constant.MultiKeyModeRandom:
  134. // Randomly pick one enabled key
  135. selectedIdx := enabledIdx[rand.Intn(len(enabledIdx))]
  136. return keys[selectedIdx], selectedIdx, nil
  137. case constant.MultiKeyModePolling:
  138. // Use channel-specific lock to ensure thread-safe polling
  139. channelInfo, err := CacheGetChannelInfo(channel.Id)
  140. if err != nil {
  141. return "", 0, types.NewError(err, types.ErrorCodeGetChannelFailed, types.ErrOptionWithSkipRetry())
  142. }
  143. //println("before polling index:", channel.ChannelInfo.MultiKeyPollingIndex)
  144. defer func() {
  145. if common.DebugEnabled {
  146. println(fmt.Sprintf("channel %d polling index: %d", channel.Id, channel.ChannelInfo.MultiKeyPollingIndex))
  147. }
  148. if !common.MemoryCacheEnabled {
  149. _ = channel.SaveChannelInfo()
  150. } else {
  151. // CacheUpdateChannel(channel)
  152. }
  153. }()
  154. // Start from the saved polling index and look for the next enabled key
  155. start := channelInfo.MultiKeyPollingIndex
  156. if start < 0 || start >= len(keys) {
  157. start = 0
  158. }
  159. for i := 0; i < len(keys); i++ {
  160. idx := (start + i) % len(keys)
  161. if getStatus(idx) == common.ChannelStatusEnabled {
  162. // update polling index for next call (point to the next position)
  163. channel.ChannelInfo.MultiKeyPollingIndex = (idx + 1) % len(keys)
  164. return keys[idx], idx, nil
  165. }
  166. }
  167. // Fallback – should not happen, but return first enabled key
  168. return keys[enabledIdx[0]], enabledIdx[0], nil
  169. default:
  170. // Unknown mode, default to first enabled key (or original key string)
  171. return keys[enabledIdx[0]], enabledIdx[0], nil
  172. }
  173. }
  174. func (channel *Channel) SaveChannelInfo() error {
  175. return DB.Model(channel).Update("channel_info", channel.ChannelInfo).Error
  176. }
  177. func (channel *Channel) GetModels() []string {
  178. if channel.Models == "" {
  179. return []string{}
  180. }
  181. return strings.Split(strings.Trim(channel.Models, ","), ",")
  182. }
  183. func (channel *Channel) GetGroups() []string {
  184. if channel.Group == "" {
  185. return []string{}
  186. }
  187. groups := strings.Split(strings.Trim(channel.Group, ","), ",")
  188. for i, group := range groups {
  189. groups[i] = strings.TrimSpace(group)
  190. }
  191. return groups
  192. }
  193. func (channel *Channel) GetOtherInfo() map[string]interface{} {
  194. otherInfo := make(map[string]interface{})
  195. if channel.OtherInfo != "" {
  196. err := common.Unmarshal([]byte(channel.OtherInfo), &otherInfo)
  197. if err != nil {
  198. common.SysLog(fmt.Sprintf("failed to unmarshal other info: channel_id=%d, tag=%s, name=%s, error=%v", channel.Id, channel.GetTag(), channel.Name, err))
  199. }
  200. }
  201. return otherInfo
  202. }
  203. func (channel *Channel) SetOtherInfo(otherInfo map[string]interface{}) {
  204. otherInfoBytes, err := json.Marshal(otherInfo)
  205. if err != nil {
  206. common.SysLog(fmt.Sprintf("failed to marshal other info: channel_id=%d, tag=%s, name=%s, error=%v", channel.Id, channel.GetTag(), channel.Name, err))
  207. return
  208. }
  209. channel.OtherInfo = string(otherInfoBytes)
  210. }
  211. func (channel *Channel) GetTag() string {
  212. if channel.Tag == nil {
  213. return ""
  214. }
  215. return *channel.Tag
  216. }
  217. func (channel *Channel) SetTag(tag string) {
  218. channel.Tag = &tag
  219. }
  220. func (channel *Channel) GetAutoBan() bool {
  221. if channel.AutoBan == nil {
  222. return false
  223. }
  224. return *channel.AutoBan == 1
  225. }
  226. func (channel *Channel) Save() error {
  227. return DB.Save(channel).Error
  228. }
  229. func (channel *Channel) SaveWithoutKey() error {
  230. return DB.Omit("key").Save(channel).Error
  231. }
  232. func GetAllChannels(startIdx int, num int, selectAll bool, idSort bool) ([]*Channel, error) {
  233. var channels []*Channel
  234. var err error
  235. order := "priority desc"
  236. if idSort {
  237. order = "id desc"
  238. }
  239. if selectAll {
  240. err = DB.Order(order).Find(&channels).Error
  241. } else {
  242. err = DB.Order(order).Limit(num).Offset(startIdx).Omit("key").Find(&channels).Error
  243. }
  244. return channels, err
  245. }
  246. func GetChannelsByTag(tag string, idSort bool, selectAll bool) ([]*Channel, error) {
  247. var channels []*Channel
  248. order := "priority desc"
  249. if idSort {
  250. order = "id desc"
  251. }
  252. query := DB.Where("tag = ?", tag).Order(order)
  253. if !selectAll {
  254. query = query.Omit("key")
  255. }
  256. err := query.Find(&channels).Error
  257. return channels, err
  258. }
  259. func SearchChannels(keyword string, group string, model string, idSort bool) ([]*Channel, error) {
  260. var channels []*Channel
  261. modelsCol := "`models`"
  262. // 如果是 PostgreSQL,使用双引号
  263. if common.UsingPostgreSQL {
  264. modelsCol = `"models"`
  265. }
  266. baseURLCol := "`base_url`"
  267. // 如果是 PostgreSQL,使用双引号
  268. if common.UsingPostgreSQL {
  269. baseURLCol = `"base_url"`
  270. }
  271. order := "priority desc"
  272. if idSort {
  273. order = "id desc"
  274. }
  275. // 构造基础查询
  276. baseQuery := DB.Model(&Channel{}).Omit("key")
  277. // 构造WHERE子句
  278. var whereClause string
  279. var args []interface{}
  280. if group != "" && group != "null" {
  281. var groupCondition string
  282. if common.UsingMySQL {
  283. groupCondition = `CONCAT(',', ` + commonGroupCol + `, ',') LIKE ?`
  284. } else {
  285. // sqlite, PostgreSQL
  286. groupCondition = `(',' || ` + commonGroupCol + ` || ',') LIKE ?`
  287. }
  288. whereClause = "(id = ? OR name LIKE ? OR " + commonKeyCol + " = ? OR " + baseURLCol + " LIKE ?) AND " + modelsCol + ` LIKE ? AND ` + groupCondition
  289. args = append(args, common.String2Int(keyword), "%"+keyword+"%", keyword, "%"+keyword+"%", "%"+model+"%", "%,"+group+",%")
  290. } else {
  291. whereClause = "(id = ? OR name LIKE ? OR " + commonKeyCol + " = ? OR " + baseURLCol + " LIKE ?) AND " + modelsCol + " LIKE ?"
  292. args = append(args, common.String2Int(keyword), "%"+keyword+"%", keyword, "%"+keyword+"%", "%"+model+"%")
  293. }
  294. // 执行查询
  295. err := baseQuery.Where(whereClause, args...).Order(order).Find(&channels).Error
  296. if err != nil {
  297. return nil, err
  298. }
  299. return channels, nil
  300. }
  301. func GetChannelById(id int, selectAll bool) (*Channel, error) {
  302. channel := &Channel{Id: id}
  303. var err error = nil
  304. if selectAll {
  305. err = DB.First(channel, "id = ?", id).Error
  306. } else {
  307. err = DB.Omit("key").First(channel, "id = ?", id).Error
  308. }
  309. if err != nil {
  310. return nil, err
  311. }
  312. if channel == nil {
  313. return nil, errors.New("channel not found")
  314. }
  315. return channel, nil
  316. }
  317. func BatchInsertChannels(channels []Channel) error {
  318. if len(channels) == 0 {
  319. return nil
  320. }
  321. tx := DB.Begin()
  322. if tx.Error != nil {
  323. return tx.Error
  324. }
  325. defer func() {
  326. if r := recover(); r != nil {
  327. tx.Rollback()
  328. }
  329. }()
  330. for _, chunk := range lo.Chunk(channels, 50) {
  331. if err := tx.Create(&chunk).Error; err != nil {
  332. tx.Rollback()
  333. return err
  334. }
  335. for _, channel_ := range chunk {
  336. if err := channel_.AddAbilities(tx); err != nil {
  337. tx.Rollback()
  338. return err
  339. }
  340. }
  341. }
  342. return tx.Commit().Error
  343. }
  344. func BatchDeleteChannels(ids []int) error {
  345. if len(ids) == 0 {
  346. return nil
  347. }
  348. // 使用事务 分批删除channel表和abilities表
  349. tx := DB.Begin()
  350. if tx.Error != nil {
  351. return tx.Error
  352. }
  353. for _, chunk := range lo.Chunk(ids, 200) {
  354. if err := tx.Where("id in (?)", chunk).Delete(&Channel{}).Error; err != nil {
  355. tx.Rollback()
  356. return err
  357. }
  358. if err := tx.Where("channel_id in (?)", chunk).Delete(&Ability{}).Error; err != nil {
  359. tx.Rollback()
  360. return err
  361. }
  362. }
  363. return tx.Commit().Error
  364. }
  365. func (channel *Channel) GetPriority() int64 {
  366. if channel.Priority == nil {
  367. return 0
  368. }
  369. return *channel.Priority
  370. }
  371. func (channel *Channel) GetWeight() int {
  372. if channel.Weight == nil {
  373. return 0
  374. }
  375. return int(*channel.Weight)
  376. }
  377. func (channel *Channel) GetBaseURL() string {
  378. if channel.BaseURL == nil {
  379. return ""
  380. }
  381. url := *channel.BaseURL
  382. if url == "" {
  383. url = constant.ChannelBaseURLs[channel.Type]
  384. }
  385. return url
  386. }
  387. func (channel *Channel) GetModelMapping() string {
  388. if channel.ModelMapping == nil {
  389. return ""
  390. }
  391. return *channel.ModelMapping
  392. }
  393. func (channel *Channel) GetStatusCodeMapping() string {
  394. if channel.StatusCodeMapping == nil {
  395. return ""
  396. }
  397. return *channel.StatusCodeMapping
  398. }
  399. func (channel *Channel) Insert() error {
  400. var err error
  401. err = DB.Create(channel).Error
  402. if err != nil {
  403. return err
  404. }
  405. err = channel.AddAbilities(nil)
  406. return err
  407. }
  408. func (channel *Channel) Update() error {
  409. // If this is a multi-key channel, recalculate MultiKeySize based on the current key list to avoid inconsistency after editing keys
  410. if channel.ChannelInfo.IsMultiKey {
  411. var keyStr string
  412. if channel.Key != "" {
  413. keyStr = channel.Key
  414. } else {
  415. // If key is not provided, read the existing key from the database
  416. if existing, err := GetChannelById(channel.Id, true); err == nil {
  417. keyStr = existing.Key
  418. }
  419. }
  420. // Parse the key list (supports newline separation or JSON array)
  421. keys := []string{}
  422. if keyStr != "" {
  423. trimmed := strings.TrimSpace(keyStr)
  424. if strings.HasPrefix(trimmed, "[") {
  425. var arr []json.RawMessage
  426. if err := common.Unmarshal([]byte(trimmed), &arr); err == nil {
  427. keys = make([]string, len(arr))
  428. for i, v := range arr {
  429. keys[i] = string(v)
  430. }
  431. }
  432. }
  433. if len(keys) == 0 { // fallback to newline split
  434. keys = strings.Split(strings.Trim(keyStr, "\n"), "\n")
  435. }
  436. }
  437. channel.ChannelInfo.MultiKeySize = len(keys)
  438. // Clean up status data that exceeds the new key count to prevent index out of range
  439. if channel.ChannelInfo.MultiKeyStatusList != nil {
  440. for idx := range channel.ChannelInfo.MultiKeyStatusList {
  441. if idx >= channel.ChannelInfo.MultiKeySize {
  442. delete(channel.ChannelInfo.MultiKeyStatusList, idx)
  443. }
  444. }
  445. }
  446. }
  447. var err error
  448. err = DB.Model(channel).Updates(channel).Error
  449. if err != nil {
  450. return err
  451. }
  452. DB.Model(channel).First(channel, "id = ?", channel.Id)
  453. err = channel.UpdateAbilities(nil)
  454. return err
  455. }
  456. func (channel *Channel) UpdateResponseTime(responseTime int64) {
  457. err := DB.Model(channel).Select("response_time", "test_time").Updates(Channel{
  458. TestTime: common.GetTimestamp(),
  459. ResponseTime: int(responseTime),
  460. }).Error
  461. if err != nil {
  462. common.SysLog(fmt.Sprintf("failed to update response time: channel_id=%d, error=%v", channel.Id, err))
  463. }
  464. }
  465. func (channel *Channel) UpdateBalance(balance float64) {
  466. err := DB.Model(channel).Select("balance_updated_time", "balance").Updates(Channel{
  467. BalanceUpdatedTime: common.GetTimestamp(),
  468. Balance: balance,
  469. }).Error
  470. if err != nil {
  471. common.SysLog(fmt.Sprintf("failed to update balance: channel_id=%d, error=%v", channel.Id, err))
  472. }
  473. }
  474. func (channel *Channel) Delete() error {
  475. var err error
  476. err = DB.Delete(channel).Error
  477. if err != nil {
  478. return err
  479. }
  480. err = channel.DeleteAbilities()
  481. return err
  482. }
  483. var channelStatusLock sync.Mutex
  484. // channelPollingLocks stores locks for each channel.id to ensure thread-safe polling
  485. var channelPollingLocks sync.Map
  486. // GetChannelPollingLock returns or creates a mutex for the given channel ID
  487. func GetChannelPollingLock(channelId int) *sync.Mutex {
  488. if lock, exists := channelPollingLocks.Load(channelId); exists {
  489. return lock.(*sync.Mutex)
  490. }
  491. // Create new lock for this channel
  492. newLock := &sync.Mutex{}
  493. actual, _ := channelPollingLocks.LoadOrStore(channelId, newLock)
  494. return actual.(*sync.Mutex)
  495. }
  496. // CleanupChannelPollingLocks removes locks for channels that no longer exist
  497. // This is optional and can be called periodically to prevent memory leaks
  498. func CleanupChannelPollingLocks() {
  499. var activeChannelIds []int
  500. DB.Model(&Channel{}).Pluck("id", &activeChannelIds)
  501. activeChannelSet := make(map[int]bool)
  502. for _, id := range activeChannelIds {
  503. activeChannelSet[id] = true
  504. }
  505. channelPollingLocks.Range(func(key, value interface{}) bool {
  506. channelId := key.(int)
  507. if !activeChannelSet[channelId] {
  508. channelPollingLocks.Delete(channelId)
  509. }
  510. return true
  511. })
  512. }
  513. func handlerMultiKeyUpdate(channel *Channel, usingKey string, status int, reason string) {
  514. keys := channel.GetKeys()
  515. if len(keys) == 0 {
  516. channel.Status = status
  517. } else {
  518. var keyIndex int
  519. for i, key := range keys {
  520. if key == usingKey {
  521. keyIndex = i
  522. break
  523. }
  524. }
  525. if channel.ChannelInfo.MultiKeyStatusList == nil {
  526. channel.ChannelInfo.MultiKeyStatusList = make(map[int]int)
  527. }
  528. if status == common.ChannelStatusEnabled {
  529. delete(channel.ChannelInfo.MultiKeyStatusList, keyIndex)
  530. } else {
  531. channel.ChannelInfo.MultiKeyStatusList[keyIndex] = status
  532. if channel.ChannelInfo.MultiKeyDisabledReason == nil {
  533. channel.ChannelInfo.MultiKeyDisabledReason = make(map[int]string)
  534. }
  535. if channel.ChannelInfo.MultiKeyDisabledTime == nil {
  536. channel.ChannelInfo.MultiKeyDisabledTime = make(map[int]int64)
  537. }
  538. channel.ChannelInfo.MultiKeyDisabledReason[keyIndex] = reason
  539. channel.ChannelInfo.MultiKeyDisabledTime[keyIndex] = common.GetTimestamp()
  540. }
  541. if len(channel.ChannelInfo.MultiKeyStatusList) >= channel.ChannelInfo.MultiKeySize {
  542. channel.Status = common.ChannelStatusAutoDisabled
  543. info := channel.GetOtherInfo()
  544. info["status_reason"] = "All keys are disabled"
  545. info["status_time"] = common.GetTimestamp()
  546. channel.SetOtherInfo(info)
  547. }
  548. }
  549. }
  550. func UpdateChannelStatus(channelId int, usingKey string, status int, reason string) bool {
  551. if common.MemoryCacheEnabled {
  552. channelStatusLock.Lock()
  553. defer channelStatusLock.Unlock()
  554. channelCache, _ := CacheGetChannel(channelId)
  555. if channelCache == nil {
  556. return false
  557. }
  558. if channelCache.ChannelInfo.IsMultiKey {
  559. // Use per-channel lock to prevent concurrent map read/write with GetNextEnabledKey
  560. pollingLock := GetChannelPollingLock(channelId)
  561. pollingLock.Lock()
  562. // 如果是多Key模式,更新缓存中的状态
  563. handlerMultiKeyUpdate(channelCache, usingKey, status, reason)
  564. pollingLock.Unlock()
  565. //CacheUpdateChannel(channelCache)
  566. //return true
  567. } else {
  568. // 如果缓存渠道存在,且状态已是目标状态,直接返回
  569. if channelCache.Status == status {
  570. return false
  571. }
  572. CacheUpdateChannelStatus(channelId, status)
  573. }
  574. }
  575. shouldUpdateAbilities := false
  576. defer func() {
  577. if shouldUpdateAbilities {
  578. err := UpdateAbilityStatus(channelId, status == common.ChannelStatusEnabled)
  579. if err != nil {
  580. common.SysLog(fmt.Sprintf("failed to update ability status: channel_id=%d, error=%v", channelId, err))
  581. }
  582. }
  583. }()
  584. channel, err := GetChannelById(channelId, true)
  585. if err != nil {
  586. return false
  587. } else {
  588. if channel.Status == status {
  589. return false
  590. }
  591. if channel.ChannelInfo.IsMultiKey {
  592. beforeStatus := channel.Status
  593. // Protect map writes with the same per-channel lock used by readers
  594. pollingLock := GetChannelPollingLock(channelId)
  595. pollingLock.Lock()
  596. handlerMultiKeyUpdate(channel, usingKey, status, reason)
  597. pollingLock.Unlock()
  598. if beforeStatus != channel.Status {
  599. shouldUpdateAbilities = true
  600. }
  601. } else {
  602. info := channel.GetOtherInfo()
  603. info["status_reason"] = reason
  604. info["status_time"] = common.GetTimestamp()
  605. channel.SetOtherInfo(info)
  606. channel.Status = status
  607. shouldUpdateAbilities = true
  608. }
  609. err = channel.SaveWithoutKey()
  610. if err != nil {
  611. common.SysLog(fmt.Sprintf("failed to update channel status: channel_id=%d, status=%d, error=%v", channel.Id, status, err))
  612. return false
  613. }
  614. }
  615. return true
  616. }
  617. func EnableChannelByTag(tag string) error {
  618. err := DB.Model(&Channel{}).Where("tag = ?", tag).Update("status", common.ChannelStatusEnabled).Error
  619. if err != nil {
  620. return err
  621. }
  622. err = UpdateAbilityStatusByTag(tag, true)
  623. return err
  624. }
  625. func DisableChannelByTag(tag string) error {
  626. err := DB.Model(&Channel{}).Where("tag = ?", tag).Update("status", common.ChannelStatusManuallyDisabled).Error
  627. if err != nil {
  628. return err
  629. }
  630. err = UpdateAbilityStatusByTag(tag, false)
  631. return err
  632. }
  633. func EditChannelByTag(tag string, newTag *string, modelMapping *string, models *string, group *string, priority *int64, weight *uint, paramOverride *string, headerOverride *string) error {
  634. updateData := Channel{}
  635. shouldReCreateAbilities := false
  636. updatedTag := tag
  637. // 如果 newTag 不为空且不等于 tag,则更新 tag
  638. if newTag != nil && *newTag != tag {
  639. updateData.Tag = newTag
  640. updatedTag = *newTag
  641. }
  642. if modelMapping != nil && *modelMapping != "" {
  643. updateData.ModelMapping = modelMapping
  644. }
  645. if models != nil && *models != "" {
  646. shouldReCreateAbilities = true
  647. updateData.Models = *models
  648. }
  649. if group != nil && *group != "" {
  650. shouldReCreateAbilities = true
  651. updateData.Group = *group
  652. }
  653. if priority != nil {
  654. updateData.Priority = priority
  655. }
  656. if weight != nil {
  657. updateData.Weight = weight
  658. }
  659. if paramOverride != nil {
  660. updateData.ParamOverride = paramOverride
  661. }
  662. if headerOverride != nil {
  663. updateData.HeaderOverride = headerOverride
  664. }
  665. err := DB.Model(&Channel{}).Where("tag = ?", tag).Updates(updateData).Error
  666. if err != nil {
  667. return err
  668. }
  669. if shouldReCreateAbilities {
  670. channels, err := GetChannelsByTag(updatedTag, false, false)
  671. if err == nil {
  672. for _, channel := range channels {
  673. err = channel.UpdateAbilities(nil)
  674. if err != nil {
  675. common.SysLog(fmt.Sprintf("failed to update abilities: channel_id=%d, tag=%s, error=%v", channel.Id, channel.GetTag(), err))
  676. }
  677. }
  678. }
  679. } else {
  680. err := UpdateAbilityByTag(tag, newTag, priority, weight)
  681. if err != nil {
  682. return err
  683. }
  684. }
  685. return nil
  686. }
  687. func UpdateChannelUsedQuota(id int, quota int) {
  688. if common.BatchUpdateEnabled {
  689. addNewRecord(BatchUpdateTypeChannelUsedQuota, id, quota)
  690. return
  691. }
  692. updateChannelUsedQuota(id, quota)
  693. }
  694. func updateChannelUsedQuota(id int, quota int) {
  695. err := DB.Model(&Channel{}).Where("id = ?", id).Update("used_quota", gorm.Expr("used_quota + ?", quota)).Error
  696. if err != nil {
  697. common.SysLog(fmt.Sprintf("failed to update channel used quota: channel_id=%d, delta_quota=%d, error=%v", id, quota, err))
  698. }
  699. }
  700. func DeleteChannelByStatus(status int64) (int64, error) {
  701. result := DB.Where("status = ?", status).Delete(&Channel{})
  702. return result.RowsAffected, result.Error
  703. }
  704. func DeleteDisabledChannel() (int64, error) {
  705. result := DB.Where("status = ? or status = ?", common.ChannelStatusAutoDisabled, common.ChannelStatusManuallyDisabled).Delete(&Channel{})
  706. return result.RowsAffected, result.Error
  707. }
  708. func GetPaginatedTags(offset int, limit int) ([]*string, error) {
  709. var tags []*string
  710. err := DB.Model(&Channel{}).Select("DISTINCT tag").Where("tag != ''").Offset(offset).Limit(limit).Find(&tags).Error
  711. return tags, err
  712. }
  713. func SearchTags(keyword string, group string, model string, idSort bool) ([]*string, error) {
  714. var tags []*string
  715. modelsCol := "`models`"
  716. // 如果是 PostgreSQL,使用双引号
  717. if common.UsingPostgreSQL {
  718. modelsCol = `"models"`
  719. }
  720. baseURLCol := "`base_url`"
  721. // 如果是 PostgreSQL,使用双引号
  722. if common.UsingPostgreSQL {
  723. baseURLCol = `"base_url"`
  724. }
  725. order := "priority desc"
  726. if idSort {
  727. order = "id desc"
  728. }
  729. // 构造基础查询
  730. baseQuery := DB.Model(&Channel{}).Omit("key")
  731. // 构造WHERE子句
  732. var whereClause string
  733. var args []interface{}
  734. if group != "" && group != "null" {
  735. var groupCondition string
  736. if common.UsingMySQL {
  737. groupCondition = `CONCAT(',', ` + commonGroupCol + `, ',') LIKE ?`
  738. } else {
  739. // sqlite, PostgreSQL
  740. groupCondition = `(',' || ` + commonGroupCol + ` || ',') LIKE ?`
  741. }
  742. whereClause = "(id = ? OR name LIKE ? OR " + commonKeyCol + " = ? OR " + baseURLCol + " LIKE ?) AND " + modelsCol + ` LIKE ? AND ` + groupCondition
  743. args = append(args, common.String2Int(keyword), "%"+keyword+"%", keyword, "%"+keyword+"%", "%"+model+"%", "%,"+group+",%")
  744. } else {
  745. whereClause = "(id = ? OR name LIKE ? OR " + commonKeyCol + " = ? OR " + baseURLCol + " LIKE ?) AND " + modelsCol + " LIKE ?"
  746. args = append(args, common.String2Int(keyword), "%"+keyword+"%", keyword, "%"+keyword+"%", "%"+model+"%")
  747. }
  748. subQuery := baseQuery.Where(whereClause, args...).
  749. Select("tag").
  750. Where("tag != ''").
  751. Order(order)
  752. err := DB.Table("(?) as sub", subQuery).
  753. Select("DISTINCT tag").
  754. Find(&tags).Error
  755. if err != nil {
  756. return nil, err
  757. }
  758. return tags, nil
  759. }
  760. func (channel *Channel) ValidateSettings() error {
  761. channelParams := &dto.ChannelSettings{}
  762. if channel.Setting != nil && *channel.Setting != "" {
  763. err := common.Unmarshal([]byte(*channel.Setting), channelParams)
  764. if err != nil {
  765. return err
  766. }
  767. }
  768. return nil
  769. }
  770. func (channel *Channel) GetSetting() dto.ChannelSettings {
  771. setting := dto.ChannelSettings{}
  772. if channel.Setting != nil && *channel.Setting != "" {
  773. err := common.Unmarshal([]byte(*channel.Setting), &setting)
  774. if err != nil {
  775. common.SysLog(fmt.Sprintf("failed to unmarshal setting: channel_id=%d, error=%v", channel.Id, err))
  776. channel.Setting = nil // 清空设置以避免后续错误
  777. _ = channel.Save() // 保存修改
  778. }
  779. }
  780. return setting
  781. }
  782. func (channel *Channel) SetSetting(setting dto.ChannelSettings) {
  783. settingBytes, err := common.Marshal(setting)
  784. if err != nil {
  785. common.SysLog(fmt.Sprintf("failed to marshal setting: channel_id=%d, error=%v", channel.Id, err))
  786. return
  787. }
  788. channel.Setting = common.GetPointer[string](string(settingBytes))
  789. }
  790. func (channel *Channel) GetOtherSettings() dto.ChannelOtherSettings {
  791. setting := dto.ChannelOtherSettings{}
  792. if channel.OtherSettings != "" {
  793. err := common.UnmarshalJsonStr(channel.OtherSettings, &setting)
  794. if err != nil {
  795. common.SysLog(fmt.Sprintf("failed to unmarshal setting: channel_id=%d, error=%v", channel.Id, err))
  796. channel.OtherSettings = "{}" // 清空设置以避免后续错误
  797. _ = channel.Save() // 保存修改
  798. }
  799. }
  800. return setting
  801. }
  802. func (channel *Channel) SetOtherSettings(setting dto.ChannelOtherSettings) {
  803. settingBytes, err := common.Marshal(setting)
  804. if err != nil {
  805. common.SysLog(fmt.Sprintf("failed to marshal setting: channel_id=%d, error=%v", channel.Id, err))
  806. return
  807. }
  808. channel.OtherSettings = string(settingBytes)
  809. }
  810. func (channel *Channel) GetParamOverride() map[string]interface{} {
  811. paramOverride := make(map[string]interface{})
  812. if channel.ParamOverride != nil && *channel.ParamOverride != "" {
  813. err := common.Unmarshal([]byte(*channel.ParamOverride), &paramOverride)
  814. if err != nil {
  815. common.SysLog(fmt.Sprintf("failed to unmarshal param override: channel_id=%d, error=%v", channel.Id, err))
  816. }
  817. }
  818. return paramOverride
  819. }
  820. func (channel *Channel) GetHeaderOverride() map[string]interface{} {
  821. headerOverride := make(map[string]interface{})
  822. if channel.HeaderOverride != nil && *channel.HeaderOverride != "" {
  823. err := common.Unmarshal([]byte(*channel.HeaderOverride), &headerOverride)
  824. if err != nil {
  825. common.SysLog(fmt.Sprintf("failed to unmarshal header override: channel_id=%d, error=%v", channel.Id, err))
  826. }
  827. }
  828. return headerOverride
  829. }
  830. func GetChannelsByIds(ids []int) ([]*Channel, error) {
  831. var channels []*Channel
  832. err := DB.Where("id in (?)", ids).Find(&channels).Error
  833. return channels, err
  834. }
  835. func BatchSetChannelTag(ids []int, tag *string) error {
  836. // 开启事务
  837. tx := DB.Begin()
  838. if tx.Error != nil {
  839. return tx.Error
  840. }
  841. // 更新标签
  842. err := tx.Model(&Channel{}).Where("id in (?)", ids).Update("tag", tag).Error
  843. if err != nil {
  844. tx.Rollback()
  845. return err
  846. }
  847. // update ability status
  848. channels, err := GetChannelsByIds(ids)
  849. if err != nil {
  850. tx.Rollback()
  851. return err
  852. }
  853. for _, channel := range channels {
  854. err = channel.UpdateAbilities(tx)
  855. if err != nil {
  856. tx.Rollback()
  857. return err
  858. }
  859. }
  860. // 提交事务
  861. return tx.Commit().Error
  862. }
  863. // CountAllChannels returns total channels in DB
  864. func CountAllChannels() (int64, error) {
  865. var total int64
  866. err := DB.Model(&Channel{}).Count(&total).Error
  867. return total, err
  868. }
  869. // CountAllTags returns number of non-empty distinct tags
  870. func CountAllTags() (int64, error) {
  871. var total int64
  872. err := DB.Model(&Channel{}).Where("tag is not null AND tag != ''").Distinct("tag").Count(&total).Error
  873. return total, err
  874. }
  875. // Get channels of specified type with pagination
  876. func GetChannelsByType(startIdx int, num int, idSort bool, channelType int) ([]*Channel, error) {
  877. var channels []*Channel
  878. order := "priority desc"
  879. if idSort {
  880. order = "id desc"
  881. }
  882. err := DB.Where("type = ?", channelType).Order(order).Limit(num).Offset(startIdx).Omit("key").Find(&channels).Error
  883. return channels, err
  884. }
  885. // Count channels of specific type
  886. func CountChannelsByType(channelType int) (int64, error) {
  887. var count int64
  888. err := DB.Model(&Channel{}).Where("type = ?", channelType).Count(&count).Error
  889. return count, err
  890. }
  891. // Return map[type]count for all channels
  892. func CountChannelsGroupByType() (map[int64]int64, error) {
  893. type result struct {
  894. Type int64 `gorm:"column:type"`
  895. Count int64 `gorm:"column:count"`
  896. }
  897. var results []result
  898. err := DB.Model(&Channel{}).Select("type, count(*) as count").Group("type").Find(&results).Error
  899. if err != nil {
  900. return nil, err
  901. }
  902. counts := make(map[int64]int64)
  903. for _, r := range results {
  904. counts[r.Type] = r.Count
  905. }
  906. return counts, nil
  907. }