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 sync.map and optimise #1294

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all 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
23 changes: 8 additions & 15 deletions internal/corazawaf/rule.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ package corazawaf

import (
"fmt"
"hash/fnv"
"regexp"
"strconv"
"strings"
"sync"
"unsafe"
Expand Down Expand Up @@ -585,23 +587,14 @@ func (r *Rule) AddVariableNegation(v variables.RuleVariable, key string) error {
return nil
}

var transformationIDToName = []string{""}
var transformationNameToID = map[string]int{"": 0}
var transformationIDsLock = sync.Mutex{}
var transformationNameToID sync.Map

func transformationID(currentID int, transformationName string) int {
transformationIDsLock.Lock()
defer transformationIDsLock.Unlock()

currName := transformationIDToName[currentID]
nextName := fmt.Sprintf("%s+%s", currName, transformationName)
if id, ok := transformationNameToID[nextName]; ok {
return id
}

id := len(transformationIDToName)
transformationIDToName = append(transformationIDToName, nextName)
transformationNameToID[nextName] = id
nextName := strconv.Itoa(currentID) + "+" + transformationName
hasher := fnv.New64a()
hasher.Write([]byte(nextName))
id := int(hasher.Sum64())
transformationNameToID.LoadOrStore(id, nextName)
return id
}

Expand Down
17 changes: 17 additions & 0 deletions internal/corazawaf/rule_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,23 @@ func TestAddTransformation(t *testing.T) {
}
}

func BenchmarkAddTransformationUnique(b *testing.B) {
transformation := func(input string) (string, bool, error) {
return "Test", true, nil
}
b.ResetTimer()
b.RunParallel(func(p *testing.PB) {
rule := NewRule()
for p.Next() {
transformationName := "transformation" + b.Name()
err := rule.AddTransformation(transformationName, transformation)
if err != nil {
b.Fatalf("Failed to add a transformation: %s", err.Error())
}
}
})
}

func TestAddTransformationEmpty(t *testing.T) {
rule := NewRule()
transformationName := ""
Expand Down
Loading