io.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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.lambda_url, "invoke")
  30. if err != nil {
  31. r.Error(fmt.Sprintf("Error creating request: %v", err))
  32. return
  33. }
  34. // create a new http request
  35. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  36. defer cancel()
  37. req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(data))
  38. if err != nil {
  39. r.Error(fmt.Sprintf("Error creating request: %v", err))
  40. return
  41. }
  42. req.Header.Set("Content-Type", "application/json")
  43. req.Header.Set("Accept", "text/event-stream")
  44. routine.Submit(func() {
  45. // remove the session from listeners
  46. defer r.listeners.Delete(session_id)
  47. response, err := r.client.Do(req)
  48. if err != nil {
  49. r.Error(fmt.Sprintf("Error sending request to aws lambda: %v", err))
  50. return
  51. }
  52. // write to data stream
  53. scanner := bufio.NewScanner(response.Body)
  54. for scanner.Scan() {
  55. bytes := scanner.Bytes()
  56. if len(bytes) == 0 {
  57. continue
  58. }
  59. data, err := parser.UnmarshalJsonBytes[plugin_entities.SessionMessage](bytes)
  60. if err != nil {
  61. log.Error("unmarshal json failed: %s, failed to parse session message", err.Error())
  62. continue
  63. }
  64. data.RuntimeType = r.Type()
  65. l.Send(data)
  66. }
  67. l.Close()
  68. })
  69. }