mcp-store.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package controller
  2. import (
  3. "context"
  4. "sync"
  5. "time"
  6. "github.com/labring/aiproxy/core/common"
  7. "github.com/labring/aiproxy/core/mcpproxy"
  8. "github.com/redis/go-redis/v9"
  9. )
  10. // Global variables for session management
  11. var (
  12. memStore mcpproxy.SessionManager = mcpproxy.NewMemStore()
  13. redisStore mcpproxy.SessionManager
  14. redisStoreOnce = &sync.Once{}
  15. )
  16. func getStore() mcpproxy.SessionManager {
  17. if common.RedisEnabled {
  18. redisStoreOnce.Do(func() {
  19. redisStore = newRedisStoreManager(common.RDB)
  20. })
  21. return redisStore
  22. }
  23. return memStore
  24. }
  25. // Redis-based session manager
  26. type redisStoreManager struct {
  27. rdb *redis.Client
  28. }
  29. func newRedisStoreManager(rdb *redis.Client) mcpproxy.SessionManager {
  30. return &redisStoreManager{
  31. rdb: rdb,
  32. }
  33. }
  34. var redisStoreManagerScript = redis.NewScript(`
  35. local key = KEYS[1]
  36. local value = redis.call('GET', key)
  37. if not value then
  38. return nil
  39. end
  40. redis.call('EXPIRE', key, 300)
  41. return value
  42. `)
  43. func (r *redisStoreManager) New() string {
  44. return common.ShortUUID()
  45. }
  46. func (r *redisStoreManager) Get(sessionID string) (string, bool) {
  47. ctx := context.Background()
  48. result, err := redisStoreManagerScript.Run(ctx, r.rdb, []string{common.RedisKey("mcp:session", sessionID)}).
  49. Result()
  50. if err != nil || result == nil {
  51. return "", false
  52. }
  53. res, ok := result.(string)
  54. return res, ok
  55. }
  56. func (r *redisStoreManager) Set(sessionID, endpoint string) {
  57. ctx := context.Background()
  58. r.rdb.Set(ctx, common.RedisKey("mcp:session", sessionID), endpoint, time.Minute*5)
  59. }
  60. func (r *redisStoreManager) Delete(session string) {
  61. ctx := context.Background()
  62. r.rdb.Del(ctx, common.RedisKey("mcp:session", session))
  63. }