io.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. package stdio_holder
  2. import (
  3. "bufio"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "sync"
  8. "time"
  9. "github.com/langgenius/dify-plugin-daemon/internal/types/entities/plugin_entities"
  10. "github.com/langgenius/dify-plugin-daemon/internal/utils/log"
  11. "github.com/langgenius/dify-plugin-daemon/internal/utils/parser"
  12. )
  13. var (
  14. stdio_holder sync.Map = sync.Map{}
  15. l *sync.Mutex = &sync.Mutex{}
  16. listeners map[string]func(string, []byte) = map[string]func(string, []byte){}
  17. )
  18. type stdioHolder struct {
  19. id string
  20. plugin_identity string
  21. writer io.WriteCloser
  22. reader io.ReadCloser
  23. err_reader io.ReadCloser
  24. l *sync.Mutex
  25. listener map[string]func([]byte)
  26. error_listener map[string]func([]byte)
  27. started bool
  28. err_message string
  29. last_err_message_updated_at time.Time
  30. health_chan chan bool
  31. health_chan_closed bool
  32. health_chan_lock *sync.Mutex
  33. last_active_at time.Time
  34. }
  35. func (s *stdioHolder) Error() error {
  36. if time.Since(s.last_err_message_updated_at) < 60*time.Second {
  37. if s.err_message != "" {
  38. return errors.New(s.err_message)
  39. }
  40. }
  41. return nil
  42. }
  43. func (s *stdioHolder) Stop() {
  44. s.writer.Close()
  45. s.reader.Close()
  46. s.err_reader.Close()
  47. s.health_chan_lock.Lock()
  48. if !s.health_chan_closed {
  49. close(s.health_chan)
  50. s.health_chan_closed = true
  51. }
  52. s.health_chan_lock.Unlock()
  53. stdio_holder.Delete(s.id)
  54. }
  55. func (s *stdioHolder) StartStdout() {
  56. s.started = true
  57. defer s.Stop()
  58. scanner := bufio.NewScanner(s.reader)
  59. for scanner.Scan() {
  60. data := scanner.Bytes()
  61. if len(data) == 0 {
  62. continue
  63. }
  64. event, err := parser.UnmarshalJsonBytes[plugin_entities.PluginUniversalEvent](data)
  65. if err != nil {
  66. // log.Error("unmarshal json failed: %s", err.Error())
  67. continue
  68. }
  69. session_id := event.SessionId
  70. switch event.Event {
  71. case plugin_entities.PLUGIN_EVENT_LOG:
  72. if event.Event == plugin_entities.PLUGIN_EVENT_LOG {
  73. logEvent, err := parser.UnmarshalJsonBytes[plugin_entities.PluginLogEvent](event.Data)
  74. if err != nil {
  75. log.Error("unmarshal json failed: %s", err.Error())
  76. continue
  77. }
  78. log.Info("plugin %s: %s", s.plugin_identity, logEvent.Message)
  79. }
  80. case plugin_entities.PLUGIN_EVENT_SESSION:
  81. for _, listener := range listeners {
  82. listener(s.id, event.Data)
  83. }
  84. for listener_session_id, listener := range s.listener {
  85. if listener_session_id == session_id {
  86. listener(event.Data)
  87. }
  88. }
  89. case plugin_entities.PLUGIN_EVENT_ERROR:
  90. log.Error("plugin %s: %s", s.plugin_identity, event.Data)
  91. case plugin_entities.PLUGIN_EVENT_HEARTBEAT:
  92. s.last_active_at = time.Now()
  93. }
  94. }
  95. }
  96. func (s *stdioHolder) WriteError(msg string) {
  97. const MAX_ERR_MSG_LEN = 1024
  98. reduce := len(msg) + len(s.err_message) - MAX_ERR_MSG_LEN
  99. if reduce > 0 {
  100. s.err_message = s.err_message[reduce:]
  101. }
  102. s.err_message += msg
  103. s.last_err_message_updated_at = time.Now()
  104. }
  105. func (s *stdioHolder) StartStderr() {
  106. for {
  107. buf := make([]byte, 1024)
  108. n, err := s.err_reader.Read(buf)
  109. if err != nil && err != io.EOF {
  110. break
  111. } else if err != nil {
  112. s.WriteError(fmt.Sprintf("%s\n", buf[:n]))
  113. break
  114. }
  115. if n > 0 {
  116. s.WriteError(fmt.Sprintf("%s\n", buf[:n]))
  117. }
  118. }
  119. }
  120. func (s *stdioHolder) Wait() error {
  121. s.health_chan_lock.Lock()
  122. if s.health_chan_closed {
  123. s.health_chan_lock.Unlock()
  124. return errors.New("you need to start the health check before waiting")
  125. }
  126. s.health_chan_lock.Unlock()
  127. ticker := time.NewTicker(5 * time.Second)
  128. defer ticker.Stop()
  129. // check status of plugin every 5 seconds
  130. for {
  131. s.health_chan_lock.Lock()
  132. if s.health_chan_closed {
  133. s.health_chan_lock.Unlock()
  134. break
  135. }
  136. s.health_chan_lock.Unlock()
  137. select {
  138. case <-ticker.C:
  139. // check heartbeat
  140. if time.Since(s.last_active_at) > 20*time.Second {
  141. return errors.New("plugin is not active")
  142. }
  143. case <-s.health_chan:
  144. // closed
  145. return s.Error()
  146. }
  147. }
  148. return nil
  149. }
  150. func (s *stdioHolder) GetID() string {
  151. return s.id
  152. }