Caching http.send
s across different Eval()
s, using the Go API
#616
-
I'm trying to use OPA+Rego via the Go API in a case where I want to call out to an external API. I notice that we talk about caching of Is that expected? package main
import (
"context"
"fmt"
"log"
"time"
"github.com/open-policy-agent/opa/ast"
"github.com/open-policy-agent/opa/rego"
)
func main() {
ctx := context.Background()
// Create query that produces a single document.
r := rego.New(
rego.Query("data.example.p"),
rego.Module("example.rego",
`package example
response := http.send({
"method": "get",
"url": sprintf("https://endoflife.date/api/%s.json", [input.product]),
"cache": true,
"force_cache": true,
"force_cache_duration_seconds": 100000,
})
p = [response.status] { true }`,
))
query, err := r.PrepareForEval(ctx)
must(err)
input := ast.NewObject()
input.Insert(ast.StringTerm("product"), ast.StringTerm("nodejs"))
start := time.Now()
rs, err := query.Eval(ctx, rego.EvalParsedInput(input))
must(err)
fmt.Printf("rs[0].Expressions[0].Value: %v\n", rs[0].Expressions[0].Value)
t := time.Now()
elapsed := t.Sub(start)
fmt.Printf("elapsed: %v\n", elapsed)
// then again
start = time.Now()
rs, err = query.Eval(ctx, rego.EvalParsedInput(input))
must(err)
fmt.Printf("rs[0].Expressions[0].Value: %v\n", rs[0].Expressions[0].Value)
t = time.Now()
elapsed = t.Sub(start)
fmt.Printf("elapsed: %v\n", elapsed)
}
func must(err error) {
if err != nil {
log.Fatal(err)
}
} Example output:
Rego snippetpackage example
response := http.send({
"method": "get",
"url": sprintf("https://endoflife.date/api/%s.json", [input.product]),
"cache": true,
"force_cache": true,
"force_cache_duration_seconds": 100000,
})
p = [response.status] { true }
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
You'll need to pass a |
Beta Was this translation helpful? Give feedback.
You'll need to pass a
rego.InterQueryBuiltinCache()
for that to happen. I'm on the move right now but I think you'll figure it out from here. If not, let me know and I can give more details later. Should be many tests around this in OPA to look at for inspiration too!