Skip to content
Snippets Groups Projects
Commit 633fc781 authored by ale's avatar ale
Browse files

Add support for external values in scripts

No external values are currently defined or filled in, it's just
defining an "ext" variable placeholder.
parent 320ab20e
Branches
No related tags found
No related merge requests found
......@@ -7,6 +7,7 @@ import (
"sync"
"github.com/d5/tengo/script"
"github.com/d5/tengo/stdlib"
ippb "git.autistici.org/ai3/tools/iprep/proto"
)
......@@ -24,7 +25,7 @@ func LoadScript(path string) (*Script, error) {
}
var globalVars = []string{
"ip", "score", "counts", "interval",
"ip", "score", "counts", "interval", "ext",
}
func NewScript(src []byte) (*Script, error) {
......@@ -36,6 +37,10 @@ func NewScript(src []byte) (*Script, error) {
return nil, err
}
}
// Add available imports.
s.SetImports(stdlib.GetModuleMap("math", "times"))
c, err := s.Compile()
if err != nil {
return nil, err
......@@ -53,11 +58,12 @@ func buildIPMap(ip string, m ippb.Map) map[string]interface{} {
return out
}
func (script *Script) RunIP(ctx context.Context, ip string, m ippb.Map, intervalSecs float64) (float64, error) {
func (script *Script) RunIP(ctx context.Context, ip string, m ippb.Map, intervalSecs float64, ext map[string]interface{}) (float64, error) {
c := script.compiled.Clone()
c.Set("ip", ip)
c.Set("score", 0.0)
c.Set("interval", intervalSecs)
c.Set("ext", ext)
if err := c.Set("counts", buildIPMap(ip, m)); err != nil {
return 0, err
}
......
......@@ -22,7 +22,7 @@ score = counts["test"] / 2 + counts["test2"]
m.Incr("test2", "1.2.3.4", 2)
m.Incr("test2", "2.3.4.5", 3)
score, err := s.RunIP(context.Background(), "1.2.3.4", m, 3600)
score, err := s.RunIP(context.Background(), "1.2.3.4", m, 3600, nil)
if err != nil {
t.Fatalf("runScript: %v", err)
}
......
......@@ -88,7 +88,7 @@ func (s *Server) GetScore(ctx context.Context, req *ippb.GetScoreRequest) (*ippb
return nil, status.Errorf(codes.Unavailable, "%v", err)
}
score, err := s.Script().RunIP(ctx, req.Ip, m, s.horizon.Seconds())
score, err := s.Script().RunIP(ctx, req.Ip, m, s.horizon.Seconds(), nil)
if err != nil {
return nil, status.Errorf(codes.Internal, "%v", err)
}
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment