io.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  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. s.last_active_at = time.Now()
  58. defer s.Stop()
  59. scanner := bufio.NewScanner(s.reader)
  60. for scanner.Scan() {
  61. data := scanner.Bytes()
  62. if len(data) == 0 {
  63. continue
  64. }
  65. event, err := parser.UnmarshalJsonBytes[plugin_entities.PluginUniversalEvent](data)
  66. if err != nil {
  67. // log.Error("unmarshal json failed: %s", err.Error())
  68. continue
  69. }
  70. session_id := event.SessionId
  71. switch event.Event {
  72. case plugin_entities.PLUGIN_EVENT_LOG:
  73. if event.Event == plugin_entities.PLUGIN_EVENT_LOG {
  74. logEvent, err := parser.UnmarshalJsonBytes[plugin_entities.PluginLogEvent](event.Data)
  75. if err != nil {
  76. log.Error("unmarshal json failed: %s", err.Error())
  77. continue
  78. }
  79. log.Info("plugin %s: %s", s.plugin_identity, logEvent.Message)
  80. }
  81. case plugin_entities.PLUGIN_EVENT_SESSION:
  82. for _, listener := range listeners {
  83. listener(s.id, event.Data)
  84. }
  85. for listener_session_id, listener := range s.listener {
  86. if listener_session_id == session_id {
  87. listener(event.Data)
  88. }
  89. }
  90. case plugin_entities.PLUGIN_EVENT_ERROR:
  91. log.Error("plugin %s: %s", s.plugin_identity, event.Data)
  92. case plugin_entities.PLUGIN_EVENT_HEARTBEAT:
  93. s.last_active_at = time.Now()
  94. }
  95. }
  96. }
  97. func (s *stdioHolder) WriteError(msg string) {
  98. const MAX_ERR_MSG_LEN = 1024
  99. reduce := len(msg) + len(s.err_message) - MAX_ERR_MSG_LEN
  100. if reduce > 0 {
  101. if reduce > len(s.err_message) {
  102. s.err_message = ""
  103. } else {
  104. s.err_message = s.err_message[reduce:]
  105. }
  106. }
  107. s.err_message += msg
  108. s.last_err_message_updated_at = time.Now()
  109. }
  110. func (s *stdioHolder) StartStderr() {
  111. for {
  112. buf := make([]byte, 1024)
  113. n, err := s.err_reader.Read(buf)
  114. if err != nil && err != io.EOF {
  115. break
  116. } else if err != nil {
  117. s.WriteError(fmt.Sprintf("%s\n", buf[:n]))
  118. break
  119. }
  120. if n > 0 {
  121. s.WriteError(fmt.Sprintf("%s\n", buf[:n]))
  122. }
  123. }
  124. }
  125. func (s *stdioHolder) Wait() error {
  126. s.health_chan_lock.Lock()
  127. if s.health_chan_closed {
  128. s.health_chan_lock.Unlock()
  129. return errors.New("you need to start the health check before waiting")
  130. }
  131. s.health_chan_lock.Unlock()
  132. ticker := time.NewTicker(5 * time.Second)
  133. defer ticker.Stop()
  134. // check status of plugin every 5 seconds
  135. for {
  136. s.health_chan_lock.Lock()
  137. if s.health_chan_closed {
  138. s.health_chan_lock.Unlock()
  139. break
  140. }
  141. s.health_chan_lock.Unlock()
  142. select {
  143. case <-ticker.C:
  144. // check heartbeat
  145. if time.Since(s.last_active_at) > 20*time.Second {
  146. return errors.New("plugin is not active, does not respond to heartbeat in 20 seconds")
  147. }
  148. case <-s.health_chan:
  149. // closed
  150. return s.Error()
  151. }
  152. }
  153. return nil
  154. }
  155. func (s *stdioHolder) GetID() string {
  156. return s.id
  157. }