sink.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // Copyright 2021-2022 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 memory
  15. import (
  16. "encoding/json"
  17. "fmt"
  18. "github.com/lf-edge/ekuiper/pkg/api"
  19. "strings"
  20. )
  21. type sink struct {
  22. topic string
  23. hasTransform bool
  24. }
  25. func (s *sink) Open(ctx api.StreamContext) error {
  26. ctx.GetLogger().Debugf("Opening memory sink: %v", s.topic)
  27. CreatePub(s.topic)
  28. return nil
  29. }
  30. func (s *sink) Configure(props map[string]interface{}) error {
  31. if t, ok := props[IdProperty]; ok {
  32. if id, casted := t.(string); casted {
  33. if strings.ContainsAny(id, "#+") {
  34. return fmt.Errorf("invalid memory topic %s: wildcard found", id)
  35. }
  36. s.topic = id
  37. } else {
  38. return fmt.Errorf("can't cast value %s to string", t)
  39. }
  40. }
  41. if _, ok := props["dataTemplate"]; ok {
  42. s.hasTransform = true
  43. }
  44. return nil
  45. }
  46. func (s *sink) Collect(ctx api.StreamContext, data interface{}) error {
  47. ctx.GetLogger().Debugf("receive %+v", data)
  48. topic, err := ctx.ParseTemplate(s.topic, data)
  49. if err != nil {
  50. return err
  51. }
  52. if s.hasTransform {
  53. jsonBytes, _, err := ctx.TransformOutput(data)
  54. if err != nil {
  55. return err
  56. }
  57. m := make(map[string]interface{})
  58. err = json.Unmarshal(jsonBytes, &m)
  59. if err != nil {
  60. return fmt.Errorf("fail to decode data %s after applying dataTemplate for error %v", string(jsonBytes), err)
  61. }
  62. data = m
  63. }
  64. switch d := data.(type) {
  65. case []map[string]interface{}:
  66. for _, el := range d {
  67. Produce(ctx, topic, el)
  68. }
  69. case map[string]interface{}:
  70. Produce(ctx, topic, d)
  71. default:
  72. return fmt.Errorf("unrecognized format of %s", data)
  73. }
  74. return nil
  75. }
  76. func (s *sink) Close(ctx api.StreamContext) error {
  77. ctx.GetLogger().Debugf("closing memory sink")
  78. RemovePub(s.topic)
  79. return nil
  80. }