random.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  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 main
  15. import (
  16. "bytes"
  17. "encoding/json"
  18. "fmt"
  19. "github.com/lf-edge/ekuiper/pkg/api"
  20. "github.com/lf-edge/ekuiper/pkg/cast"
  21. "github.com/lf-edge/ekuiper/pkg/message"
  22. "math/rand"
  23. "strings"
  24. "time"
  25. )
  26. const dedupStateKey = "input"
  27. type randomSourceConfig struct {
  28. Interval int `json:"interval"`
  29. Seed int `json:"seed"`
  30. Pattern map[string]interface{} `json:"pattern"`
  31. // how long will the source trace for deduplication. If 0, deduplicate is disabled; if negative, deduplicate will be the whole life time
  32. Deduplicate int `json:"deduplicate"`
  33. Format string `json:"format"`
  34. }
  35. //Emit data randomly with only a string field
  36. type randomSource struct {
  37. conf *randomSourceConfig
  38. list [][]byte
  39. }
  40. func (s *randomSource) Configure(topic string, props map[string]interface{}) error {
  41. cfg := &randomSourceConfig{}
  42. err := cast.MapToStruct(props, cfg)
  43. if err != nil {
  44. return fmt.Errorf("read properties %v fail with error: %v", props, err)
  45. }
  46. if cfg.Interval <= 0 {
  47. return fmt.Errorf("source `random` property `interval` must be a positive integer but got %d", cfg.Interval)
  48. }
  49. if cfg.Pattern == nil {
  50. return fmt.Errorf("source `random` property `pattern` is required")
  51. }
  52. if cfg.Interval <= 0 {
  53. return fmt.Errorf("source `random` property `seed` must be a positive integer but got %d", cfg.Seed)
  54. }
  55. if strings.ToLower(cfg.Format) != message.FormatJson {
  56. return fmt.Errorf("random source only supports `json` format")
  57. }
  58. s.conf = cfg
  59. return nil
  60. }
  61. func (s *randomSource) Open(ctx api.StreamContext, consumer chan<- api.SourceTuple, errCh chan<- error) {
  62. logger := ctx.GetLogger()
  63. logger.Debugf("open random source with deduplicate %d", s.conf.Deduplicate)
  64. if s.conf.Deduplicate != 0 {
  65. list, err := ctx.GetState(dedupStateKey)
  66. if err != nil {
  67. errCh <- err
  68. return
  69. }
  70. if list == nil {
  71. list = make([][]byte, 0)
  72. } else {
  73. if l, ok := list.([][]byte); ok {
  74. logger.Debugf("restore list %v", l)
  75. s.list = l
  76. } else {
  77. s.list = make([][]byte, 0)
  78. logger.Warnf("random source gets invalid state, ignore it")
  79. }
  80. }
  81. }
  82. t := time.NewTicker(time.Duration(s.conf.Interval) * time.Millisecond)
  83. defer t.Stop()
  84. for {
  85. select {
  86. case <-t.C:
  87. next := randomize(s.conf.Pattern, s.conf.Seed)
  88. if s.conf.Deduplicate != 0 && s.isDup(ctx, next) {
  89. logger.Debugf("find duplicate")
  90. continue
  91. }
  92. logger.Debugf("Send out data %v", next)
  93. consumer <- api.NewDefaultSourceTuple(next, nil)
  94. case <-ctx.Done():
  95. return
  96. }
  97. }
  98. }
  99. func randomize(p map[string]interface{}, seed int) map[string]interface{} {
  100. r := make(map[string]interface{})
  101. for k, v := range p {
  102. //TODO other data types
  103. vi, err := cast.ToInt(v, cast.STRICT)
  104. if err != nil {
  105. break
  106. }
  107. r[k] = vi + rand.Intn(seed)
  108. }
  109. return r
  110. }
  111. func (s *randomSource) isDup(ctx api.StreamContext, next map[string]interface{}) bool {
  112. logger := ctx.GetLogger()
  113. ns, err := json.Marshal(next)
  114. if err != nil {
  115. logger.Warnf("invalid input data %v", next)
  116. return true
  117. }
  118. for _, ps := range s.list {
  119. if bytes.Compare(ns, ps) == 0 {
  120. logger.Debugf("got duplicate %s", ns)
  121. return true
  122. }
  123. }
  124. logger.Debugf("no duplicate %s", ns)
  125. if s.conf.Deduplicate > 0 && len(s.list) >= s.conf.Deduplicate {
  126. s.list = s.list[1:]
  127. }
  128. s.list = append(s.list, ns)
  129. ctx.PutState(dedupStateKey, s.list)
  130. return false
  131. }
  132. func (s *randomSource) Close(_ api.StreamContext) error {
  133. return nil
  134. }
  135. func Random() api.Source {
  136. return &randomSource{}
  137. }