sink.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. "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. tpc, err := ctx.ParseDynamicProp(s.topic, data)
  45. if err != nil {
  46. return err
  47. }
  48. topic, ok := tpc.(string)
  49. if !ok {
  50. return fmt.Errorf("the value %v of dynamic prop %s for topic is not a string", s.topic, tpc)
  51. }
  52. switch d := data.(type) {
  53. case []map[string]interface{}:
  54. for _, el := range d {
  55. produce(ctx, topic, el)
  56. }
  57. case map[string]interface{}:
  58. produce(ctx, topic, d)
  59. default:
  60. return fmt.Errorf("unrecognized format of %s", data)
  61. }
  62. return nil
  63. }
  64. func (s *sink) Close(ctx api.StreamContext) error {
  65. ctx.GetLogger().Debugf("closing memory sink")
  66. return closeSink(s.topic)
  67. }