rest_sink.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. // Copyright 2022-2023 EMQ Technologies Co., Ltd.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package http
  15. import (
  16. "fmt"
  17. "net/http"
  18. "net/url"
  19. "strings"
  20. "github.com/lf-edge/ekuiper/internal/conf"
  21. "github.com/lf-edge/ekuiper/internal/pkg/httpx"
  22. "github.com/lf-edge/ekuiper/pkg/api"
  23. "github.com/lf-edge/ekuiper/pkg/errorx"
  24. )
  25. type RestSink struct {
  26. ClientConf
  27. }
  28. func (ms *RestSink) Configure(ps map[string]interface{}) error {
  29. conf.Log.Infof("Initialized rest sink with configurations %#v.", ps)
  30. return ms.InitConf("", ps)
  31. }
  32. func (ms *RestSink) Open(ctx api.StreamContext) error {
  33. ctx.GetLogger().Infof("Opening HTTP pull source with conf %+v", ms.config)
  34. return nil
  35. }
  36. type MultiErrors []error
  37. func (me MultiErrors) AddError(err error) MultiErrors {
  38. me = append(me, err)
  39. return me
  40. }
  41. func (me MultiErrors) Error() string {
  42. s := make([]string, len(me))
  43. for i, v := range me {
  44. s = append(s, fmt.Sprintf("Error %d with info %s. \n", i, v))
  45. }
  46. return strings.Join(s, " ")
  47. }
  48. func (ms *RestSink) Collect(ctx api.StreamContext, item interface{}) error {
  49. logger := ctx.GetLogger()
  50. logger.Debugf("rest sink receive %s", item)
  51. decodedData, _, err := ctx.TransformOutput(item)
  52. if err != nil {
  53. logger.Warnf("rest sink decode data error: %v", err)
  54. return fmt.Errorf("rest sink decode data error: %v", err)
  55. }
  56. resp, err := ms.Send(ctx, decodedData, item, logger)
  57. if err != nil {
  58. e := err.Error()
  59. if urlErr, ok := err.(*url.Error); ok {
  60. // consider timeout and temporary error as recoverable
  61. if urlErr.Timeout() || urlErr.Temporary() {
  62. e = errorx.IOErr
  63. }
  64. }
  65. return fmt.Errorf(`%s: rest sink fails to send out the data: method=%s path="%s" request_body="%s"`,
  66. e,
  67. ms.config.Method,
  68. ms.config.Url,
  69. decodedData,
  70. )
  71. } else {
  72. logger.Debugf("rest sink got response %v", resp)
  73. _, b, err := ms.parseResponse(ctx, resp, ms.config.DebugResp, nil)
  74. if err != nil {
  75. return fmt.Errorf(`%s: http error. | method=%s path="%s" status=%d request_body="%s" response_body="%s"`,
  76. err,
  77. ms.config.Method,
  78. ms.config.Url,
  79. resp.StatusCode,
  80. decodedData,
  81. b,
  82. )
  83. }
  84. if ms.config.DebugResp {
  85. logger.Infof("Response raw content: %s\n", string(b))
  86. }
  87. }
  88. return nil
  89. }
  90. func (ms *RestSink) Send(ctx api.StreamContext, decodedData []byte, v interface{}, logger api.Logger) (*http.Response, error) {
  91. // Allow to use tokens in headers
  92. // TODO optimization: only do this if tokens are used in template
  93. if ms.tokens != nil {
  94. switch dt := v.(type) {
  95. case map[string]interface{}:
  96. for k, vv := range ms.tokens {
  97. dt[k] = vv
  98. }
  99. case []map[string]interface{}:
  100. for m := range dt {
  101. for k, vv := range ms.tokens {
  102. dt[m][k] = vv
  103. }
  104. }
  105. }
  106. }
  107. bodyType, err := ctx.ParseTemplate(ms.config.BodyType, v)
  108. if err != nil {
  109. return nil, err
  110. }
  111. method, err := ctx.ParseTemplate(ms.config.Method, v)
  112. if err != nil {
  113. return nil, err
  114. }
  115. u, err := ctx.ParseTemplate(ms.config.Url, v)
  116. if err != nil {
  117. return nil, err
  118. }
  119. headers, err := ms.parseHeaders(ctx, v)
  120. if err != nil {
  121. return nil, fmt.Errorf("rest sink headers template decode error: %v", err)
  122. }
  123. return httpx.Send(logger, ms.client, bodyType, method, u, headers, ms.config.SendSingle, decodedData)
  124. }
  125. func (ms *RestSink) Close(ctx api.StreamContext) error {
  126. logger := ctx.GetLogger()
  127. logger.Infof("Closing rest sink")
  128. return nil
  129. }