Skip to content

Commit

Permalink
feat: use lazy map for variables
Browse files Browse the repository at this point in the history
  • Loading branch information
matheusfm committed Mar 12, 2024
1 parent 9c3a65f commit 8faebb3
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 8 deletions.
2 changes: 1 addition & 1 deletion pkg/validator/activation.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ type activation struct {
params any
apiVersions []string
kubeVersion any
variables map[string]any
variables any
}

func (a *activation) ResolveName(name string) (any, bool) {
Expand Down
23 changes: 16 additions & 7 deletions pkg/validator/validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,12 @@ import (

"github.com/google/cel-go/cel"
"github.com/google/cel-go/common/types"
"github.com/google/cel-go/common/types/ref"
marvin "github.com/undistro/marvin/pkg/types"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/version"

marvin "github.com/undistro/marvin/pkg/types"
"k8s.io/apiserver/pkg/cel/lazy"
)

// CELValidator is a Validator that performs CEL expressions
Expand Down Expand Up @@ -56,13 +57,11 @@ func (r *CELValidator) Validate(obj unstructured.Unstructured, params any) (bool
if err := r.setPodSpecParams(obj, input); err != nil {
return false, "", err
}
lazyMap := lazy.NewMapValue(types.MapType)
for _, v := range r.variables {
val, _, err := v.program.Eval(input)
if err != nil {
return false, "", fmt.Errorf("failed to evaluate variable %q: %s", v.name, err)
}
input.variables[v.name] = val.Value()
lazyMap.Append(v.name, callback(v, input))
}
input.variables = lazyMap
for i, prg := range r.programs {
out, _, err := prg.Eval(input)
if err != nil {
Expand All @@ -75,6 +74,16 @@ func (r *CELValidator) Validate(obj unstructured.Unstructured, params any) (bool
return true, "", nil
}

func callback(v compiledVariables, activation any) lazy.GetFieldFunc {
return func(_ *lazy.MapValue) ref.Val {
val, _, err := v.program.Eval(activation)
if err != nil {
return types.NewErr("variable %q fails to evaluate: %v", v.name, err)
}
return val
}
}

func (r *CELValidator) setPodSpecParams(obj unstructured.Unstructured, input *activation) error {
if !HasPodSpec(obj) {
return nil
Expand Down

0 comments on commit 8faebb3

Please sign in to comment.