session.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package session_manager
  2. import (
  3. "errors"
  4. "sync"
  5. "github.com/google/uuid"
  6. "github.com/langgenius/dify-plugin-daemon/internal/types/entities"
  7. )
  8. var (
  9. sessions map[string]*Session = map[string]*Session{}
  10. session_lock sync.RWMutex
  11. )
  12. type Session struct {
  13. id string
  14. runtime entities.PluginRuntimeSessionIOInterface
  15. tenant_id string
  16. user_id string
  17. plugin_identity string
  18. }
  19. func NewSession(tenant_id string, user_id string, plugin_identity string) *Session {
  20. s := &Session{
  21. id: uuid.New().String(),
  22. tenant_id: tenant_id,
  23. user_id: user_id,
  24. plugin_identity: plugin_identity,
  25. }
  26. session_lock.Lock()
  27. defer session_lock.Unlock()
  28. sessions[s.id] = s
  29. return s
  30. }
  31. func GetSession(id string) *Session {
  32. session_lock.RLock()
  33. defer session_lock.RUnlock()
  34. return sessions[id]
  35. }
  36. func DeleteSession(id string) {
  37. session_lock.Lock()
  38. defer session_lock.Unlock()
  39. delete(sessions, id)
  40. }
  41. func (s *Session) Close() {
  42. session_lock.Lock()
  43. defer session_lock.Unlock()
  44. delete(sessions, s.id)
  45. }
  46. func (s *Session) ID() string {
  47. return s.id
  48. }
  49. func (s *Session) TenantID() string {
  50. return s.tenant_id
  51. }
  52. func (s *Session) UserID() string {
  53. return s.user_id
  54. }
  55. func (s *Session) PluginIdentity() string {
  56. return s.plugin_identity
  57. }
  58. func (s *Session) BindRuntime(runtime entities.PluginRuntimeSessionIOInterface) {
  59. s.runtime = runtime
  60. }
  61. func (s *Session) Write(data []byte) error {
  62. if s.runtime == nil {
  63. return errors.New("runtime not bound")
  64. }
  65. s.runtime.Write(s.id, data)
  66. return nil
  67. }