Skip to content

Commit 4154949

Browse files
authored
feat(test): Enable inter-query cache (#1073)
This improves performance for some Rego policies, such as those that use the http.send builtin. This is only enabled for the "conftest test" comamnd to avoid introducing flaky unit tests with "conftest verify" due to the caching. Signed-off-by: James Alseth <[email protected]>
1 parent cdd65ba commit 4154949

File tree

2 files changed

+17
-7
lines changed

2 files changed

+17
-7
lines changed

policy/engine.go

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -19,19 +19,21 @@ import (
1919
"github.com/open-policy-agent/opa/storage"
2020
"github.com/open-policy-agent/opa/storage/inmem"
2121
"github.com/open-policy-agent/opa/topdown"
22+
"github.com/open-policy-agent/opa/topdown/cache"
2223
"github.com/open-policy-agent/opa/topdown/print"
2324
"github.com/open-policy-agent/opa/version"
2425
)
2526

2627
// Engine represents the policy engine.
2728
type Engine struct {
28-
trace bool
29-
builtinErrors bool
30-
modules map[string]*ast.Module
31-
compiler *ast.Compiler
32-
store storage.Store
33-
policies map[string]string
34-
docs map[string]string
29+
trace bool
30+
builtinErrors bool
31+
modules map[string]*ast.Module
32+
compiler *ast.Compiler
33+
store storage.Store
34+
policies map[string]string
35+
docs map[string]string
36+
enableInterQueryCache bool
3537
}
3638

3739
// CompilerOptions defines the options for the Rego compiler.
@@ -171,6 +173,10 @@ func (e *Engine) ShowBuiltinErrors() {
171173
e.builtinErrors = true
172174
}
173175

176+
func (e *Engine) EnableInterQueryCache() {
177+
e.enableInterQueryCache = true
178+
}
179+
174180
// Check executes all of the loaded policies against the input and returns the results.
175181
func (e *Engine) Check(ctx context.Context, configs map[string]interface{}, namespace string) (output.CheckResults, error) {
176182
var checkResults output.CheckResults
@@ -454,6 +460,9 @@ func (e *Engine) query(ctx context.Context, input any, query string) (output.Que
454460
rego.PrintHook(ph),
455461
rego.BuiltinErrorList(builtInErrors),
456462
}
463+
if e.enableInterQueryCache {
464+
options = append(options, rego.InterQueryBuiltinCache(cache.NewInterQueryCacheWithContext(ctx, nil)))
465+
}
457466

458467
regoInstance := rego.New(options...)
459468
resultSet, err := regoInstance.Eval(ctx)

runner/test.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ func (t *TestRunner) Run(ctx context.Context, fileList []string) (output.CheckRe
7676
if err != nil {
7777
return nil, fmt.Errorf("load: %w", err)
7878
}
79+
engine.EnableInterQueryCache()
7980

8081
if t.Trace {
8182
engine.EnableTracing()

0 commit comments

Comments
 (0)