source.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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"
  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. connected bool
  26. }
  27. func (s *source) Configure(_ string, props map[string]interface{}) error {
  28. s.url = NeuronUrl
  29. s.bufferLength = 1024
  30. if c, ok := props["bufferLength"]; ok {
  31. if bl, err := cast.ToInt(c, cast.STRICT); err != nil || bl > 0 {
  32. s.bufferLength = bl
  33. }
  34. }
  35. return nil
  36. }
  37. func (s *source) Open(ctx api.StreamContext, consumer chan<- api.SourceTuple, errCh chan<- error) {
  38. err := createOrGetConnection(ctx, s.url)
  39. if err != nil {
  40. infra.DrainError(ctx, err, errCh)
  41. return
  42. }
  43. defer closeConnection(ctx, s.url)
  44. ch := memory.CreateSub(NeuronTopic, nil, fmt.Sprintf("%s_%s_%d", ctx.GetRuleId(), ctx.GetOpId(), ctx.GetInstanceId()), s.bufferLength)
  45. defer memory.CloseSourceConsumerChannel(NeuronTopic, fmt.Sprintf("%s_%s_%d", ctx.GetRuleId(), ctx.GetOpId(), ctx.GetInstanceId()))
  46. for {
  47. select {
  48. case v, opened := <-ch:
  49. if !opened {
  50. return
  51. }
  52. consumer <- v
  53. case <-ctx.Done():
  54. return
  55. }
  56. }
  57. }
  58. func (s *source) Close(ctx api.StreamContext) error {
  59. ctx.GetLogger().Infof("closing neuron source")
  60. return nil
  61. }
  62. func GetSource() *source {
  63. return &source{}
  64. }