Skip to content

Commit

Permalink
compile during creation not invocation.
Browse files Browse the repository at this point in the history
  • Loading branch information
jiahuif committed Feb 24, 2024
1 parent 41a60b0 commit e208964
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -39,18 +39,27 @@ import (

func compilePolicy(policy *Policy) PolicyEvaluator {
// removal not yet supported
evaluator := &evaluator{policy: policy}
return evaluator.Invoke
e := &evaluator{policy: policy}
e.compiledEvaluator, e.err = e.compile(plugincel.OptionalVariableDeclarations{HasParams: e.hasParams()})
return e.Invoke
}

type evaluator struct {
policy *Policy

compiledEvaluator *compiledEvaluator
// err holds the error during the creation of compiledEvaluator
err error
}

type compiledEvaluator struct {
programs []cel.Program
}

func (e *evaluator) hasParams() bool {
return e.policy.Spec.ParamKind != nil
}

func (e *evaluator) compile(vars plugincel.OptionalVariableDeclarations) (*compiledEvaluator, error) {
envSet, err := createEnvSet(vars)
if err != nil {
Expand Down Expand Up @@ -81,7 +90,7 @@ func (e *evaluator) compile(vars plugincel.OptionalVariableDeclarations) (*compi
}

func (e *evaluator) Invoke(ctx context.Context, matchedResource schema.GroupVersionResource, versionedAttr *admission.VersionedAttributes, o admission.ObjectInterfaces, versionedParams runtime.Object, namespace *v1.Namespace, typeConverter managedfields.TypeConverter, runtimeCELCostBudget int64) (patch.Application, error) {
compiled, err := e.compile(plugincel.OptionalVariableDeclarations{HasParams: versionedParams != nil})
err := e.err
if err != nil {
return nil, err
}
Expand All @@ -99,7 +108,7 @@ func (e *evaluator) Invoke(ctx context.Context, matchedResource schema.GroupVers
if err != nil {
return nil, err
}
for _, p := range compiled.programs {
for _, p := range e.compiledEvaluator.programs {
v, _, err := p.ContextEval(ctx, a)
if err != nil {
return nil, err
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ func TestCompilation(t *testing.T) {
} {
t.Run(tc.name, func(t *testing.T) {
e := &evaluator{policy: tc.policy}
c, err := e.compile(plugincel.OptionalVariableDeclarations{})
c, err := e.compile(plugincel.OptionalVariableDeclarations{HasParams: e.hasParams()})
if err != nil {
if tc.expectedErr == "" {
t.Fatalf("unexpected error: %v", err)
Expand Down

0 comments on commit e208964

Please sign in to comment.