Skip to content

Instantly share code, notes, and snippets.

@patrick-east
Created April 13, 2019 08:23
Show Gist options
  • Select an option

  • Save patrick-east/7c16d3db2025ffa85ff10aacf6cd88bd to your computer and use it in GitHub Desktop.

Select an option

Save patrick-east/7c16d3db2025ffa85ff10aacf6cd88bd to your computer and use it in GitHub Desktop.
OPA Rego.Update() sample
package main
import (
"context"
"fmt"
"os"
"sort"
"github.com/open-policy-agent/opa/metrics"
"github.com/open-policy-agent/opa/rego"
)
func printMetrics(m metrics.Metrics) {
all := m.All()
var keys []string
for k := range all {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
fmt.Printf("%s: %+v\n", k, all[k].(map[string]interface{})["mean"])
}
}
func main() {
ctx := context.Background()
// Raw input data that will be used in the first evaluation
input := map[string]interface{}{"x": 2}
m := metrics.New()
bh := metrics.New()
ah := metrics.New()
iterations := 5000
for i := 0; i < iterations; i++ {
// Create a simple query over the input.
r := rego.New(
rego.Module("test.rego", `
package test
p {
input.x = 1
}
`),
rego.Query("data.test.p"),
rego.Input(input),
rego.Metrics(m),
)
// Run evaluation.
_, err := r.Eval(ctx)
if err != nil {
fmt.Printf("error: %s", err.Error())
os.Exit(1)
}
// Update the "before" histogram
for k, v := range m.All() {
bh.Histogram(k).Update(v.(int64))
}
m.Clear()
// Update input
input["x"] = 1
r.Update(
rego.Input(input),
)
// Evaluate again
_, err = r.Eval(ctx)
if err != nil {
fmt.Printf("error: %s", err.Error())
os.Exit(1)
}
// Update the "after" histogram
for k, v := range m.All() {
ah.Histogram(k).Update(v.(int64))
}
m.Clear()
}
fmt.Println("iterations:", iterations)
fmt.Println("--- Baseline (mean)")
printMetrics(bh)
fmt.Println("--- With Update() (mean)")
printMetrics(ah)
}
@patrick-east

Copy link
Copy Markdown
Author

Results from my macbook:

iterations: 5000
--- Baseline (mean)
histogram_timer_rego_input_parse_ns: 6242.012645914397
histogram_timer_rego_module_compile_ns: 127545.95428015564
histogram_timer_rego_module_parse_ns: 257651.36575875487
histogram_timer_rego_query_compile_ns: 54596.98249027237
histogram_timer_rego_query_eval_ns: 11885.103112840467
histogram_timer_rego_query_parse_ns: 110806.67217898833
--- With Update() (mean)
histogram_timer_rego_input_parse_ns: 6654.037937743191
histogram_timer_rego_module_compile_ns: 204425.4980544747
histogram_timer_rego_module_parse_ns: 217.61673151750972
histogram_timer_rego_query_compile_ns: 170.28891050583658
histogram_timer_rego_query_eval_ns: 11199.252918287937
histogram_timer_rego_query_parse_ns: 199.5408560311284

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment