session.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package mcpproxy
  2. import (
  3. "sync"
  4. "github.com/labring/aiproxy/core/common"
  5. )
  6. // SessionManager defines the interface for managing session information
  7. type SessionManager interface {
  8. New() (sessionID string)
  9. // Set stores a sessionID and its corresponding backend endpoint
  10. Set(sessionID, endpoint string)
  11. // Get retrieves the backend endpoint for a sessionID
  12. Get(sessionID string) (string, bool)
  13. // Delete removes a sessionID from the store
  14. Delete(sessionID string)
  15. }
  16. // MemStore implements the SessionManager interface
  17. type MemStore struct {
  18. mu sync.RWMutex
  19. sessions map[string]string // sessionID -> host+endpoint
  20. }
  21. // NewMemStore creates a new session store
  22. func NewMemStore() *MemStore {
  23. return &MemStore{
  24. sessions: make(map[string]string),
  25. }
  26. }
  27. func (s *MemStore) New() string {
  28. return common.ShortUUID()
  29. }
  30. // Set stores a sessionID and its corresponding backend endpoint
  31. func (s *MemStore) Set(sessionID, endpoint string) {
  32. s.mu.Lock()
  33. defer s.mu.Unlock()
  34. s.sessions[sessionID] = endpoint
  35. }
  36. // Get retrieves the backend endpoint for a sessionID
  37. func (s *MemStore) Get(sessionID string) (string, bool) {
  38. s.mu.RLock()
  39. defer s.mu.RUnlock()
  40. endpoint, ok := s.sessions[sessionID]
  41. return endpoint, ok
  42. }
  43. // Delete removes a sessionID from the store
  44. func (s *MemStore) Delete(sessionID string) {
  45. s.mu.Lock()
  46. defer s.mu.Unlock()
  47. delete(s.sessions, sessionID)
  48. }