-
-
Notifications
You must be signed in to change notification settings - Fork 36
/
engine.go
79 lines (70 loc) · 1.88 KB
/
engine.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package main
import (
"fmt"
"reflect"
"github.com/golang/glog"
"github.com/google/cel-go/cel"
"github.com/google/cel-go/common/types/ref"
"github.com/segmentio/encoding/json"
"google.golang.org/protobuf/encoding/prototext"
"google.golang.org/protobuf/proto"
)
// evaluateRule ...
func evaluateRule(program cel.Program, inputs map[string]any) (ref.Val, error) {
// activation, err := cel.NewEnv()
// if err != nil {
// return nil, err
// }
out, _, err := eval(program, inputs)
return out, err
}
// eval ...
func eval(prg cel.Program,
vars any,
) (out ref.Val, det *cel.EvalDetails, err error) {
varMap, isMap := vars.(map[string]any)
fmt.Println("------ input ------")
if !isMap {
fmt.Printf("(%T)\n", vars)
} else {
for k, v := range varMap {
switch val := v.(type) {
case proto.Message:
bytes, errMarshal := prototext.Marshal(val)
if errMarshal != nil {
glog.Exitf("failed to marshal proto to text: %v", val)
}
fmt.Printf("%s = %s", k, string(bytes))
case map[string]any:
b, errMarshalIndent := json.MarshalIndent(v, "", " ")
if errMarshalIndent != nil {
return nil, nil, errMarshalIndent
}
fmt.Printf("%s = %v\n", k, string(b))
case uint64:
fmt.Printf("%s = %vu\n", k, v)
default:
fmt.Printf("%s = %v\n", k, v)
}
}
}
fmt.Println()
out, det, err = prg.Eval(vars)
report(out, det, err)
fmt.Println()
return out, det, err
}
// compile will parse and check an expression `expr` against a given
// environment `env` and determine whether the resulting type of the expression
// matches the `exprType` provided as input.
func compile(env *cel.Env, expr string, celType *cel.Type) *cel.Ast {
ast, iss := env.Compile(expr)
if iss.Err() != nil {
glog.Exit(iss.Err())
}
if !reflect.DeepEqual(ast.OutputType(), celType) {
glog.Exitf(
"Got %v, wanted %v result type", ast.OutputType(), celType)
}
return ast
}