source.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright 2022-2023 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/io/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 sc struct {
  23. Url string `json:"url,omitempty"`
  24. BufferLength int `json:"bufferLength,omitempty"`
  25. }
  26. type source struct {
  27. c *sc
  28. }
  29. func (s *source) Configure(_ string, props map[string]interface{}) error {
  30. cc := &sc{
  31. BufferLength: 1024,
  32. Url: DefaultNeuronUrl,
  33. }
  34. err := cast.MapToStruct(props, cc)
  35. if err != nil {
  36. return err
  37. }
  38. s.c = cc
  39. return nil
  40. }
  41. func (s *source) Open(ctx api.StreamContext, consumer chan<- api.SourceTuple, errCh chan<- error) {
  42. _, err := createOrGetConnection(ctx, s.c.Url)
  43. if err != nil {
  44. infra.DrainError(ctx, err, errCh)
  45. return
  46. }
  47. defer closeConnection(ctx, s.c.Url)
  48. ch := pubsub.CreateSub(TopicPrefix+s.c.Url, nil, fmt.Sprintf("%s_%s_%d", ctx.GetRuleId(), ctx.GetOpId(), ctx.GetInstanceId()), s.c.BufferLength)
  49. defer pubsub.CloseSourceConsumerChannel(TopicPrefix+s.c.Url, fmt.Sprintf("%s_%s_%d", ctx.GetRuleId(), ctx.GetOpId(), ctx.GetInstanceId()))
  50. for {
  51. select {
  52. case v, opened := <-ch:
  53. if !opened {
  54. return
  55. }
  56. consumer <- v
  57. case <-ctx.Done():
  58. return
  59. }
  60. }
  61. }
  62. func (s *source) Close(ctx api.StreamContext) error {
  63. ctx.GetLogger().Infof("closing neuron source")
  64. return nil
  65. }
  66. func GetSource() *source {
  67. return &source{}
  68. }