source.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Copyright 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 neuron
  15. import (
  16. "fmt"
  17. "github.com/lf-edge/ekuiper/internal/topo/memory/pubsub"
  18. "github.com/lf-edge/ekuiper/pkg/api"
  19. "github.com/lf-edge/ekuiper/pkg/cast"
  20. "github.com/lf-edge/ekuiper/pkg/infra"
  21. )
  22. type source struct {
  23. url string
  24. bufferLength int
  25. }
  26. func (s *source) Configure(_ string, props map[string]interface{}) error {
  27. s.url = NeuronUrl
  28. s.bufferLength = 1024
  29. if c, ok := props["bufferLength"]; ok {
  30. if bl, err := cast.ToInt(c, cast.STRICT); err != nil || bl > 0 {
  31. s.bufferLength = bl
  32. }
  33. }
  34. return nil
  35. }
  36. func (s *source) Open(ctx api.StreamContext, consumer chan<- api.SourceTuple, errCh chan<- error) {
  37. err := createOrGetConnection(ctx, s.url)
  38. if err != nil {
  39. infra.DrainError(ctx, err, errCh)
  40. return
  41. }
  42. defer closeConnection(ctx, s.url)
  43. ch := pubsub.CreateSub(NeuronTopic, nil, fmt.Sprintf("%s_%s_%d", ctx.GetRuleId(), ctx.GetOpId(), ctx.GetInstanceId()), s.bufferLength)
  44. defer pubsub.CloseSourceConsumerChannel(NeuronTopic, fmt.Sprintf("%s_%s_%d", ctx.GetRuleId(), ctx.GetOpId(), ctx.GetInstanceId()))
  45. for {
  46. select {
  47. case v, opened := <-ch:
  48. if !opened {
  49. return
  50. }
  51. consumer <- v
  52. case <-ctx.Done():
  53. return
  54. }
  55. }
  56. }
  57. func (s *source) Close(ctx api.StreamContext) error {
  58. ctx.GetLogger().Infof("closing neuron source")
  59. return nil
  60. }
  61. func GetSource() *source {
  62. return &source{}
  63. }