lookupsource.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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 memory
  15. import (
  16. "fmt"
  17. "regexp"
  18. "strings"
  19. "github.com/lf-edge/ekuiper/internal/io/memory/store"
  20. "github.com/lf-edge/ekuiper/pkg/api"
  21. )
  22. // lookupsource is a lookup source that reads data from memory
  23. // The memory lookup table reads a global memory store for data
  24. type lookupsource struct {
  25. topic string
  26. topicRegex *regexp.Regexp
  27. table *store.Table
  28. key string
  29. }
  30. func (s *lookupsource) Open(ctx api.StreamContext) error {
  31. ctx.GetLogger().Infof("lookup source %s is opened with key %v", s.topic, s.key)
  32. var err error
  33. s.table, err = store.Reg(s.topic, s.topicRegex, s.key)
  34. return err
  35. }
  36. func (s *lookupsource) Configure(datasource string, props map[string]interface{}) error {
  37. s.topic = datasource
  38. if strings.ContainsAny(datasource, "+#") {
  39. r, err := getRegexp(datasource)
  40. if err != nil {
  41. return err
  42. }
  43. s.topicRegex = r
  44. }
  45. if k, ok := props["key"]; ok {
  46. if kk, ok := k.(string); ok {
  47. s.key = kk
  48. }
  49. }
  50. if s.key == "" {
  51. return fmt.Errorf("key is required for lookup source")
  52. }
  53. return nil
  54. }
  55. func (s *lookupsource) Lookup(ctx api.StreamContext, _ []string, keys []string, values []interface{}) ([]api.SourceTuple, error) {
  56. ctx.GetLogger().Debugf("lookup source %s is looking up keys %v with values %v", s.topic, keys, values)
  57. return s.table.Read(keys, values)
  58. }
  59. func (s *lookupsource) Close(ctx api.StreamContext) error {
  60. ctx.GetLogger().Infof("lookup source %s is closing", s.topic)
  61. return store.Unreg(s.topic, s.key)
  62. }