io.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  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. sessionAlive := true
  77. for scanner.Scan() && sessionAlive {
  78. bytes := scanner.Bytes()
  79. if len(bytes) == 0 {
  80. continue
  81. }
  82. plugin_entities.ParsePluginUniversalEvent(
  83. bytes,
  84. func(session_id string, data []byte) {
  85. sessionMessage, err := parser.UnmarshalJsonBytes[plugin_entities.SessionMessage](data)
  86. if err != nil {
  87. l.Send(plugin_entities.SessionMessage{
  88. Type: plugin_entities.SESSION_MESSAGE_TYPE_ERROR,
  89. Data: parser.MarshalJsonBytes(plugin_entities.ErrorResponse{
  90. ErrorType: "PluginDaemonInnerError",
  91. Message: fmt.Sprintf("failed to parse session message %s, err: %v", bytes, err),
  92. }),
  93. })
  94. sessionAlive = false
  95. }
  96. l.Send(sessionMessage)
  97. },
  98. func() {},
  99. func(err string) {
  100. l.Send(plugin_entities.SessionMessage{
  101. Type: plugin_entities.SESSION_MESSAGE_TYPE_ERROR,
  102. Data: parser.MarshalJsonBytes(plugin_entities.ErrorResponse{
  103. ErrorType: "PluginDaemonInnerError",
  104. Message: fmt.Sprintf("encountered an error: %v", err),
  105. }),
  106. })
  107. },
  108. func(message string) {},
  109. )
  110. }
  111. if scanner.Err() != nil {
  112. l.Send(plugin_entities.SessionMessage{
  113. Type: plugin_entities.SESSION_MESSAGE_TYPE_ERROR,
  114. Data: parser.MarshalJsonBytes(plugin_entities.ErrorResponse{
  115. ErrorType: "PluginDaemonInnerError",
  116. Message: fmt.Sprintf("failed to read response body: %v", scanner.Err()),
  117. }),
  118. })
  119. }
  120. })
  121. }