cache.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  1. package model
  2. import (
  3. "context"
  4. "encoding"
  5. "errors"
  6. "fmt"
  7. "math/rand/v2"
  8. "slices"
  9. "sort"
  10. "sync"
  11. "sync/atomic"
  12. "time"
  13. "github.com/bytedance/sonic"
  14. "github.com/labring/aiproxy/core/common"
  15. "github.com/labring/aiproxy/core/common/config"
  16. "github.com/labring/aiproxy/core/common/conv"
  17. "github.com/labring/aiproxy/core/common/notify"
  18. "github.com/maruel/natural"
  19. "github.com/redis/go-redis/v9"
  20. log "github.com/sirupsen/logrus"
  21. )
  22. const (
  23. SyncFrequency = time.Minute * 3
  24. TokenCacheKey = "token:%s"
  25. GroupCacheKey = "group:%s"
  26. GroupModelTPMKey = "group:%s:model_tpm"
  27. )
  28. var (
  29. _ encoding.BinaryMarshaler = (*redisStringSlice)(nil)
  30. _ redis.Scanner = (*redisStringSlice)(nil)
  31. )
  32. type redisStringSlice []string
  33. func (r *redisStringSlice) ScanRedis(value string) error {
  34. return sonic.Unmarshal(conv.StringToBytes(value), r)
  35. }
  36. func (r redisStringSlice) MarshalBinary() ([]byte, error) {
  37. return sonic.Marshal(r)
  38. }
  39. type redisTime time.Time
  40. var (
  41. _ redis.Scanner = (*redisTime)(nil)
  42. _ encoding.BinaryMarshaler = (*redisTime)(nil)
  43. )
  44. func (t *redisTime) ScanRedis(value string) error {
  45. return (*time.Time)(t).UnmarshalBinary(conv.StringToBytes(value))
  46. }
  47. func (t redisTime) MarshalBinary() ([]byte, error) {
  48. return time.Time(t).MarshalBinary()
  49. }
  50. type TokenCache struct {
  51. ExpiredAt redisTime `json:"expired_at" redis:"e"`
  52. Group string `json:"group" redis:"g"`
  53. Key string `json:"-" redis:"-"`
  54. Name string `json:"name" redis:"n"`
  55. Subnets redisStringSlice `json:"subnets" redis:"s"`
  56. Models redisStringSlice `json:"models" redis:"m"`
  57. ID int `json:"id" redis:"i"`
  58. Status int `json:"status" redis:"st"`
  59. Quota float64 `json:"quota" redis:"q"`
  60. UsedAmount float64 `json:"used_amount" redis:"u"`
  61. availableSets []string
  62. modelsBySet map[string][]string
  63. }
  64. func (t *TokenCache) SetAvailableSets(availableSets []string) {
  65. t.availableSets = availableSets
  66. }
  67. func (t *TokenCache) SetModelsBySet(modelsBySet map[string][]string) {
  68. t.modelsBySet = modelsBySet
  69. }
  70. func (t *TokenCache) ContainsModel(model string) bool {
  71. if len(t.Models) != 0 {
  72. if !slices.Contains(t.Models, model) {
  73. return false
  74. }
  75. }
  76. return containsModel(model, t.availableSets, t.modelsBySet)
  77. }
  78. func containsModel(model string, sets []string, modelsBySet map[string][]string) bool {
  79. for _, set := range sets {
  80. if slices.Contains(modelsBySet[set], model) {
  81. return true
  82. }
  83. }
  84. return false
  85. }
  86. func (t *TokenCache) Range(fn func(model string) bool) {
  87. ranged := make(map[string]struct{})
  88. if len(t.Models) != 0 {
  89. for _, model := range t.Models {
  90. if _, ok := ranged[model]; !ok && containsModel(model, t.availableSets, t.modelsBySet) {
  91. if !fn(model) {
  92. return
  93. }
  94. }
  95. ranged[model] = struct{}{}
  96. }
  97. return
  98. }
  99. for _, set := range t.availableSets {
  100. for _, model := range t.modelsBySet[set] {
  101. if _, ok := ranged[model]; !ok {
  102. if !fn(model) {
  103. return
  104. }
  105. }
  106. ranged[model] = struct{}{}
  107. }
  108. }
  109. }
  110. func (t *Token) ToTokenCache() *TokenCache {
  111. return &TokenCache{
  112. ID: t.ID,
  113. Group: t.GroupID,
  114. Key: t.Key,
  115. Name: t.Name.String(),
  116. Models: t.Models,
  117. Subnets: t.Subnets,
  118. Status: t.Status,
  119. ExpiredAt: redisTime(t.ExpiredAt),
  120. Quota: t.Quota,
  121. UsedAmount: t.UsedAmount,
  122. }
  123. }
  124. func CacheDeleteToken(key string) error {
  125. if !common.RedisEnabled {
  126. return nil
  127. }
  128. return common.RedisDel(fmt.Sprintf(TokenCacheKey, key))
  129. }
  130. //nolint:gosec
  131. func CacheSetToken(token *TokenCache) error {
  132. if !common.RedisEnabled {
  133. return nil
  134. }
  135. key := fmt.Sprintf(TokenCacheKey, token.Key)
  136. pipe := common.RDB.Pipeline()
  137. pipe.HSet(context.Background(), key, token)
  138. expireTime := SyncFrequency + time.Duration(rand.Int64N(60)-30)*time.Second
  139. pipe.Expire(context.Background(), key, expireTime)
  140. _, err := pipe.Exec(context.Background())
  141. return err
  142. }
  143. func CacheGetTokenByKey(key string) (*TokenCache, error) {
  144. if !common.RedisEnabled {
  145. token, err := GetTokenByKey(key)
  146. if err != nil {
  147. return nil, err
  148. }
  149. return token.ToTokenCache(), nil
  150. }
  151. cacheKey := fmt.Sprintf(TokenCacheKey, key)
  152. tokenCache := &TokenCache{}
  153. err := common.RDB.HGetAll(context.Background(), cacheKey).Scan(tokenCache)
  154. if err == nil && tokenCache.ID != 0 {
  155. tokenCache.Key = key
  156. return tokenCache, nil
  157. } else if err != nil && !errors.Is(err, redis.Nil) {
  158. log.Errorf("get token (%s) from redis error: %s", key, err.Error())
  159. }
  160. token, err := GetTokenByKey(key)
  161. if err != nil {
  162. return nil, err
  163. }
  164. tc := token.ToTokenCache()
  165. if err := CacheSetToken(tc); err != nil {
  166. log.Error("redis set token error: " + err.Error())
  167. }
  168. return tc, nil
  169. }
  170. var updateTokenUsedAmountOnlyIncreaseScript = redis.NewScript(`
  171. local used_amount = redis.call("HGet", KEYS[1], "ua")
  172. if used_amount == false then
  173. return redis.status_reply("ok")
  174. end
  175. if ARGV[1] < used_amount then
  176. return redis.status_reply("ok")
  177. end
  178. redis.call("HSet", KEYS[1], "ua", ARGV[1])
  179. return redis.status_reply("ok")
  180. `)
  181. func CacheUpdateTokenUsedAmountOnlyIncrease(key string, amount float64) error {
  182. if !common.RedisEnabled {
  183. return nil
  184. }
  185. return updateTokenUsedAmountOnlyIncreaseScript.Run(context.Background(), common.RDB, []string{fmt.Sprintf(TokenCacheKey, key)}, amount).Err()
  186. }
  187. var updateTokenNameScript = redis.NewScript(`
  188. if redis.call("HExists", KEYS[1], "n") then
  189. redis.call("HSet", KEYS[1], "n", ARGV[1])
  190. end
  191. return redis.status_reply("ok")
  192. `)
  193. func CacheUpdateTokenName(key string, name string) error {
  194. if !common.RedisEnabled {
  195. return nil
  196. }
  197. return updateTokenNameScript.Run(context.Background(), common.RDB, []string{fmt.Sprintf(TokenCacheKey, key)}, name).Err()
  198. }
  199. var updateTokenStatusScript = redis.NewScript(`
  200. if redis.call("HExists", KEYS[1], "st") then
  201. redis.call("HSet", KEYS[1], "st", ARGV[1])
  202. end
  203. return redis.status_reply("ok")
  204. `)
  205. func CacheUpdateTokenStatus(key string, status int) error {
  206. if !common.RedisEnabled {
  207. return nil
  208. }
  209. return updateTokenStatusScript.Run(context.Background(), common.RDB, []string{fmt.Sprintf(TokenCacheKey, key)}, status).Err()
  210. }
  211. type redisGroupModelConfigMap map[string]GroupModelConfig
  212. var (
  213. _ redis.Scanner = (*redisGroupModelConfigMap)(nil)
  214. _ encoding.BinaryMarshaler = (*redisGroupModelConfigMap)(nil)
  215. )
  216. func (r *redisGroupModelConfigMap) ScanRedis(value string) error {
  217. return sonic.UnmarshalString(value, r)
  218. }
  219. func (r redisGroupModelConfigMap) MarshalBinary() ([]byte, error) {
  220. return sonic.Marshal(r)
  221. }
  222. type GroupCache struct {
  223. ID string `json:"-" redis:"-"`
  224. Status int `json:"status" redis:"st"`
  225. UsedAmount float64 `json:"used_amount" redis:"ua"`
  226. RPMRatio float64 `json:"rpm_ratio" redis:"rpm_r"`
  227. TPMRatio float64 `json:"tpm_ratio" redis:"tpm_r"`
  228. AvailableSets redisStringSlice `json:"available_sets" redis:"ass"`
  229. ModelConfigs redisGroupModelConfigMap `json:"model_configs" redis:"mc"`
  230. BalanceAlertEnabled bool `json:"balance_alert_enabled" redis:"bae"`
  231. BalanceAlertThreshold float64 `json:"balance_alert_threshold" redis:"bat"`
  232. }
  233. func (g *GroupCache) GetAvailableSets() []string {
  234. if len(g.AvailableSets) == 0 {
  235. return []string{ChannelDefaultSet}
  236. }
  237. return g.AvailableSets
  238. }
  239. func (g *Group) ToGroupCache() *GroupCache {
  240. modelConfigs := make(redisGroupModelConfigMap, len(g.GroupModelConfigs))
  241. for _, modelConfig := range g.GroupModelConfigs {
  242. modelConfigs[modelConfig.Model] = modelConfig
  243. }
  244. return &GroupCache{
  245. ID: g.ID,
  246. Status: g.Status,
  247. UsedAmount: g.UsedAmount,
  248. RPMRatio: g.RPMRatio,
  249. TPMRatio: g.TPMRatio,
  250. AvailableSets: g.AvailableSets,
  251. ModelConfigs: modelConfigs,
  252. BalanceAlertEnabled: g.BalanceAlertEnabled,
  253. BalanceAlertThreshold: g.BalanceAlertThreshold,
  254. }
  255. }
  256. func CacheDeleteGroup(id string) error {
  257. if !common.RedisEnabled {
  258. return nil
  259. }
  260. return common.RedisDel(fmt.Sprintf(GroupCacheKey, id))
  261. }
  262. var updateGroupRPMRatioScript = redis.NewScript(`
  263. if redis.call("HExists", KEYS[1], "rpm_r") then
  264. redis.call("HSet", KEYS[1], "rpm_r", ARGV[1])
  265. end
  266. return redis.status_reply("ok")
  267. `)
  268. func CacheUpdateGroupRPMRatio(id string, rpmRatio float64) error {
  269. if !common.RedisEnabled {
  270. return nil
  271. }
  272. return updateGroupRPMRatioScript.Run(context.Background(), common.RDB, []string{fmt.Sprintf(GroupCacheKey, id)}, rpmRatio).Err()
  273. }
  274. var updateGroupTPMRatioScript = redis.NewScript(`
  275. if redis.call("HExists", KEYS[1], "tpm_r") then
  276. redis.call("HSet", KEYS[1], "tpm_r", ARGV[1])
  277. end
  278. return redis.status_reply("ok")
  279. `)
  280. func CacheUpdateGroupTPMRatio(id string, tpmRatio float64) error {
  281. if !common.RedisEnabled {
  282. return nil
  283. }
  284. return updateGroupTPMRatioScript.Run(context.Background(), common.RDB, []string{fmt.Sprintf(GroupCacheKey, id)}, tpmRatio).Err()
  285. }
  286. var updateGroupStatusScript = redis.NewScript(`
  287. if redis.call("HExists", KEYS[1], "st") then
  288. redis.call("HSet", KEYS[1], "st", ARGV[1])
  289. end
  290. return redis.status_reply("ok")
  291. `)
  292. func CacheUpdateGroupStatus(id string, status int) error {
  293. if !common.RedisEnabled {
  294. return nil
  295. }
  296. return updateGroupStatusScript.Run(context.Background(), common.RDB, []string{fmt.Sprintf(GroupCacheKey, id)}, status).Err()
  297. }
  298. //nolint:gosec
  299. func CacheSetGroup(group *GroupCache) error {
  300. if !common.RedisEnabled {
  301. return nil
  302. }
  303. key := fmt.Sprintf(GroupCacheKey, group.ID)
  304. pipe := common.RDB.Pipeline()
  305. pipe.HSet(context.Background(), key, group)
  306. expireTime := SyncFrequency + time.Duration(rand.Int64N(60)-30)*time.Second
  307. pipe.Expire(context.Background(), key, expireTime)
  308. _, err := pipe.Exec(context.Background())
  309. return err
  310. }
  311. func CacheGetGroup(id string) (*GroupCache, error) {
  312. if !common.RedisEnabled {
  313. group, err := GetGroupByID(id, true)
  314. if err != nil {
  315. return nil, err
  316. }
  317. return group.ToGroupCache(), nil
  318. }
  319. cacheKey := fmt.Sprintf(GroupCacheKey, id)
  320. groupCache := &GroupCache{}
  321. err := common.RDB.HGetAll(context.Background(), cacheKey).Scan(groupCache)
  322. if err == nil && groupCache.Status != 0 {
  323. groupCache.ID = id
  324. return groupCache, nil
  325. } else if err != nil && !errors.Is(err, redis.Nil) {
  326. log.Errorf("get group (%s) from redis error: %s", id, err.Error())
  327. }
  328. group, err := GetGroupByID(id, true)
  329. if err != nil {
  330. return nil, err
  331. }
  332. gc := group.ToGroupCache()
  333. if err := CacheSetGroup(gc); err != nil {
  334. log.Error("redis set group error: " + err.Error())
  335. }
  336. return gc, nil
  337. }
  338. var updateGroupUsedAmountOnlyIncreaseScript = redis.NewScript(`
  339. local used_amount = redis.call("HGet", KEYS[1], "ua")
  340. if used_amount == false then
  341. return redis.status_reply("ok")
  342. end
  343. if ARGV[1] < used_amount then
  344. return redis.status_reply("ok")
  345. end
  346. redis.call("HSet", KEYS[1], "ua", ARGV[1])
  347. return redis.status_reply("ok")
  348. `)
  349. func CacheUpdateGroupUsedAmountOnlyIncrease(id string, amount float64) error {
  350. if !common.RedisEnabled {
  351. return nil
  352. }
  353. return updateGroupUsedAmountOnlyIncreaseScript.Run(context.Background(), common.RDB, []string{fmt.Sprintf(GroupCacheKey, id)}, amount).Err()
  354. }
  355. //nolint:gosec
  356. func CacheGetGroupModelTPM(group string, model string) (int64, error) {
  357. if !common.RedisEnabled {
  358. return GetGroupModelTPM(group, model)
  359. }
  360. cacheKey := fmt.Sprintf(GroupModelTPMKey, group)
  361. tpm, err := common.RDB.HGet(context.Background(), cacheKey, model).Int64()
  362. if err == nil {
  363. return tpm, nil
  364. } else if !errors.Is(err, redis.Nil) {
  365. log.Errorf("get group model tpm (%s:%s) from redis error: %s", group, model, err.Error())
  366. }
  367. tpm, err = GetGroupModelTPM(group, model)
  368. if err != nil {
  369. return 0, err
  370. }
  371. pipe := common.RDB.Pipeline()
  372. pipe.HSet(context.Background(), cacheKey, model, tpm)
  373. // 2-5 seconds
  374. pipe.Expire(context.Background(), cacheKey, 2*time.Second+time.Duration(rand.Int64N(3))*time.Second)
  375. _, err = pipe.Exec(context.Background())
  376. if err != nil {
  377. log.Errorf("set group model tpm (%s:%s) to redis error: %s", group, model, err.Error())
  378. }
  379. return tpm, nil
  380. }
  381. //nolint:revive
  382. type ModelConfigCache interface {
  383. GetModelConfig(model string) (*ModelConfig, bool)
  384. }
  385. // read-only cache
  386. //
  387. //nolint:revive
  388. type ModelCaches struct {
  389. ModelConfig ModelConfigCache
  390. EnabledModelsBySet map[string][]string
  391. EnabledModelConfigsBySet map[string][]*ModelConfig
  392. EnabledModelConfigsMap map[string]*ModelConfig
  393. EnabledModel2ChannelsBySet map[string]map[string][]*Channel
  394. DisabledModel2ChannelsBySet map[string]map[string][]*Channel
  395. }
  396. var modelCaches atomic.Pointer[ModelCaches]
  397. func init() {
  398. modelCaches.Store(new(ModelCaches))
  399. }
  400. func LoadModelCaches() *ModelCaches {
  401. return modelCaches.Load()
  402. }
  403. // InitModelConfigAndChannelCache initializes the channel cache from database
  404. func InitModelConfigAndChannelCache() error {
  405. modelConfig, err := initializeModelConfigCache()
  406. if err != nil {
  407. return err
  408. }
  409. // Load enabled channels from database
  410. enabledChannels, err := LoadEnabledChannels()
  411. if err != nil {
  412. return err
  413. }
  414. // Build model to channels map by set
  415. enabledModel2ChannelsBySet := buildModelToChannelsBySetMap(enabledChannels)
  416. // Sort channels by priority within each set
  417. sortChannelsByPriorityBySet(enabledModel2ChannelsBySet)
  418. // Build enabled models and configs by set
  419. enabledModelsBySet, enabledModelConfigsBySet, enabledModelConfigsMap := buildEnabledModelsBySet(enabledModel2ChannelsBySet, modelConfig)
  420. // Load disabled channels
  421. disabledChannels, err := LoadDisabledChannels()
  422. if err != nil {
  423. return err
  424. }
  425. // Build disabled model to channels map by set
  426. disabledModel2ChannelsBySet := buildModelToChannelsBySetMap(disabledChannels)
  427. // Update global cache atomically
  428. modelCaches.Store(&ModelCaches{
  429. ModelConfig: modelConfig,
  430. EnabledModelsBySet: enabledModelsBySet,
  431. EnabledModelConfigsBySet: enabledModelConfigsBySet,
  432. EnabledModelConfigsMap: enabledModelConfigsMap,
  433. EnabledModel2ChannelsBySet: enabledModel2ChannelsBySet,
  434. DisabledModel2ChannelsBySet: disabledModel2ChannelsBySet,
  435. })
  436. return nil
  437. }
  438. func LoadEnabledChannels() ([]*Channel, error) {
  439. var channels []*Channel
  440. err := DB.Where("status = ?", ChannelStatusEnabled).Find(&channels).Error
  441. if err != nil {
  442. return nil, err
  443. }
  444. for _, channel := range channels {
  445. initializeChannelModels(channel)
  446. initializeChannelModelMapping(channel)
  447. }
  448. return channels, nil
  449. }
  450. func LoadDisabledChannels() ([]*Channel, error) {
  451. var channels []*Channel
  452. err := DB.Where("status = ?", ChannelStatusDisabled).Find(&channels).Error
  453. if err != nil {
  454. return nil, err
  455. }
  456. for _, channel := range channels {
  457. initializeChannelModels(channel)
  458. initializeChannelModelMapping(channel)
  459. }
  460. return channels, nil
  461. }
  462. func LoadChannels() ([]*Channel, error) {
  463. var channels []*Channel
  464. err := DB.Find(&channels).Error
  465. if err != nil {
  466. return nil, err
  467. }
  468. for _, channel := range channels {
  469. initializeChannelModels(channel)
  470. initializeChannelModelMapping(channel)
  471. }
  472. return channels, nil
  473. }
  474. func LoadChannelByID(id int) (*Channel, error) {
  475. var channel Channel
  476. err := DB.First(&channel, id).Error
  477. if err != nil {
  478. return nil, err
  479. }
  480. initializeChannelModels(&channel)
  481. initializeChannelModelMapping(&channel)
  482. return &channel, nil
  483. }
  484. var _ ModelConfigCache = (*modelConfigMapCache)(nil)
  485. type modelConfigMapCache struct {
  486. modelConfigMap map[string]*ModelConfig
  487. }
  488. func (m *modelConfigMapCache) GetModelConfig(model string) (*ModelConfig, bool) {
  489. config, ok := m.modelConfigMap[model]
  490. return config, ok
  491. }
  492. var _ ModelConfigCache = (*disabledModelConfigCache)(nil)
  493. type disabledModelConfigCache struct {
  494. modelConfigs ModelConfigCache
  495. }
  496. func (d *disabledModelConfigCache) GetModelConfig(model string) (*ModelConfig, bool) {
  497. if config, ok := d.modelConfigs.GetModelConfig(model); ok {
  498. return config, true
  499. }
  500. return NewDefaultModelConfig(model), true
  501. }
  502. func initializeModelConfigCache() (ModelConfigCache, error) {
  503. modelConfigs, err := GetAllModelConfigs()
  504. if err != nil {
  505. return nil, err
  506. }
  507. newModelConfigMap := make(map[string]*ModelConfig)
  508. for _, modelConfig := range modelConfigs {
  509. newModelConfigMap[modelConfig.Model] = modelConfig
  510. }
  511. configs := &modelConfigMapCache{modelConfigMap: newModelConfigMap}
  512. if config.GetDisableModelConfig() {
  513. return &disabledModelConfigCache{modelConfigs: configs}, nil
  514. }
  515. return configs, nil
  516. }
  517. func initializeChannelModels(channel *Channel) {
  518. if len(channel.Models) == 0 {
  519. channel.Models = config.GetDefaultChannelModels()[channel.Type]
  520. return
  521. }
  522. findedModels, missingModels, err := GetModelConfigWithModels(channel.Models)
  523. if err != nil {
  524. return
  525. }
  526. if len(missingModels) > 0 {
  527. slices.Sort(missingModels)
  528. log.Errorf("model config not found: %v", missingModels)
  529. }
  530. slices.Sort(findedModels)
  531. channel.Models = findedModels
  532. }
  533. func initializeChannelModelMapping(channel *Channel) {
  534. if len(channel.ModelMapping) == 0 {
  535. channel.ModelMapping = config.GetDefaultChannelModelMapping()[channel.Type]
  536. }
  537. }
  538. func buildModelToChannelsBySetMap(channels []*Channel) map[string]map[string][]*Channel {
  539. modelMapBySet := make(map[string]map[string][]*Channel)
  540. for _, channel := range channels {
  541. sets := channel.GetSets()
  542. for _, set := range sets {
  543. if _, ok := modelMapBySet[set]; !ok {
  544. modelMapBySet[set] = make(map[string][]*Channel)
  545. }
  546. for _, model := range channel.Models {
  547. modelMapBySet[set][model] = append(modelMapBySet[set][model], channel)
  548. }
  549. }
  550. }
  551. return modelMapBySet
  552. }
  553. func sortChannelsByPriorityBySet(modelMapBySet map[string]map[string][]*Channel) {
  554. for _, modelMap := range modelMapBySet {
  555. for _, channels := range modelMap {
  556. sort.Slice(channels, func(i, j int) bool {
  557. return channels[i].GetPriority() > channels[j].GetPriority()
  558. })
  559. }
  560. }
  561. }
  562. func buildEnabledModelsBySet(modelMapBySet map[string]map[string][]*Channel, modelConfigCache ModelConfigCache) (
  563. map[string][]string,
  564. map[string][]*ModelConfig,
  565. map[string]*ModelConfig,
  566. ) {
  567. modelsBySet := make(map[string][]string)
  568. modelConfigsBySet := make(map[string][]*ModelConfig)
  569. modelConfigsMap := make(map[string]*ModelConfig)
  570. for set, modelMap := range modelMapBySet {
  571. models := make([]string, 0)
  572. configs := make([]*ModelConfig, 0)
  573. appended := make(map[string]struct{})
  574. for model := range modelMap {
  575. if _, ok := appended[model]; ok {
  576. continue
  577. }
  578. if config, ok := modelConfigCache.GetModelConfig(model); ok {
  579. models = append(models, model)
  580. configs = append(configs, config)
  581. appended[model] = struct{}{}
  582. modelConfigsMap[model] = config
  583. }
  584. }
  585. slices.Sort(models)
  586. slices.SortStableFunc(configs, SortModelConfigsFunc)
  587. modelsBySet[set] = models
  588. modelConfigsBySet[set] = configs
  589. }
  590. return modelsBySet, modelConfigsBySet, modelConfigsMap
  591. }
  592. func SortModelConfigsFunc(i, j *ModelConfig) int {
  593. if i.Owner != j.Owner {
  594. if natural.Less(string(i.Owner), string(j.Owner)) {
  595. return -1
  596. }
  597. return 1
  598. }
  599. if i.Type != j.Type {
  600. if i.Type < j.Type {
  601. return -1
  602. }
  603. return 1
  604. }
  605. if i.Model == j.Model {
  606. return 0
  607. }
  608. if natural.Less(i.Model, j.Model) {
  609. return -1
  610. }
  611. return 1
  612. }
  613. func SyncModelConfigAndChannelCache(ctx context.Context, wg *sync.WaitGroup, frequency time.Duration) {
  614. defer wg.Done()
  615. ticker := time.NewTicker(frequency)
  616. defer ticker.Stop()
  617. for {
  618. select {
  619. case <-ctx.Done():
  620. return
  621. case <-ticker.C:
  622. err := InitModelConfigAndChannelCache()
  623. if err != nil {
  624. notify.ErrorThrottle("syncModelChannel", time.Minute, "failed to sync channels", err.Error())
  625. }
  626. }
  627. }
  628. }