random.go 4.0 KB

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