session.go 1.4 KB

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