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

chore: Replace sync.Mutex with sync.Map #1197

Merged
merged 9 commits into from
Dec 30, 2024
12 changes: 4 additions & 8 deletions internal/corazawaf/rule.go
Original file line number Diff line number Diff line change
Expand Up @@ -586,22 +586,18 @@
}

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

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
if id, ok := transformationNameToID.Load(nextName); ok {
return id.(int)

Check warning on line 595 in internal/corazawaf/rule.go

View check run for this annotation

Codecov / codecov/patch

internal/corazawaf/rule.go#L594-L595

Added lines #L594 - L595 were not covered by tests
}

id := len(transformationIDToName)
transformationIDToName = append(transformationIDToName, nextName)
transformationNameToID[nextName] = id
transformationNameToID.Store(nextName, id)

Check warning on line 600 in internal/corazawaf/rule.go

View check run for this annotation

Codecov / codecov/patch

internal/corazawaf/rule.go#L600

Added line #L600 was not covered by tests
return id
}

Expand Down
34 changes: 34 additions & 0 deletions internal/corazawaf/rule_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,40 @@ 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 BenchmarkAddTransformationSame(b *testing.B) {
transformation := func(input string) (string, bool, error) {
return "Test", true, nil
}
b.ResetTimer()
b.RunParallel(func(p *testing.PB) {
for p.Next() {
rule := NewRule()
transformationName := "transformation"
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