Skip to content
This repository has been archived by the owner on Jun 6, 2024. It is now read-only.

Commit

Permalink
perf: cache compiled rules to improve performance by 30% (#944)
Browse files Browse the repository at this point in the history
* perf: cache rules compiled schemas

* cleanup logs

* add log

* cleanup

* cleanuo

* docs

* fix lint

* load schema once

* add error catchere
  • Loading branch information
royhadad authored Jun 7, 2023
1 parent abcea62 commit 32b504a
Showing 1 changed file with 19 additions and 5 deletions.
24 changes: 19 additions & 5 deletions pkg/jsonSchemaValidator/validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"os"
"strconv"
"strings"
"sync"

extensions "github.com/datreeio/datree/pkg/jsonSchemaValidator/extensions"
"github.com/ghodss/yaml"
Expand All @@ -14,10 +15,13 @@ import (
)

type JSONSchemaValidator struct {
rulesSchemasCache sync.Map
}

func New() *JSONSchemaValidator {
return &JSONSchemaValidator{}
return &JSONSchemaValidator{
rulesSchemasCache: sync.Map{},
}
}

type resourceMinimumCompiler struct{}
Expand Down Expand Up @@ -70,12 +74,22 @@ func (jsv *JSONSchemaValidator) Validate(schemaContent string, yamlContent []byt
compiler.RegisterExtension("customKeyRule101", extensions.CustomKeyRule101, extensions.CustomKeyRule101Compiler{})
compiler.RegisterExtension("customKeyRegoRule", extensions.CustomKeyRegoRule, extensions.CustomKeyRegoDefinitionCompiler{})

schema, err := compiler.Compile("schema.json")
if err != nil {
return nil, err
// compiler.Compile() is an expensive operation. We cache the compiled schema in rulesSchemasCache to avoid re-compiling the same schema.
schemaAny, ok := jsv.rulesSchemasCache.Load(schemaContent)
if !ok {
compiledSchema, err := compiler.Compile("schema.json")
if err != nil {
return nil, err
}
jsv.rulesSchemasCache.Store(schemaContent, compiledSchema)
schemaAny = compiledSchema
}
schema, ok := schemaAny.(*jsonschema.Schema)
if !ok {
return nil, fmt.Errorf("failed to convert schema to *jsonschema.Schema")
}

err = schema.Validate(jsonYamlContent)
err := schema.Validate(jsonYamlContent)

if err != nil {
if validationError, ok := err.(*jsonschema.ValidationError); ok {
Expand Down

0 comments on commit 32b504a

Please sign in to comment.