Skip to content
Snippets Groups Projects
Commit 4b8f7c8b authored by Valery Kalashnikov's avatar Valery Kalashnikov Committed by Lyuben Penkovski
Browse files

Add Rego lang extension to work with the cache

parent 157721cf
No related branches found
No related tags found
2 merge requests!11Rego functions for cache write and read (set and get),!7Add Rego lang extension to work with the cache
package regoext
import (
"fmt"
"net/http"
"github.com/open-policy-agent/opa/ast"
"github.com/open-policy-agent/opa/rego"
"github.com/open-policy-agent/opa/types"
)
type CacheExt struct {
path string
}
func NewCacheExt(path string) *CacheExt {
return &CacheExt{path: path}
}
func (ce *CacheExt) GetCacheFunc() (*rego.Function, rego.Builtin3) {
return &rego.Function{
Name: "cache.get",
Decl: types.NewFunction(types.Args(types.S, types.S, types.S), types.A),
Memoize: true,
},
func(bctx rego.BuiltinContext, a, b, c *ast.Term) (*ast.Term, error) {
var key, namespace, scope string
if err := ast.As(a.Value, &key); err != nil {
return nil, err
} else if ast.As(b.Value, &namespace); err != nil {
return nil, err
} else if ast.As(c.Value, &scope); err != nil {
return nil, err
}
req, err := http.NewRequest("GET", ce.path+"/v1/cache", nil)
req.Header = http.Header{
"x-cache-key": []string{key},
"x-cache-namespace": []string{namespace},
"x-cache-scope": []string{scope},
}
if err != nil {
return nil, err
}
resp, err := http.DefaultClient.Do(req.WithContext(bctx.Context))
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf(resp.Status)
}
v, err := ast.ValueFromReader(resp.Body)
if err != nil {
return nil, err
}
return ast.NewTerm(v), nil
}
}
package regoext_test
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"code.vereign.com/gaiax/tsa/policy/regoext"
"github.com/open-policy-agent/opa/rego"
)
func TestCacheExt_GetCacheFunc(t *testing.T) {
expected := "{}"
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, expected)
}))
defer srv.Close()
fmt.Println(srv.URL)
cache := regoext.NewCacheExt(srv.URL)
r := rego.New(
rego.Query(`cache.get("open-policy-agent", "opa", "111")`),
rego.Function3(cache.GetCacheFunc()),
)
rs, err := r.Eval(context.Background())
if err != nil {
t.Errorf("unexpected error, %v", err)
return
}
bs, err := json.MarshalIndent(rs[0].Expressions[0].Value, "", " ")
if err != nil {
t.Errorf("unexpected error, %v", err)
return
}
if string(bs) != expected {
t.Errorf("expected %s, got %s", expected, string(bs))
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment