Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add counter reset support #152

Merged
merged 9 commits into from
Sep 20, 2024
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 49 additions & 9 deletions pkg/genlib/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,15 +39,55 @@ type Config struct {
}

type ConfigField struct {
Name string `config:"name"`
Fuzziness float64 `config:"fuzziness"`
Range Range `config:"range"`
Cardinality int `config:"cardinality"`
Period time.Duration `config:"period"`
Enum []string `config:"enum"`
ObjectKeys []string `config:"object_keys"`
Value any `config:"value"`
Counter bool `config:"counter"`
Name string `config:"name"`
Fuzziness float64 `config:"fuzziness"`
Range Range `config:"range"`
Cardinality int `config:"cardinality"`
Period time.Duration `config:"period"`
Enum []string `config:"enum"`
ObjectKeys []string `config:"object_keys"`
Value any `config:"value"`
Counter bool `config:"counter"`
CounterReset *CounterReset `config:"counter_reset"`
}

const (
CounterResetStrategyRandom string = "random"
CounterResetStrategyProbabilistic string = "probabilistic"
CounterResetStrategyAfterN string = "after_n"
)

type CounterReset struct {
Strategy string `config:"strategy"`
Probability *uint64 `config:"probability"`
ResetAfterN *uint64 `config:"reset_after_n"`
}

func (cf ConfigField) ValidateCounterResetStrategy() error {
if cf.Counter && cf.CounterReset != nil &&
cf.CounterReset.Strategy != CounterResetStrategyRandom &&
cf.CounterReset.Strategy != CounterResetStrategyProbabilistic &&
cf.CounterReset.Strategy != CounterResetStrategyAfterN {
return errors.New("counter_reset strategy must be one of 'random', 'probabilistic', 'after_n'")
}

return nil
}

func (cf ConfigField) ValidateCounterResetAfterN() error {
if cf.Counter && cf.CounterReset != nil && cf.CounterReset.Strategy == CounterResetStrategyAfterN && cf.CounterReset.ResetAfterN == nil {
return errors.New("counter_reset after_n requires 'reset_after_n' value to be set")
}

return nil
}

func (cf ConfigField) ValidateCounterResetProbabilistic() error {
if cf.Counter && cf.CounterReset != nil && cf.CounterReset.Strategy == CounterResetStrategyProbabilistic && cf.CounterReset.Probability == nil {
return errors.New("counter_reset probabilistic requires 'probability' value to be set")
}

return nil
}

func (cf ConfigField) ValidForDateField() error {
Expand Down
66 changes: 64 additions & 2 deletions pkg/genlib/generator_interface.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,6 @@ func newGenState() *genState {
}

func bindField(cfg Config, field Field, fieldMap map[string]any, withReturn bool) error {

// Check for hardcoded field value
if len(field.Value) > 0 {
if withReturn {
Expand Down Expand Up @@ -194,7 +193,6 @@ func bindByType(cfg Config, field Field, fieldMap map[string]any) (err error) {
}

func bindByTypeWithReturn(cfg Config, field Field, fieldMap map[string]any) (err error) {

fieldCfg, _ := cfg.GetField(field.Name)

switch field.Type {
Expand Down Expand Up @@ -971,6 +969,18 @@ func bindLongWithReturn(fieldCfg ConfigField, field Field, fieldMap map[string]a
return err
}

if err := fieldCfg.ValidateCounterResetStrategy(); err != nil {
return err
}

if err := fieldCfg.ValidateCounterResetAfterN(); err != nil {
return err
}

if err := fieldCfg.ValidateCounterResetProbabilistic(); err != nil {
return err
}

if len(fieldCfg.Enum) > 0 {
var emitF emitF
idx := customRand.Intn(len(fieldCfg.Enum))
Expand Down Expand Up @@ -1008,6 +1018,26 @@ func bindLongWithReturn(fieldCfg ConfigField, field Field, fieldMap map[string]a
dummyInt = fuzzyIntCounter(previous, fieldCfg.Fuzziness)
}

if fieldCfg.CounterReset != nil {
switch fieldCfg.CounterReset.Strategy {
case config.CounterResetStrategyRandom:
// 50% chance to reset
if customRand.Intn(2) == 0 {
dummyInt = 0
}
case config.CounterResetStrategyProbabilistic:
// Probability% chance to reset
if customRand.Intn(100) < int(*fieldCfg.CounterReset.Probability) {
dummyInt = 0
}
case config.CounterResetStrategyAfterN:
// Reset after N
if state.counter%*fieldCfg.CounterReset.ResetAfterN == 0 {
dummyInt = 0
}
}
}

state.prevCache[field.Name] = dummyInt
return dummyInt
}
Expand Down Expand Up @@ -1090,6 +1120,18 @@ func bindDoubleWithReturn(fieldCfg ConfigField, field Field, fieldMap map[string
return err
}

if err := fieldCfg.ValidateCounterResetStrategy(); err != nil {
return err
}

if err := fieldCfg.ValidateCounterResetAfterN(); err != nil {
return err
}

if err := fieldCfg.ValidateCounterResetProbabilistic(); err != nil {
return err
}

if len(fieldCfg.Enum) > 0 {
var emitF emitF
idx := customRand.Intn(len(fieldCfg.Enum))
Expand Down Expand Up @@ -1127,6 +1169,26 @@ func bindDoubleWithReturn(fieldCfg ConfigField, field Field, fieldMap map[string
dummyFloat = fuzzyFloatCounter(previous, fieldCfg.Fuzziness)
}

if fieldCfg.CounterReset != nil {
switch fieldCfg.CounterReset.Strategy {
case config.CounterResetStrategyRandom:
// 50% chance to reset
if customRand.Intn(2) == 0 {
dummyFloat = 0
}
case config.CounterResetStrategyProbabilistic:
// Probability% chance to reset
if customRand.Intn(100) < int(*fieldCfg.CounterReset.Probability) {
dummyFloat = 0
}
case config.CounterResetStrategyAfterN:
// Reset after N
if state.counter%*fieldCfg.CounterReset.ResetAfterN == 0 {
dummyFloat = 0
}
}
}

state.prevCache[field.Name] = dummyFloat
return dummyFloat
}
Expand Down
63 changes: 63 additions & 0 deletions pkg/genlib/generator_with_text_template_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -755,6 +755,69 @@ func Test_FieldIPWithTextTemplate(t *testing.T) {
}
}

func Test_FieldLongCounterResetAfterN5WithTextTemplate(t *testing.T) {
fld := Field{
Name: "counter_reset_test",
Type: FieldTypeLong,
}

afterN := 5

template := []byte(`{{$counter_reset_test := generate "counter_reset_test"}}{"counter_reset_test":"{{$counter_reset_test}}"}`)
configYaml := []byte(fmt.Sprintf(`fields:
- name: counter_reset_test
counter: true
counter_reset:
strategy: after_n
reset_after_n: %d`, afterN))
t.Logf("with template: %s", string(template))

cfg, err := config.LoadConfigFromYaml(configYaml)
if err != nil {
t.Fatal(err)
}

g := makeGeneratorWithTextTemplate(t, cfg, []Field{fld}, template, 40)

var buf bytes.Buffer

nSpins := int64(40)

var resetCount int64
expectedResetCount := nSpins / int64(afterN) // 8

for i := int64(0); i < nSpins; i++ {
if err := g.Emit(&buf); err != nil {
t.Fatal(err)
}

m := unmarshalJSONT[string](t, buf.Bytes())
buf.Reset()

if len(m) != 1 {
t.Errorf("Expected map size 1, got %d", len(m))
}

v, ok := m[fld.Name]
if !ok {
t.Errorf("Missing key %v", fld.Name)
}

if i%int64(afterN) == 0 {
if v != "0" {
t.Errorf("Expected counter to reset to 0, got %v", v)
}
resetCount++
}

t.Logf("counter value: %v", v)
}

if resetCount != expectedResetCount {
t.Errorf("Expected counter to reset %d times, got %d", expectedResetCount, resetCount)
}
}

func Test_FieldFloatsWithTextTemplate(t *testing.T) {
_testNumericWithTextTemplate[float64](t, FieldTypeDouble)
_testNumericWithTextTemplate[float32](t, FieldTypeFloat)
Expand Down
Loading