io.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. package aws_manager
  2. import (
  3. "bufio"
  4. "bytes"
  5. "context"
  6. "fmt"
  7. "net/http"
  8. "net/url"
  9. "time"
  10. "github.com/langgenius/dify-plugin-daemon/internal/types/entities"
  11. "github.com/langgenius/dify-plugin-daemon/internal/types/entities/plugin_entities"
  12. "github.com/langgenius/dify-plugin-daemon/internal/utils/log"
  13. "github.com/langgenius/dify-plugin-daemon/internal/utils/parser"
  14. "github.com/langgenius/dify-plugin-daemon/internal/utils/routine"
  15. )
  16. func (r *AWSPluginRuntime) Listen(session_id string) *entities.Broadcast[plugin_entities.SessionMessage] {
  17. l := entities.NewBroadcast[plugin_entities.SessionMessage]()
  18. // store the listener
  19. r.listeners.Store(session_id, l)
  20. return l
  21. }
  22. // For AWS Lambda, write is equivalent to http request, it's not a normal stream like stdio and tcp
  23. func (r *AWSPluginRuntime) Write(session_id string, data []byte) {
  24. l, ok := r.listeners.Load(session_id)
  25. if !ok {
  26. log.Error("session %s not found", session_id)
  27. return
  28. }
  29. url, err := url.JoinPath(r.LambdaURL, "invoke")
  30. if err != nil {
  31. l.Send(plugin_entities.SessionMessage{
  32. Type: plugin_entities.SESSION_MESSAGE_TYPE_ERROR,
  33. Data: parser.MarshalJsonBytes(plugin_entities.ErrorResponse{
  34. ErrorType: "PluginDaemonInnerError",
  35. Message: fmt.Sprintf("Error creating request: %v", err),
  36. }),
  37. })
  38. l.Close()
  39. r.Error(fmt.Sprintf("Error creating request: %v", err))
  40. return
  41. }
  42. connectTime := 240 * time.Second
  43. // create a new http request
  44. ctx, cancel := context.WithTimeout(context.Background(), connectTime)
  45. time.AfterFunc(connectTime, cancel)
  46. req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(data))
  47. if err != nil {
  48. r.Error(fmt.Sprintf("Error creating request: %v", err))
  49. return
  50. }
  51. req.Header.Set("Content-Type", "application/json")
  52. req.Header.Set("Accept", "text/event-stream")
  53. req.Header.Set("Dify-Plugin-Session-ID", session_id)
  54. routine.Submit(func() {
  55. // remove the session from listeners
  56. defer r.listeners.Delete(session_id)
  57. defer l.Close()
  58. defer l.Send(plugin_entities.SessionMessage{
  59. Type: plugin_entities.SESSION_MESSAGE_TYPE_END,
  60. Data: []byte(""),
  61. })
  62. response, err := r.client.Do(req)
  63. if err != nil {
  64. l.Send(plugin_entities.SessionMessage{
  65. Type: plugin_entities.SESSION_MESSAGE_TYPE_ERROR,
  66. Data: parser.MarshalJsonBytes(plugin_entities.ErrorResponse{
  67. ErrorType: "PluginDaemonInnerError",
  68. Message: fmt.Sprintf("Error sending request to aws lambda: %v", err),
  69. }),
  70. })
  71. r.Error(fmt.Sprintf("Error sending request to aws lambda: %v", err))
  72. return
  73. }
  74. // write to data stream
  75. scanner := bufio.NewScanner(response.Body)
  76. // TODO: set a reasonable buffer size or use a reader, this is a temporary solution
  77. scanner.Buffer(make([]byte, 1024), 5*1024*1024)
  78. sessionAlive := true
  79. for scanner.Scan() && sessionAlive {
  80. bytes := scanner.Bytes()
  81. if len(bytes) == 0 {
  82. continue
  83. }
  84. plugin_entities.ParsePluginUniversalEvent(
  85. bytes,
  86. func(session_id string, data []byte) {
  87. sessionMessage, err := parser.UnmarshalJsonBytes[plugin_entities.SessionMessage](data)
  88. if err != nil {
  89. l.Send(plugin_entities.SessionMessage{
  90. Type: plugin_entities.SESSION_MESSAGE_TYPE_ERROR,
  91. Data: parser.MarshalJsonBytes(plugin_entities.ErrorResponse{
  92. ErrorType: "PluginDaemonInnerError",
  93. Message: fmt.Sprintf("failed to parse session message %s, err: %v", bytes, err),
  94. }),
  95. })
  96. sessionAlive = false
  97. }
  98. l.Send(sessionMessage)
  99. },
  100. func() {},
  101. func(err string) {
  102. l.Send(plugin_entities.SessionMessage{
  103. Type: plugin_entities.SESSION_MESSAGE_TYPE_ERROR,
  104. Data: parser.MarshalJsonBytes(plugin_entities.ErrorResponse{
  105. ErrorType: "PluginDaemonInnerError",
  106. Message: fmt.Sprintf("encountered an error: %v", err),
  107. }),
  108. })
  109. },
  110. func(message string) {},
  111. )
  112. }
  113. if err := scanner.Err(); err != nil {
  114. l.Send(plugin_entities.SessionMessage{
  115. Type: plugin_entities.SESSION_MESSAGE_TYPE_ERROR,
  116. Data: parser.MarshalJsonBytes(plugin_entities.ErrorResponse{
  117. ErrorType: "PluginDaemonInnerError",
  118. Message: fmt.Sprintf("failed to read response body: %v", err),
  119. }),
  120. })
  121. }
  122. })
  123. }