sink.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. "fmt"
  17. "github.com/lf-edge/ekuiper/pkg/api"
  18. "strings"
  19. )
  20. type sink struct {
  21. topic string
  22. }
  23. func (s *sink) Open(ctx api.StreamContext) error {
  24. ctx.GetLogger().Debugf("Opening memory sink: %v", s.topic)
  25. CreatePub(s.topic)
  26. return nil
  27. }
  28. func (s *sink) Configure(props map[string]interface{}) error {
  29. if t, ok := props[IdProperty]; ok {
  30. if id, casted := t.(string); casted {
  31. if strings.ContainsAny(id, "#+") {
  32. return fmt.Errorf("invalid memory topic %s: wildcard found", id)
  33. }
  34. s.topic = id
  35. return nil
  36. } else {
  37. return fmt.Errorf("can't cast value %s to string", t)
  38. }
  39. }
  40. return fmt.Errorf("there is no topic property in the memory action")
  41. }
  42. func (s *sink) Collect(ctx api.StreamContext, data interface{}) error {
  43. ctx.GetLogger().Debugf("receive %+v", data)
  44. topic, err := ctx.ParseTemplate(s.topic, data)
  45. if err != nil {
  46. return err
  47. }
  48. switch d := data.(type) {
  49. case []map[string]interface{}:
  50. for _, el := range d {
  51. Produce(ctx, topic, el)
  52. }
  53. case map[string]interface{}:
  54. Produce(ctx, topic, d)
  55. default:
  56. return fmt.Errorf("unrecognized format of %s", data)
  57. }
  58. return nil
  59. }
  60. func (s *sink) Close(ctx api.StreamContext) error {
  61. ctx.GetLogger().Debugf("closing memory sink")
  62. RemovePub(s.topic)
  63. return nil
  64. }