random.go 4.1 KB

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