io.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  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. if reduce > len(s.err_message) {
  101. s.err_message = ""
  102. } else {
  103. s.err_message = s.err_message[reduce:]
  104. }
  105. }
  106. s.err_message += msg
  107. s.last_err_message_updated_at = time.Now()
  108. }
  109. func (s *stdioHolder) StartStderr() {
  110. for {
  111. buf := make([]byte, 1024)
  112. n, err := s.err_reader.Read(buf)
  113. if err != nil && err != io.EOF {
  114. break
  115. } else if err != nil {
  116. s.WriteError(fmt.Sprintf("%s\n", buf[:n]))
  117. break
  118. }
  119. if n > 0 {
  120. s.WriteError(fmt.Sprintf("%s\n", buf[:n]))
  121. }
  122. }
  123. }
  124. func (s *stdioHolder) Wait() error {
  125. s.health_chan_lock.Lock()
  126. if s.health_chan_closed {
  127. s.health_chan_lock.Unlock()
  128. return errors.New("you need to start the health check before waiting")
  129. }
  130. s.health_chan_lock.Unlock()
  131. ticker := time.NewTicker(5 * time.Second)
  132. defer ticker.Stop()
  133. // check status of plugin every 5 seconds
  134. for {
  135. s.health_chan_lock.Lock()
  136. if s.health_chan_closed {
  137. s.health_chan_lock.Unlock()
  138. break
  139. }
  140. s.health_chan_lock.Unlock()
  141. select {
  142. case <-ticker.C:
  143. // check heartbeat
  144. if time.Since(s.last_active_at) > 20*time.Second {
  145. return errors.New("plugin is not active, does not respond to heartbeat in 20 seconds")
  146. }
  147. case <-s.health_chan:
  148. // closed
  149. return s.Error()
  150. }
  151. }
  152. return nil
  153. }
  154. func (s *stdioHolder) GetID() string {
  155. return s.id
  156. }