sink.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright 2021 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. }
  24. func (s *sink) Open(ctx api.StreamContext) error {
  25. ctx.GetLogger().Debugf("Opening memory sink: %v", s.topic)
  26. createPub(s.topic)
  27. return nil
  28. }
  29. func (s *sink) Configure(props map[string]interface{}) error {
  30. if t, ok := props[IdProperty]; ok {
  31. if id, casted := t.(string); casted {
  32. if strings.ContainsAny(id, "#+") {
  33. return fmt.Errorf("invalid memory topic %s: wildcard found", id)
  34. }
  35. s.topic = id
  36. return nil
  37. } else {
  38. return fmt.Errorf("can't cast value %s to string", t)
  39. }
  40. }
  41. return fmt.Errorf("there is no topic property in the memory action")
  42. }
  43. func (s *sink) Collect(ctx api.StreamContext, data interface{}) error {
  44. ctx.GetLogger().Debugf("receive %+v", data)
  45. if b, casted := data.([]byte); casted {
  46. d, err := toMap(b)
  47. if err != nil {
  48. return err
  49. }
  50. for _, el := range d {
  51. produce(ctx, s.topic, el)
  52. }
  53. return nil
  54. }
  55. return fmt.Errorf("unrecognized format of %s", data)
  56. }
  57. func (s *sink) Close(ctx api.StreamContext) error {
  58. ctx.GetLogger().Debugf("closing memory sink")
  59. return closeSink(s.topic)
  60. }
  61. func toMap(data []byte) ([]map[string]interface{}, error) {
  62. res := make([]map[string]interface{}, 0)
  63. err := json.Unmarshal(data, &res)
  64. if err != nil {
  65. return nil, err
  66. }
  67. return res, nil
  68. }