channel_affinity.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. package service
  2. import (
  3. "fmt"
  4. "regexp"
  5. "strconv"
  6. "strings"
  7. "sync"
  8. "time"
  9. "github.com/QuantumNous/new-api/common"
  10. "github.com/QuantumNous/new-api/pkg/cachex"
  11. "github.com/QuantumNous/new-api/setting/operation_setting"
  12. "github.com/gin-gonic/gin"
  13. "github.com/samber/hot"
  14. "github.com/tidwall/gjson"
  15. )
  16. const (
  17. ginKeyChannelAffinityCacheKey = "channel_affinity_cache_key"
  18. ginKeyChannelAffinityTTLSeconds = "channel_affinity_ttl_seconds"
  19. ginKeyChannelAffinityMeta = "channel_affinity_meta"
  20. ginKeyChannelAffinityLogInfo = "channel_affinity_log_info"
  21. channelAffinityCacheNamespace = "new-api:channel_affinity:v1"
  22. )
  23. var (
  24. channelAffinityCacheOnce sync.Once
  25. channelAffinityCache *cachex.HybridCache[int]
  26. channelAffinityRegexCache sync.Map // map[string]*regexp.Regexp
  27. )
  28. type channelAffinityMeta struct {
  29. CacheKey string
  30. TTLSeconds int
  31. RuleName string
  32. KeySourceType string
  33. KeySourceKey string
  34. KeySourcePath string
  35. KeyFingerprint string
  36. UsingGroup string
  37. ModelName string
  38. RequestPath string
  39. }
  40. type ChannelAffinityCacheStats struct {
  41. Enabled bool `json:"enabled"`
  42. Total int `json:"total"`
  43. Unknown int `json:"unknown"`
  44. ByRuleName map[string]int `json:"by_rule_name"`
  45. CacheCapacity int `json:"cache_capacity"`
  46. CacheAlgo string `json:"cache_algo"`
  47. }
  48. func getChannelAffinityCache() *cachex.HybridCache[int] {
  49. channelAffinityCacheOnce.Do(func() {
  50. setting := operation_setting.GetChannelAffinitySetting()
  51. capacity := setting.MaxEntries
  52. if capacity <= 0 {
  53. capacity = 100_000
  54. }
  55. defaultTTLSeconds := setting.DefaultTTLSeconds
  56. if defaultTTLSeconds <= 0 {
  57. defaultTTLSeconds = 3600
  58. }
  59. channelAffinityCache = cachex.NewHybridCache[int](cachex.HybridCacheConfig[int]{
  60. Namespace: cachex.Namespace(channelAffinityCacheNamespace),
  61. Redis: common.RDB,
  62. RedisEnabled: func() bool {
  63. return common.RedisEnabled && common.RDB != nil
  64. },
  65. RedisCodec: cachex.IntCodec{},
  66. Memory: func() *hot.HotCache[string, int] {
  67. return hot.NewHotCache[string, int](hot.LRU, capacity).
  68. WithTTL(time.Duration(defaultTTLSeconds) * time.Second).
  69. WithJanitor().
  70. Build()
  71. },
  72. })
  73. })
  74. return channelAffinityCache
  75. }
  76. func GetChannelAffinityCacheStats() ChannelAffinityCacheStats {
  77. setting := operation_setting.GetChannelAffinitySetting()
  78. if setting == nil {
  79. return ChannelAffinityCacheStats{
  80. Enabled: false,
  81. Total: 0,
  82. Unknown: 0,
  83. ByRuleName: map[string]int{},
  84. }
  85. }
  86. cache := getChannelAffinityCache()
  87. mainCap, _ := cache.Capacity()
  88. mainAlgo, _ := cache.Algorithm()
  89. rules := setting.Rules
  90. ruleByName := make(map[string]operation_setting.ChannelAffinityRule, len(rules))
  91. for _, r := range rules {
  92. name := strings.TrimSpace(r.Name)
  93. if name == "" {
  94. continue
  95. }
  96. if !r.IncludeRuleName {
  97. continue
  98. }
  99. ruleByName[name] = r
  100. }
  101. byRuleName := make(map[string]int, len(ruleByName))
  102. for name := range ruleByName {
  103. byRuleName[name] = 0
  104. }
  105. keys, err := cache.Keys()
  106. if err != nil {
  107. common.SysError(fmt.Sprintf("channel affinity cache list keys failed: err=%v", err))
  108. keys = nil
  109. }
  110. total := len(keys)
  111. unknown := 0
  112. for _, k := range keys {
  113. prefix := channelAffinityCacheNamespace + ":"
  114. if !strings.HasPrefix(k, prefix) {
  115. unknown++
  116. continue
  117. }
  118. rest := strings.TrimPrefix(k, prefix)
  119. parts := strings.Split(rest, ":")
  120. if len(parts) < 2 {
  121. unknown++
  122. continue
  123. }
  124. ruleName := parts[0]
  125. rule, ok := ruleByName[ruleName]
  126. if !ok {
  127. unknown++
  128. continue
  129. }
  130. if rule.IncludeUsingGroup {
  131. if len(parts) < 3 {
  132. unknown++
  133. continue
  134. }
  135. }
  136. byRuleName[ruleName]++
  137. }
  138. return ChannelAffinityCacheStats{
  139. Enabled: setting.Enabled,
  140. Total: total,
  141. Unknown: unknown,
  142. ByRuleName: byRuleName,
  143. CacheCapacity: mainCap,
  144. CacheAlgo: mainAlgo,
  145. }
  146. }
  147. func ClearChannelAffinityCacheAll() int {
  148. cache := getChannelAffinityCache()
  149. keys, err := cache.Keys()
  150. if err != nil {
  151. common.SysError(fmt.Sprintf("channel affinity cache list keys failed: err=%v", err))
  152. keys = nil
  153. }
  154. if len(keys) > 0 {
  155. if _, err := cache.DeleteMany(keys); err != nil {
  156. common.SysError(fmt.Sprintf("channel affinity cache delete many failed: err=%v", err))
  157. }
  158. }
  159. return len(keys)
  160. }
  161. func ClearChannelAffinityCacheByRuleName(ruleName string) (int, error) {
  162. ruleName = strings.TrimSpace(ruleName)
  163. if ruleName == "" {
  164. return 0, fmt.Errorf("rule_name 不能为空")
  165. }
  166. setting := operation_setting.GetChannelAffinitySetting()
  167. if setting == nil {
  168. return 0, fmt.Errorf("channel_affinity_setting 未初始化")
  169. }
  170. var matchedRule *operation_setting.ChannelAffinityRule
  171. for i := range setting.Rules {
  172. r := &setting.Rules[i]
  173. if strings.TrimSpace(r.Name) != ruleName {
  174. continue
  175. }
  176. matchedRule = r
  177. break
  178. }
  179. if matchedRule == nil {
  180. return 0, fmt.Errorf("未知规则名称")
  181. }
  182. if !matchedRule.IncludeRuleName {
  183. return 0, fmt.Errorf("该规则未启用 include_rule_name,无法按规则清空缓存")
  184. }
  185. cache := getChannelAffinityCache()
  186. deleted, err := cache.DeleteByPrefix(ruleName)
  187. if err != nil {
  188. return 0, err
  189. }
  190. return deleted, nil
  191. }
  192. func matchAnyRegexCached(patterns []string, s string) bool {
  193. if len(patterns) == 0 || s == "" {
  194. return false
  195. }
  196. for _, pattern := range patterns {
  197. if pattern == "" {
  198. continue
  199. }
  200. re, ok := channelAffinityRegexCache.Load(pattern)
  201. if !ok {
  202. compiled, err := regexp.Compile(pattern)
  203. if err != nil {
  204. continue
  205. }
  206. re = compiled
  207. channelAffinityRegexCache.Store(pattern, re)
  208. }
  209. if re.(*regexp.Regexp).MatchString(s) {
  210. return true
  211. }
  212. }
  213. return false
  214. }
  215. func matchAnyIncludeFold(patterns []string, s string) bool {
  216. if len(patterns) == 0 || s == "" {
  217. return false
  218. }
  219. sLower := strings.ToLower(s)
  220. for _, p := range patterns {
  221. p = strings.TrimSpace(p)
  222. if p == "" {
  223. continue
  224. }
  225. if strings.Contains(sLower, strings.ToLower(p)) {
  226. return true
  227. }
  228. }
  229. return false
  230. }
  231. func extractChannelAffinityValue(c *gin.Context, src operation_setting.ChannelAffinityKeySource) string {
  232. switch src.Type {
  233. case "context_int":
  234. if src.Key == "" {
  235. return ""
  236. }
  237. v := c.GetInt(src.Key)
  238. if v <= 0 {
  239. return ""
  240. }
  241. return strconv.Itoa(v)
  242. case "context_string":
  243. if src.Key == "" {
  244. return ""
  245. }
  246. return strings.TrimSpace(c.GetString(src.Key))
  247. case "gjson":
  248. if src.Path == "" {
  249. return ""
  250. }
  251. body, err := common.GetRequestBody(c)
  252. if err != nil || len(body) == 0 {
  253. return ""
  254. }
  255. res := gjson.GetBytes(body, src.Path)
  256. if !res.Exists() {
  257. return ""
  258. }
  259. switch res.Type {
  260. case gjson.String, gjson.Number, gjson.True, gjson.False:
  261. return strings.TrimSpace(res.String())
  262. default:
  263. return strings.TrimSpace(res.Raw)
  264. }
  265. default:
  266. return ""
  267. }
  268. }
  269. func buildChannelAffinityCacheKeySuffix(rule operation_setting.ChannelAffinityRule, usingGroup string, affinityValue string) string {
  270. parts := make([]string, 0, 3)
  271. if rule.IncludeRuleName && rule.Name != "" {
  272. parts = append(parts, rule.Name)
  273. }
  274. if rule.IncludeUsingGroup && usingGroup != "" {
  275. parts = append(parts, usingGroup)
  276. }
  277. parts = append(parts, affinityValue)
  278. return strings.Join(parts, ":")
  279. }
  280. func setChannelAffinityContext(c *gin.Context, meta channelAffinityMeta) {
  281. c.Set(ginKeyChannelAffinityCacheKey, meta.CacheKey)
  282. c.Set(ginKeyChannelAffinityTTLSeconds, meta.TTLSeconds)
  283. c.Set(ginKeyChannelAffinityMeta, meta)
  284. }
  285. func getChannelAffinityContext(c *gin.Context) (string, int, bool) {
  286. keyAny, ok := c.Get(ginKeyChannelAffinityCacheKey)
  287. if !ok {
  288. return "", 0, false
  289. }
  290. key, ok := keyAny.(string)
  291. if !ok || key == "" {
  292. return "", 0, false
  293. }
  294. ttlAny, ok := c.Get(ginKeyChannelAffinityTTLSeconds)
  295. if !ok {
  296. return key, 0, true
  297. }
  298. ttlSeconds, _ := ttlAny.(int)
  299. return key, ttlSeconds, true
  300. }
  301. func getChannelAffinityMeta(c *gin.Context) (channelAffinityMeta, bool) {
  302. anyMeta, ok := c.Get(ginKeyChannelAffinityMeta)
  303. if !ok {
  304. return channelAffinityMeta{}, false
  305. }
  306. meta, ok := anyMeta.(channelAffinityMeta)
  307. if !ok {
  308. return channelAffinityMeta{}, false
  309. }
  310. return meta, true
  311. }
  312. func affinityFingerprint(s string) string {
  313. if s == "" {
  314. return ""
  315. }
  316. hex := common.Sha1([]byte(s))
  317. if len(hex) >= 8 {
  318. return hex[:8]
  319. }
  320. return hex
  321. }
  322. func GetPreferredChannelByAffinity(c *gin.Context, modelName string, usingGroup string) (int, bool) {
  323. setting := operation_setting.GetChannelAffinitySetting()
  324. if setting == nil || !setting.Enabled {
  325. return 0, false
  326. }
  327. path := ""
  328. if c != nil && c.Request != nil && c.Request.URL != nil {
  329. path = c.Request.URL.Path
  330. }
  331. userAgent := ""
  332. if c != nil && c.Request != nil {
  333. userAgent = c.Request.UserAgent()
  334. }
  335. for _, rule := range setting.Rules {
  336. if !matchAnyRegexCached(rule.ModelRegex, modelName) {
  337. continue
  338. }
  339. if len(rule.PathRegex) > 0 && !matchAnyRegexCached(rule.PathRegex, path) {
  340. continue
  341. }
  342. if len(rule.UserAgentInclude) > 0 && !matchAnyIncludeFold(rule.UserAgentInclude, userAgent) {
  343. continue
  344. }
  345. var affinityValue string
  346. var usedSource operation_setting.ChannelAffinityKeySource
  347. for _, src := range rule.KeySources {
  348. affinityValue = extractChannelAffinityValue(c, src)
  349. if affinityValue != "" {
  350. usedSource = src
  351. break
  352. }
  353. }
  354. if affinityValue == "" {
  355. continue
  356. }
  357. if rule.ValueRegex != "" && !matchAnyRegexCached([]string{rule.ValueRegex}, affinityValue) {
  358. continue
  359. }
  360. ttlSeconds := rule.TTLSeconds
  361. if ttlSeconds <= 0 {
  362. ttlSeconds = setting.DefaultTTLSeconds
  363. }
  364. cacheKeySuffix := buildChannelAffinityCacheKeySuffix(rule, usingGroup, affinityValue)
  365. cacheKeyFull := channelAffinityCacheNamespace + ":" + cacheKeySuffix
  366. setChannelAffinityContext(c, channelAffinityMeta{
  367. CacheKey: cacheKeyFull,
  368. TTLSeconds: ttlSeconds,
  369. RuleName: rule.Name,
  370. KeySourceType: strings.TrimSpace(usedSource.Type),
  371. KeySourceKey: strings.TrimSpace(usedSource.Key),
  372. KeySourcePath: strings.TrimSpace(usedSource.Path),
  373. KeyFingerprint: affinityFingerprint(affinityValue),
  374. UsingGroup: usingGroup,
  375. ModelName: modelName,
  376. RequestPath: path,
  377. })
  378. cache := getChannelAffinityCache()
  379. channelID, found, err := cache.Get(cacheKeySuffix)
  380. if err != nil {
  381. common.SysError(fmt.Sprintf("channel affinity cache get failed: key=%s, err=%v", cacheKeyFull, err))
  382. return 0, false
  383. }
  384. if found {
  385. return channelID, true
  386. }
  387. return 0, false
  388. }
  389. return 0, false
  390. }
  391. func MarkChannelAffinityUsed(c *gin.Context, selectedGroup string, channelID int) {
  392. if c == nil || channelID <= 0 {
  393. return
  394. }
  395. meta, ok := getChannelAffinityMeta(c)
  396. if !ok {
  397. return
  398. }
  399. info := map[string]interface{}{
  400. "reason": meta.RuleName,
  401. "rule_name": meta.RuleName,
  402. "using_group": meta.UsingGroup,
  403. "selected_group": selectedGroup,
  404. "model": meta.ModelName,
  405. "request_path": meta.RequestPath,
  406. "channel_id": channelID,
  407. "key_source": meta.KeySourceType,
  408. "key_key": meta.KeySourceKey,
  409. "key_path": meta.KeySourcePath,
  410. "key_fp": meta.KeyFingerprint,
  411. }
  412. c.Set(ginKeyChannelAffinityLogInfo, info)
  413. }
  414. func AppendChannelAffinityAdminInfo(c *gin.Context, adminInfo map[string]interface{}) {
  415. if c == nil || adminInfo == nil {
  416. return
  417. }
  418. anyInfo, ok := c.Get(ginKeyChannelAffinityLogInfo)
  419. if !ok || anyInfo == nil {
  420. return
  421. }
  422. adminInfo["channel_affinity"] = anyInfo
  423. }
  424. func RecordChannelAffinity(c *gin.Context, channelID int) {
  425. if channelID <= 0 {
  426. return
  427. }
  428. setting := operation_setting.GetChannelAffinitySetting()
  429. if setting == nil || !setting.Enabled {
  430. return
  431. }
  432. if setting.SwitchOnSuccess && c != nil {
  433. if successChannelID := c.GetInt("channel_id"); successChannelID > 0 {
  434. channelID = successChannelID
  435. }
  436. }
  437. cacheKey, ttlSeconds, ok := getChannelAffinityContext(c)
  438. if !ok {
  439. return
  440. }
  441. if ttlSeconds <= 0 {
  442. ttlSeconds = setting.DefaultTTLSeconds
  443. }
  444. if ttlSeconds <= 0 {
  445. ttlSeconds = 3600
  446. }
  447. cache := getChannelAffinityCache()
  448. if err := cache.SetWithTTL(cacheKey, channelID, time.Duration(ttlSeconds)*time.Second); err != nil {
  449. common.SysError(fmt.Sprintf("channel affinity cache set failed: key=%s, err=%v", cacheKey, err))
  450. }
  451. }